Compare commits

..
Author SHA1 Message Date
9a1c0919e4 TRIM and EXTEND take what a block reference draws as edges (#3569) (#3739)
* TRIM and EXTEND take what a block reference draws as edges (#3569)

A block reference chosen as a cutting or boundary edge, or met when every
object is an edge, gave no edge, so nothing was trimmed or extended at
it. The objects a reference draws are now edges, nested references
expanded and each placed by the references above it, giving what the same
object gives outside a block. Parts that are not drawn (hidden, on a layer
that is off or frozen) and the reference's own attributes are not edges.

* Edges that run on inside a block reference run on in drawing units (#3569)

* A proxy is an edge by the graphics it draws (#3569)

* An edge in a block reference keeps its direction at any scale (#3569)

* One bound for the whole look for TRIM and EXTEND edges in block references (#3569)

Each block reference started the bound on the objects visited inside it
anew, so a look at every reference of a space (Quick mode, on every hover
and fence preview) had no bound as a whole. The look now starts one count
at MAX_BLOCK_LEAVES and every reference spends from it, as a snap query
does. References reached after the count is spent give no edges inside
them.

* A proxy's graphics in a block reference count toward the bound of the look for edges (#3569)

A proxy inside a block came to TRIM and EXTEND as one object and spent
one count, while the look takes every graphic it draws, in every
reference. It now spends one count for each graphic it draws as well, so
references to a block whose proxy draws thousands of graphics stay inside
the same bound.

* Every graphic of a proxy in a block reference counts toward the bound, drawn or not (#3569)

The count was of the graphics that are drawn, taken by going through all
of them, so hidden graphics were gone through in every reference without
spending anything. The length of the list is charged now, before any
graphic is looked at.

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
Co-authored-by: FredApps <FredApps@users.noreply.github.com>
2026-12-04 08:04:57 +01:00
3fb4b51f0f Selected annotative objects show their other scales faded (SELECTIONANNODISPLAY) (#1379)
* Annotative objects keep a position per scale; ANNORESET synchronizes them

An annotative object that supports several scales can now sit somewhere
else at one of them, as in AutoCAD: its position grip moves it at the
current annotation scale only, MOVE/ROTATE/SCALE/MIRROR/paste/CHSPACE move
every scale, and ANNORESET puts every scale back where the current one is
(it was a no-op). The offset is kept per scale name (Common::anno_moves)
and applied where an object is drawn at a scale (anno_placed), so drawing,
extents, explode and grips all see it. Grips now show where the object is
drawn at the current scale; a shape grip's edit is taken back to paper size.

What moves per kind: text, MText and block references as a whole; a
multileader's landing and content (arrowheads stay); a dimension's text.

DXF/DWG: each scale context is written at the object's position at that
scale, and a context placing the object elsewhere reads back as its offset.

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

* DXF: an annotative multileader has annotation scale enabled (293)

The MULTILEADER entity's 293 after its CONTEXT_DATA block is the DXF
reference's "Enable Annotation Scale". CADCraft wrote 0, so AutoCAD kept
the multileader's per-scale contexts (and showed each scale's position)
but its ANNORESET passed the multileader over. With 293 = 1, as AutoCAD
writes for its own annotative multileaders, ANNORESET at either scale
moves the other context to the current scale's position.

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

* Annotative grips and ANNORESET in a viewport use the viewport's scale

In MSPACE the renderer draws model space at the active viewport's scale,
while grips, grip stretches, the hot-grip preview, grip dimensions and
ANNORESET looked up the object at CANNOSCALE: with the two different, grips
sat on another scale's representation and a position grip moved the wrong
scale. They now take the viewport's scale (`DocState::anno_view`,
`Drawing::anno_draw_in`); CANNOSCALE still applies in model space and on
paper outside a viewport.

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

* Annotative scales: import Vec2 after upstream's explicit-import cleanup

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

* Selected annotative objects show their other scales faded (SELECTIONANNODISPLAY)

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

* Docs: SELECTIONANNODISPLAY in the annotative scaling and selection rows

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

* SELECTIONANNODISPLAY: a viewport zoom rebuilds the faded scales; docs rows

The canvas keyed the faded copies of the selection on the active viewport but
not its scale, and an unlocked viewport's zoom changes the scale without a new
revision, so the copies stayed at the old scale's set. The scale is now part
of the key (`DocState::anno_view`, also used by `selection_anno_others`).

ui-parity.md: the duplicate Selection cycling and Selection preview rows a
merge brought back are gone; SELECTIONANNODISPLAY is on the existing row.

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

* Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them)

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

* Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them)

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

* io: dxf_anno uses craft_dxf, as main's DXF crate now is

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

* Tests: the DWG annotation scale round trip waits for craft-libs#2005

Without the bridge's annotation context conversion, a text context read back
from a DWG has its fields from the wrong groups (at the origin), which per-scale
positions read as a move. Ignored until the pinned craft-dwg has the conversion.

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

* Tests: the DWG annotation scale round trip waits for craft-libs#2005

Without the bridge's annotation context conversion, a text context read back
from a DWG has its fields from the wrong groups (at the origin), which per-scale
positions read as a move. Ignored until the pinned craft-dwg has the conversion.

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

* fmt: dxf_anno's craft_dxf import in order

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

* fmt: dxf_anno's craft_dxf import in order

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

* Annotative positions: main's text editor box and extents take the placed object (AnnoDraw::Scaled carries its offset)

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

* Select: a blank MText frame is where its annotation scale places it (main's AnnoDraw use, with the offset)

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

* Options: Reset puts SELECTIONANNODISPLAY back too (main's reset test)

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

* Selection: the faded other-scale copies of a selection share one budget

The cap on selected objects didn't bound the copies: each object could still
make one per scale it supports before any was drawn. anno_others now takes
from a budget, checked before each copy is made, and a selection shares one
(MAX_ANNO_FADED).

FredApps on #1379.

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

* Tests: the annotative position tests join the engine's test binary (AGENTS.md rule 30)

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

* Tests: the selection scale display tests join the engine's test binary (AGENTS.md rule 30)

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

* DWG: per-scale positions travel in CADCraft's record; main's annotation_scales round trip runs again

A DWG save writes no annotation scale contexts while the bridge can't convert
them (storytold/craft-libs#2005), so an object moved at one scale alone would
lose that move through DWG. CADCraft's annotative record now carries each
object's moves next to its scales (only for scales it keeps, finite, at most
MAX_SCALES), as it does for formats before 2007.

The roundtrip/dwg annotation_scales test this PR had marked ignored (main's
own test) runs again, unchanged, and passes; the multileader moved-at-one-scale
DWG test runs too, through the record.

FredApps on #1362 (rule 31).

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

* Keep annotative I/O fixture at normal text orientation

* Tests: an unlimited budget is a local, not usize::MAX.clone()

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

---------

Co-authored-by: Cody Vogt <18035288+codyvogt@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: FredApps <FredApps@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-04 07:54:00 +01:00
3825b49f9e Save: refuse to save over a drawing another program changed on disk (#3600)
* Save: refuse to save over a drawing another program changed on disk

CADCraft keeps no file open, so another program (or another CADCraft) saving
the same file in between was silently replaced by the next save. The drawing
now remembers a stamp (length and hash) of what its file held when it was
read or last written here, and QSAVE/SAVEAS onto that file refuse when it
changed; `overwrite: true` replaces it anyway. A file that is gone, a drawing
never read from that file, and saves under another name are not checked.

Part of #540.

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

* Save: the disk check knows a file under another spelling, and saves past the read cap

Review follow-ups: a save onto the drawing's own file named another way
(`./plan.dxf`, a relative or absolute path, a link) is checked too, and a
file this session wrote larger than the read cap is compared up to its own
length instead of counting as changed.

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

* Save: compare the file only where the automation roots allow, and say when it could not be checked

With automation roots in force, a save outside the write root is now refused
by the roots before the file there is compared, and the drawing's own path
is resolved only where it may be read (AGENTS.md rule 18). Before, the
comparison read the target first and its refusal said whether a file outside
the roots had changed.

A file that could not be read is no longer reported as saved by someone
else: the refusal says it may have changed and could not be checked.

The tests move into the engine's integration harness (tests/it, rule 30),
with a new case for the roots.

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

* GUI: ask before a save replaces a drawing another program changed

A user's save over the drawing's own file, after another program changed it,
stopped with the engine's refusal, which says `overwrite: true` saves anyway:
a user at the GUI has no way to pass that (rule 15). File > Save and its
shortcut, Save As onto the same file, Save in the close prompt and Save Anyway
in the lossy-save warning now ask instead: Save As... / Cancel / Overwrite.
Overwrite repeats that one save with `overwrite: true`; the next save compares
again. A file that could not be read to compare gets its own wording.

The decision moves into `cmd::file::on_disk`, which the engine's refusal and
the GUI both use, so the roots are still checked before the file is compared
(rule 18). Programmatic saves keep the refusal.

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

* GUI: Overwrite saves only to the file the question named

The changed-file question keeps the path it warned about, but its QSAVE ran
against the drawing's file at the time of the answer. A save under another
name while the question was up (the control channel, a script) moved the
drawing, and Overwrite then replaced that other file without a check. Now
Overwrite saves nothing when the drawing's file is no longer the one the
question named, and says to save again. SAVEAS names its file, so it was
already bound to it.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-04 07:52:47 +01:00
e3feeacabb GETVAR at the command line asks for a name and shows its value (#3273) (#3275)
* GETVAR at the command line asks for a name and shows its value (#3273)

GETVAR had no command-line form, so typing it (GETVAR DIMSCALE) ran it with no name and it said
only that `name` was required. It now prompts "Enter variable name", as SETVAR does, and
echoes NAME = value (or that the variable is unknown), changing nothing. The command's JSON
form is unchanged.

* CMDNAMES and CMDACTIVE count the command a transparent one runs inside

While 'GETVAR (or any transparent command) read its input, the outer command was only
suspended, so CMDNAMES read "" and CMDACTIVE 0. They now name it (LINE'PAN while a nested
command prompts) and set CMDACTIVE's transparent bit, as AutoCAD does.

---------

Co-authored-by: FredApps <FredApps@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-04 07:37:59 +01:00
56b496d9e8 fix(engine): DIMRADIUS, DIMDIAMETER and DIMJOGGED take a circle or arc inside a block (#1967) (#2483)
* fix(engine): DIMRADIUS, DIMDIAMETER and DIMJOGGED take a circle or arc inside a block

Picking a circle or arc that belongs to a block reference said "Object
selected is not a circle or arc." AutoCAD measures it. These commands now
look inside the reference picked (nested references too) for the object
under the cursor, through the walker object snaps already use, and take
it when it is a circle or arc the reference scales evenly. A block's line,
or a circle drawn as an ellipse by an uneven scale, is still refused.

Part of #1967

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

* Rank nested picks by the geometry drawn

A circle that a reference scales unevenly was measured as a circle of its
average radius, so it could take a pick that lands on a real circle next
to it, and the first of two equally near objects always won. Each object
in the reference is now measured on its exactly placed primitives (an
unevenly scaled circle as its ellipse, as object snaps do), a circle is
recognised by the same similarity test, and at equal distance a circle
or arc wins.

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

* Use the shared pick aperture; leave pick_at as it was

curves.rs already has pick_aperture; the copy in annotate/common.rs is
gone, and pick_at is back to its original text, which keeps this change
clear of #2477's edit there.

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

* Measure nested picks as any pick measures them

Objects inside the picked reference are now measured with the hit test
every pick uses, on the object placed by the reference: text and tables
inside their box, a SOLID or solid hatch inside its fill, a ray only
ahead of its start. A curve the reference scales unevenly still goes by
its exactly placed primitives. Layers frozen in the active layout
viewport are left out, as they aren't drawn there.

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

* test(dim): a circle in a mirrored reference is taken, unassociated

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

* test(dim): the text and SOLID picks are refused before cancel, with a real SOLID in the block

The SOLID case used a LISP entmake that made nothing, so it tested only that an unfinished
DIMRADIUS makes no dimension. It now draws the SOLID with the solid command, checks the block
holds it, and checks DIMRADIUS refuses the pick and still asks for an arc or circle.

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

* fix(dim): a zero-radius circle picked directly is refused too, as one in a block is

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

---------

Co-authored-by: austin62jake <340374338+austin62jake@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: FredApps <FredApps@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-04 07:37:10 +01:00
Dimitrios VidalisandFredApps c6a6a3ab96 -PLOT and -PAGESETUP ask for their options at the command line (#3433) (#3751)
* -PLOT and -PAGESETUP ask for their options at the command line (#3433)

Typed -PLOT and -PAGESETUP started the dialog commands and asked nothing,
so a script or (command ...) could not set a layout's paper or plot it.
They are now commands of their own that ask the plot and page setup
options one question at a time and then run the plot and pagesetup
commands with the answers. An answer the engine has no option for is
refused and asked again; nothing changes before the last answer.

* -PLOT and -PAGESETUP ask again at the question for what the plot or the page setup would refuse or change (#3433)

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-04 07:21:38 +01:00
Elvis33LEandFredApps 26bd9f171d ci(tests): consolidate 43 engine and ui-egui integration tests into tests/it (#3736)
* ci(tests): consolidate 43 engine and ui-egui integration tests into tests/it

* fix(tests): keep ui-egui set_io tests in separate binaries

* test: keep options_followups and cursor_contrast in their own binaries

options_followups documents its own-binary requirement (SAVETIME and
SAVEFILEPATH are process-wide), and cursor_contrast's Canvas fixture resets
the shared canvas theme in Drop, which can race the selection-highlight
test's set-then-read between setting and assertion when both share one
binary. Both move back out of tests/it so their assertions keep their
isolation; the consolidation keeps every other suite.

---------

Co-authored-by: FredApps <FredApps@users.noreply.github.com>
2026-12-04 06:58:48 +01:00
FredApps c556983869 Merge pull request #3645 from storytold/chore/craft-libs-9949e08
Repin craft-libs and preserve DWG geometry with acadrust 0.6.9
2026-12-04 06:50:56 +01:00
FredApps 2d08ea7b74 Cover both render setting class versions through SAVEAS and QSAVE 2026-12-04 06:07:12 +01:00
FredApps 976d2357ff Merge pull request #3825 from storytold/fix/main-locked-png
Fix locked PNG dependency for muda
2026-12-04 06:01:58 +01:00
FredApps 4dc420ab90 Disambiguate muda PNG dependency in lockfile 2026-12-04 05:36:12 +01:00
FredApps 9d85a971f4 Treat implicit and explicit ByBlock dimension linetypes alike 2026-12-04 05:35:56 +01:00
FredApps 40d4098375 Preserve native viewport lighting across DXF and DWG exports 2026-12-04 05:11:51 +01:00
FredApps a24fb6f930 Use the shared winit fork for Wayland window activation 2026-12-04 04:52:40 +01:00
FredApps 586f3d38b5 Pin CADCraft to the merged DWG bridge and matching fork graph 2026-12-04 04:45:07 +01:00
FredApps d327547208 Preserve repeated viewport lighting tags and limit the DWG test to supported targets 2026-12-04 04:34:12 +01:00
FredApps 246aaf35de Canonicalize default viewport lighting as a unit 2026-12-04 04:25:12 +01:00
FredApps c15cec8a98 Keep exact circle angles and avoid division on narrow ellipses 2026-12-04 04:21:02 +01:00
FredApps 5586822f8a Read hatch ellipse angles as circular rays 2026-12-04 04:20:10 +01:00
FredApps f48ae711e1 Use saved OLE frame headers in roundtrip fixtures 2026-12-04 04:18:08 +01:00
FredApps f78ca4e722 Omit default DWG viewport style and icon settings 2026-12-04 04:18:08 +01:00
FredApps 52ab5d2549 Check round-tripped proxy classes and interpolated spline geometry 2026-12-04 04:18:08 +01:00
FredApps 3b95d0510c Preserve table title suppression and render settings across file versions 2026-12-04 04:18:08 +01:00
FredApps 07bec9df31 Read DWG hatch angles once with the 0.6.9 decoder 2026-12-04 04:18:08 +01:00
FredApps e785adb63d Merge remote-tracking branch 'origin/main' into review/cadcraft-repin-3645-20261204 2026-12-04 04:14:30 +01:00
FredApps c870f83900 fix(engine): use placed annotative text in selection (#3808) 2026-12-04 10:02:38 +07:00
FredApps 0be750a98a Reconcile the shared dependency repin with current CADCraft main 2026-12-04 03:58:29 +01:00
aiongg 20ad85efc4 Merge pull request #3772 from davidmann4/feat/macos-cli-in-app
packaging(macos): ship cadcraft-cli inside CADCraft.app
2026-12-03 18:53:10 -05:00
aiongg d9f7de77e0 Merge pull request #3770 from davidmann4/feat/agents-open-window
feat(automation): agents in the open window through the ArtCraft Launcher's switch
2026-12-03 18:52:55 -05:00
Dimitrios Vidalis 6681531546 refactor(render,io): move the dimension block generator from the DXF writer to render (#2421) (#3777)
`dim_block_entities` makes the contents of a dimension's anonymous `*D`
block from the dimension's drawn geometry. It lived in the DXF writer
(`crates/io/src/dxf_write/blocks.rs`) and only the writer could call it.
It moves to `crates/render/src/dim_block.rs`, beside the geometry it reads,
and is exported as `cadcraft_render::dim_block_entities`. The writer calls
it there.

The body is unchanged: the three `cadcraft_render::` paths in it lose their
prefix and `pub(super)` becomes `pub`. No behaviour changes.
2026-12-03 15:36:36 +01:00
97fed2970c Annotative objects keep a position per scale; ANNORESET synchronizes them (stacked on #1370) (#1373)
* DXF: a block record keeps its annotative flag and uniform scaling

A BLOCK_RECORD's AcadAnnotative xdata (references to the block are
annotative) was dropped on reading, AcadAnnotative being among the
applications CADCraft writes itself, and never written: a saved drawing's
annotative blocks came back plain, and AutoCAD then scaled their references
by units instead of the annotation scale (a metre block showed Unit factor
1000 and Scale 0.005). Group 281 (scale uniformly) was dropped too. Both are
now read into the block (`Block::annotative`, `Block::scale_uniformly`) and
written back.

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

* DXF: a block reference keeps its annotation scale contexts, following the reference

A reference to an annotative block holds its scale at each annotation scale in
its extension dictionary (AcDbContextDataManager, ACDB_ANNOTATIONSCALES).
CADCraft dropped it with the other annotation contexts it means to write from
its model, but it models none for references: with the block's annotative
flag kept, AutoCAD then scaled the reference once more by the current
annotation scale (5 became 25). A reference's contexts are now kept, and
refreshed on writing: each moves, turns and scales by what the reference did
since the file was read (its default context was the reference then), so a
reference left alone keeps them as read. The scales they name are found by
name (SCALE group 300), as the scale list is written again from the model.

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

* Block literals in tests take scale_uniformly; a test helper's lifetime is elided

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

* DXF: a block reference's attributes keep their annotation scale contexts

The attributes of an annotative reference hold their own contexts (insertion
and alignment points and rotation at each annotation scale, under the ATTRIB's
extension dictionary), dropped like the reference's were. CADCraft writes
attributes with new handles, so their extension dictionaries are now kept by
attribute, as its reference's handle and tag, and put back on the attribute
written with that reference and tag. On writing each context keeps its own
place in the block at its scale, moves by what the attribute did in the block
since (its default context then, the attribute now), and is placed by the
reference's context for that scale as it is now: a reference left alone keeps
them as read; one moved, turned or scaled carries them exactly.

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

* DWG: block reference annotation contexts keep their rotation, insertion and scales

AutoCAD's DXF has a block reference context's rotation (50, degrees),
insertion point and scales straight after its scale (340). acadrust 0.6.4
reads them after an AcDbBlkRefObjectContextData marker, with the rotation in
radians, and without the marker read zeros: a drawing saved as DWG had every
annotative reference at scale 0 at its other annotation scales, where
AutoCAD then drew nothing. The DWG bridge now gives acadrust the contexts its
way (marker, radians) and turns its DXF back into AutoCAD's (no marker,
degrees).

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

* DXF: kept reference contexts follow the drawing's and the reference's scales

A kept block reference or attribute context whose SCALE is no longer in the
drawing's list is not written (its dictionary entry goes with it), so no
context points at a null scale. A reference CADCraft's model keeps annotative
has a context for exactly the scales it supports: contexts of scales it
dropped go, and one per new scale is made from the default context, scaled
by the ratio of the scales about the reference's insertion point. One
context stays the default.

Attributes are identified by reference, tag and their place among the
reference's attributes with that tag, so two attributes with one tag keep
their own extension dictionaries and contexts.

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

* DXF: new reference contexts come from one whose scale is still written

When the default context's scale had been deleted from the drawing's list,
a reference CADCraft keeps annotative got no new contexts for its added
scales; the template is now its default context, else its first, among
those whose SCALE is written.

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

* DXF: kept reference contexts follow the reference as read; one default rule

A kept context is brought up to date by what its block reference did since
the file was read. That baseline was the default context, which needn't be
where the reference was (an unchanged save then moved every context); the
reference and its attributes as read are now kept (`Foreign::placements`)
and used, the default context only for data without them.

A context's own offset from the reference now scales and mirrors with it
(back into the reference's frame then, scaled, turned to its frame now), not
only turns.

The default context is the one whose first 290 group is 1 everywhere (an
attribute context has a later 290 of its own).

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

* DXF: new reference contexts take handles above every handle in use

Upstream now believes handles above 2^48 (AutoCAD writes them), so new
annotation contexts can no longer take stand-in handles from 2^48 up: they
start above the written handles, $HANDSEED, the kept objects and their targets.

Test: a drawing whose reference sits at 2^48 + 1 gains a scale and every
written handle stays unique (red with the old 2^48 base).

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

* DXF: an attribute as read is found by its tag and place, and keeps its rotation

A kept attribute placement was looked up by its index among the reference's
attributes now, which differs once they are reordered or replaced (ATTSYNC).
It is now found by tag and place among that tag, like the attribute's contexts.
The rotation change is measured from the attribute as read too, not from its
default context, so an unchanged save no longer turns every context when the
ATTRIB (at the current scale) and the default context differ.

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

* DXF: the kept-context code in read and finish moves into helpers

main now denies cognitive_complexity over 30 and too_many_arguments over 7.
This PR's additions took read to 32 and finish to 31, and retained_objects
to 8 arguments: the block-reference and attribute bookkeeping now lives in
insert_handles, of_insert, keep_attrib_dictionaries, keep_placements,
written_attribs and refreshed_contexts, and retained_objects takes the root
and its entries as one pair.

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

* DXF/DWG: annotative text, MText and dimensions keep their annotation scales on save

AutoCAD keeps an annotative object's size at each annotation scale it
supports in scale contexts (extension dictionary AcDbContextDataManager,
ACDB_ANNOTATIONSCALES, one *OBJECTCONTEXTDATA_CLASS per scale), with the
object's own groups at its default scale. CADCraft dropped AutoCAD's contexts
on read, so those objects opened as plain text at the default scale's size
and lost their scales on save; its own annotative objects went out with only
CADCraft's private record, so AutoCAD showed them at one size at every scale.

Text, MText and dimensions in model space and layouts are now written at
their default scale (the current one when supported) with AcadAnnotative
xdata and a context per scale: text insertion and alignment points, MText
width and columns, a dimension's text position and a *D block with its
geometry at that scale (sharing the DIMASSOC's extension dictionary when
there is one). Scales missing from the list are added. Reading takes the
scales from the contexts and the sizes back to paper size. Files before the
2007 format keep CADCraft's record as before. The DWG bridge gives acadrust
text contexts its way (marker, radians) and dimension contexts' blocks as
BLOCK_RECORD handles, and turns them back.

Checked in AutoCAD: it opens the output, keeps both contexts of each
object, and draws the dimension at 0.18 / 9.0 text height at 1:1 / 1:50.

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

* DXF test: a justified text's start point is recomputed on save (since #1062)

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

* DXF: only annotative dimensions get a *D block per scale

Annotative text and MText went through the dimension block planning too and
left one empty anonymous *D block per scale in every saved file. The hostile
contexts test now saves, opens the file again and checks the scales and that
every context names a written SCALE.

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

* DXF/DWG: annotative multileaders keep their annotation scales on save

An annotative multileader's scale context (ACDB_MLEADEROBJECTCONTEXTDATA_CLASS)
holds the multileader's whole CONTEXT_DATA body at that scale: overall scale
(40), text height, arrowhead size, landing gap, content position and the
leaders. CADCraft dropped AutoCAD's on read and wrote none, so annotative
multileaders came back plain at the default scale's size, and AutoCAD showed
CADCraft's at one size at every scale.

Multileaders now go through the annotation scale contexts like text, MText
and dimensions: written at the default scale with AcadAnnotative xdata and a
context per scale (the entity writer's CONTEXT_DATA at that scale, with its
overall scale and landing gap set), read back at paper size. The DWG bridge
gives acadrust the CONTEXT_DATA{ group it reads the context after, and takes
acadrust's braces and marker out again.

Checked in AutoCAD: its own annotative multileader reads back at 1:2 and
1:10 at paper size, and the saved file reopens with text 0.18 / 0.9 as
before; one made in CADCraft opens with text 2.5 / 25 at 1:1 / 1:10, the text
moved with the scale.

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

* DXF: the current annotation scale is AutoCAD's CANNOSCALE variable

AutoCAD keeps the current annotation scale in the named object dictionary's
AcDbVariableDictionary, as a DICTIONARYVAR CANNOSCALE naming the scale.
CADCraft read only its own record, so AutoCAD's drawings opened at 1:1
whatever their scale (annotative objects then showed at their first scale),
and the variable was written back as read, so AutoCAD reopened a drawing at
its old scale after CADCraft changed it.

The variable is read when the scale is in the list (after CADCraft's record:
AutoCAD keeps that record as it was, so the variable is the newer one), and
the kept variable is written with the drawing's current scale. Annotative
objects are written at that scale.

Checked in CADCraft and AutoCAD: an AutoCAD drawing at 1:2 opens at 1:2;
switched to 1:10 and saved as DXF and DWG, AutoCAD opens both at 1:10.

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

* DXF test: an annotative multileader has no *D block

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

* DXF: AutoCAD's CANNOSCALE names the scale the contexts are written at

A CANNOSCALE naming none of the drawing's scales wrote that name to the
variable dictionary while the default contexts were written at 1:1; the
variable now names the resolved scale too.

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

* DWG: a multileader context's body closes (301 }) before the next record

As acadrust writes it; its reader stops at the next record either way.

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

* Annotative objects keep a position per scale; ANNORESET synchronizes them

An annotative object that supports several scales can now sit somewhere
else at one of them, as in AutoCAD: its position grip moves it at the
current annotation scale only, MOVE/ROTATE/SCALE/MIRROR/paste/CHSPACE move
every scale, and ANNORESET puts every scale back where the current one is
(it was a no-op). The offset is kept per scale name (Common::anno_moves)
and applied where an object is drawn at a scale (anno_placed), so drawing,
extents, explode and grips all see it. Grips now show where the object is
drawn at the current scale; a shape grip's edit is taken back to paper size.

What moves per kind: text, MText and block references as a whole; a
multileader's landing and content (arrowheads stay); a dimension's text.

DXF/DWG: each scale context is written at the object's position at that
scale, and a context placing the object elsewhere reads back as its offset.

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

* DXF: an annotative multileader has annotation scale enabled (293)

The MULTILEADER entity's 293 after its CONTEXT_DATA block is the DXF
reference's "Enable Annotation Scale". CADCraft wrote 0, so AutoCAD kept
the multileader's per-scale contexts (and showed each scale's position)
but its ANNORESET passed the multileader over. With 293 = 1, as AutoCAD
writes for its own annotative multileaders, ANNORESET at either scale
moves the other context to the current scale's position.

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

* Annotative grips and ANNORESET in a viewport use the viewport's scale

In MSPACE the renderer draws model space at the active viewport's scale,
while grips, grip stretches, the hot-grip preview, grip dimensions and
ANNORESET looked up the object at CANNOSCALE: with the two different, grips
sat on another scale's representation and a position grip moved the wrong
scale. They now take the viewport's scale (`DocState::anno_view`,
`Drawing::anno_draw_in`); CANNOSCALE still applies in model space and on
paper outside a viewport.

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

* Annotative scales: import Vec2 after upstream's explicit-import cleanup

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

* Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them)

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

* Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them)

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

* Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them)

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

* Annotative text contexts test: Dimension gains insertion_point on main

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

* io: dxf_anno uses craft_dxf, as main's DXF crate now is

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

* io: dxf_anno uses craft_dxf, as main's DXF crate now is

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

* io: dxf_anno uses craft_dxf, as main's DXF crate now is

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

* Tests: the DWG annotation scale round trip waits for craft-libs#2005

Without the bridge's annotation context conversion, a text context read back
from a DWG has its fields from the wrong groups (at the origin), which per-scale
positions read as a move. Ignored until the pinned craft-dwg has the conversion.

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

* fmt: dxf_anno's craft_dxf import in order

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

* fmt: dxf_anno's craft_dxf import in order

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

* fmt: dxf_anno's craft_dxf import in order

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

* io: dxf_anno reads main's borrowed DXF sections (SectionRef)

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

* Annotative positions: main's text editor box and extents take the placed object (AnnoDraw::Scaled carries its offset)

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

* DXF writer: annotation scale planning in two helpers (main's tags_kept_for passed the complexity limit)

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

* Select: a blank MText frame is where its annotation scale places it (main's AnnoDraw use, with the offset)

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

* DXF: a block reference moved in elevation takes its contexts along, at their own heights

block_contexts compared the reference with the one read in X and Y only, so a
reference moved only in Z kept its contexts at their old heights; and any
other change set every context's group 30 to the reference's Z, losing a
context's own height. Z is part of the change check now, and each context
keeps its offset from the reference as read, scaled with the reference's Z
scale as X and Y follow theirs.

FredApps on #1244.

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

* Tests: the annotative block context tests join the io test binary (AGENTS.md rule 30)

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

* Tests: the annotative text context tests join the io test binary (AGENTS.md rule 30)

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

* Tests: the annotative position tests join the engine's test binary (AGENTS.md rule 30)

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

* DWG: block reference contexts and the block's annotative flag stay DXF-only until the bridge converts them

The DWG bridge doesn't carry annotation scale contexts into a DWG yet
(storytold/craft-libs#2005): the DWG reader read them back as zeros, a
reference at scale 0 at its other scales. A save through the bridge now
leaves the kept block reference and attribute contexts out, as before they
were kept, and the block's AcadAnnotative flag too (without its references'
contexts AutoCAD would scale them by the annotation scale once more). DXF
keeps both.

The DWG round-trip test that waited for craft-libs#2005 (ignored,
a_reference_s_contexts_survive_dwg) is replaced by one that runs: a DWG save
leaves the contexts out and the reference reads back at its own scale. The
round trip of the contexts through DWG follows once the bridge converts
them.

FredApps on #1362 (rule 31).

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

* DWG: annotative text, MText and dimensions keep their scales in CADCraft's record until the bridge converts contexts

A save through the DWG bridge writes no annotation scale contexts now: the
bridge doesn't convert them yet (storytold/craft-libs#2005), so CADCraft's own
record carries the scales, as for an older format. DXF from 2007 on writes the
contexts as before.

The DWG test that waited for craft-libs#2005 (ignored) now runs: the scales,
paper height and rotation come back through DWG from the record, and the DWG
holds no contexts. The contexts' own round trip through DWG follows with the
bridge.

FredApps on #1362 (rule 31).

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

* Tests: the multileader's DWG round trip runs, through CADCraft's record

The multileader DWG test that waited for craft-libs#2005 (ignored) now runs:
its scales and paper text height come back through DWG from CADCraft's own
record, and the DWG holds no multileader contexts. The contexts' round trip
through DWG follows with the bridge.

FredApps on #1362 (rule 31).

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

* DWG: per-scale positions travel in CADCraft's record; main's annotation_scales round trip runs again

A DWG save writes no annotation scale contexts while the bridge can't convert
them (storytold/craft-libs#2005), so an object moved at one scale alone would
lose that move through DWG. CADCraft's annotative record now carries each
object's moves next to its scales (only for scales it keeps, finite, at most
MAX_SCALES), as it does for formats before 2007.

The roundtrip/dwg annotation_scales test this PR had marked ignored (main's
own test) runs again, unchanged, and passes; the multileader moved-at-one-scale
DWG test runs too, through the record.

FredApps on #1362 (rule 31).

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

* DXF writer: the DWG bridge's context choice in contexts_for (finish passed the complexity limit)

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

* Keep annotative I/O fixture at normal text orientation

---------

Co-authored-by: Cody Vogt <18035288+codyvogt@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: FredApps <FredApps@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-03 15:30:30 +01:00
44fa197bcc Linux: native Wayland by default, with in-app window buttons on GNOME (#1853)
* Linux: native Wayland by default; CADCRAFT_X11=1 for XWayland

On a Wayland desktop CADCraft forced winit's X11 backend (XWayland)
whenever DISPLAY was set. The deb and rpm only recommend the X11
libraries, and without libxkbcommon-x11 winit panicked at startup:
"Library libxkbcommon-x11.so could not be loaded".

Run natively on Wayland instead: sharp at fractional scales, with
working input methods. File drops from the file manager work there too,
through storytold/winit's W15 patch. CADCRAFT_X11=1 opts into XWayland
as a fallback, and only when the X11 libraries load; otherwise it logs
what is missing and stays on Wayland. It is read with the other
variables in env.rs and replaces CADCRAFT_WAYLAND.
The deb and rpm recommend libxkbcommon-x11 (and rpm libX11-xcb) too.

Ported from WordCraft (storytold/wordcraft#3359).

* GNOME Wayland: draw the window buttons and resize edges in the app

GNOME's compositor offers no zxdg_decoration_manager_v1, so with native
Wayland it draws no frame for CADCraft. Where the protocol is missing,
the window opens without winit's frame and the app draws a title row as
GNOME's header bar: the drawing's name centred, and minimize, maximize
and close in the order GNOME's button-layout names (read once through
the XDG Desktop Portal). Thin zones along the window's edges resize it.
KDE, Sway, Hyprland, COSMIC and X11 keep the desktop's frame.

Options > Display > Use system title bar (OPTIONS key systemTitleBar)
brings back winit's frame at once. It is kept in workspace.json, which
is now read before the window opens. CADCRAFT_TITLEBAR=app or =system
overrides the detection. The new strings are translated in all 15
catalogs.

Ported from WordCraft (storytold/wordcraft#3361).

* Linux: decide the window frame from the backend winit runs on

On an X11-only session winit picks X11 without CADCRAFT_X11, so x11
stayed false and CADCRAFT_TITLEBAR=app drew the app's window buttons on
X11, whose window manager draws the frame. runs_on_x11 follows winit's
own choice (WAYLAND_DISPLAY or WAYLAND_SOCKET set and not empty).

* Linux: leave WAYLAND_SOCKET to winit; empty DISPLAY; TITLEBAR=app wins

Three CodeRabbit findings on #1853:

- The decorations probe connected with Connection::connect_to_env, which,
  given WAYLAND_SOCKET, takes that descriptor, removes the variable and
  closes it when the probe's connection drops, so winit had no Wayland
  connection left. The probe now connects only to WAYLAND_DISPLAY's
  socket (display_socket, found as wayland-client finds it); with only
  WAYLAND_SOCKET it doesn't probe and the desktop keeps the frame.
- An empty DISPLAY counted as an X display, so CADCRAFT_X11=1 forced X11
  with nothing to connect to. DISPLAY is now read as winit reads the
  Wayland variables: set and not empty.
- CADCRAFT_TITLEBAR=app chose the app's buttons, but a saved Use system
  title bar still kept winit's frame, at startup and in
  CadApp::draws_window_frame. Both now decide with app_draws_frame, which
  the override wins (CadApp::frame_forced), and Options doesn't offer the
  setting while it's overridden.

Tests: display_socket and forces_app (decorations), an empty DISPLAY
(main), and titlebar_app_overrides_the_saved_system_title_bar.

* i18n: window button and title bar rows for bs, ka, pl and vi

These catalogs arrived on main after this branch added "Minimize",
"Maximize", "Use system title bar" and its tooltip to the others, so
every catalog now has all four rows.

* Drop the parity-doc edits; the rows go in the PR description

AGENTS.md: PRs don't edit ROADMAP.md or docs/ui-parity.md.

---------

Co-authored-by: bmh129 <11478682+bmh129@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-03 15:07:20 +01:00
FredApps 36e8c31f0d Merge pull request #3781 from storytold/fix/metal-language-version-1631
macOS: compile shaders with the newest Metal version the system compiler accepts (#1631)
2026-12-03 07:35:05 +01:00
FredApps 5ab5e6f343 Merge pull request #3768 from storytold/stack/e6
Land 4 reviewed PRs (stack e6)
2026-12-03 06:45:42 +01:00
FredApps 8698649da1 Merge main into stack/e6
Conflict: crates/engine/tests/it/main.rs (both new test modules kept: legacy_sysvars and lisp_answer_by_frames).
2026-12-03 06:25:12 +01:00
FredApps a6add77c5a Drop #3580 from this landing
Reverts the Merge #3580 commit (0d70d25f, first parent) and the landing fix that moved its
tests into tests/it (4ecd4aed). #3580 is not ready (changes still requested on 9bbe7b69) and lands
on its own. #3601, #3497 and #3503 stay.
2026-12-03 05:45:02 +01:00
David MannandClaude Opus 5.5 db4f07655b fix(agents): the frame that starts the agent server schedules its first check
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 03:13:26 +01:00
David MannandClaude Opus 5.5 5c2a897abc fix(agents): a serving window schedules its next connection check
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 02:50:23 +01:00
David MannandClaude Opus 5.5 b760962907 fix(agents): survive a start race; a tab an agent used saves nothing
- A serving window publishes its connection again when the one the file
  names has closed (two windows that started together both serve).
- The AI Agents tab shown with agent folders in force refuses every save
  until the person shows it afresh, so a later unconfined pass (focus
  loss) can't commit what an agent typed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 02:22:10 +01:00
David MannandClaude Opus 5.5 489df47647 test(agents): the same-frame LISP test must see the request run; --control stays unconfined
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 02:03:43 +01:00
David MannandClaude Opus 5.5 23354c91f5 fix(agents): confine an agent's LISP slices from the same frame on; clearer refusal
- lisp_tick runs under the stored agent roots, so the slice right after
  the request that started the routine (same logic call) is held too.
- The AI Agents tab says saving waits until the agent's work has finished.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 01:52:46 +01:00
David MannandClaude Opus 5.5 901e5fb6fd fix(agents): review findings on the agent link
- mcp --when-closed: a typed parse error (ast-grep string-error).
- mcp honours --config-dir when it looks for the window.
- A second window with the same settings folder leaves the first one's
  connection alone and takes over once that window has closed.
- An agent's LISP routine that runs past its first slice stays held to the
  agent folders until it ends.
- The AI Agents settings refuse changes while agent folders are in force,
  so an agent can't widen them by clicking in Options.
- Docs: a usable write folder still allows reads; the test dir is reset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 01:37:37 +01:00
David MannandClaude Opus 5.5 16b3732b63 fix(agents): keep the agent folders in force for input an agent queued
ui.click, ui.key and ui.text are handled frames after the request, outside
its confinement; keep the agent's roots in force over logic and UI passes
until that input has gone through a UI pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 00:36:15 +01:00
David MannandClaude Opus 5.5 272dc5cecf feat(automation): agents in the open window through the ArtCraft Launcher's switch
While ArtCraft Launcher > Settings > AI agents names CADCraft, the open
window serves its control channel for agents (craft_automation's
AgentLink: token file, agent-connection.json, the switch, retries), and
plain `cadcraft-cli mcp` reaches it through the shared live client
(craft_control::agents::Live) with the challenge handshake; otherwise it
works headless as before.

- Agent requests in the window run inside the agent folders of the new
  Options > AI Agents tab (the shared Agents page), like headless roots;
  ui.render and ui.screenshot paths are checked too.
- The agent settings are saved in agent-settings.json for the CLI; no
  command changes them.
- `mcp --headless`, `--when-closed`; `--connect` deprecated for a release.
- New `agent_folders` tool.

Closes #3769.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 00:29:51 +01:00
David MannandClaude Opus 5.5 c6974ad9dd packaging(macos): ship cadcraft-cli inside CADCraft.app
The ArtCraft Launcher lists an app for AI agents only when <id>-cli sits
beside its executable, so on macOS CADCraft was left out. Copy the CLI
into Contents/MacOS and sign it before the bundle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:47:50 +01:00
David MannandClaude Opus 5.5 bf0936ff65 wip: agents in the open window through the ArtCraft Launcher's switch (#3769)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:07:55 +01:00
Tanish Manku 4ecd4aed42 Landing fix: #3580's tests join each crate's tests/it binary (rule 30) 2026-12-02 14:19:42 -07:00
Tanish Manku 636dd26f07 Merge #3503 2026-12-02 14:19:34 -07:00
Tanish Manku 0d70d25f07 Merge #3580 2026-12-02 14:19:23 -07:00
Tanish Manku 15c8926c97 Merge #3497 2026-12-02 14:19:16 -07:00
Tanish Manku 300a64f711 Merge #3601 2026-12-02 14:19:13 -07:00
Magzhan ZhakudaandClaude Opus 5.5 27a9b91f3c Vertex identifier tests: move into the io harness (tests/it)
AGENTS.md rule 30: one integration test binary per crate. The five cases
move unchanged into crates/io/tests/it/lwpolyline_vertex_ids.rs, registered
in main.rs under the same target guard the separate binary had.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 15:50:44 +05:00
Magzhan Zhakuda e48f8805a5 Merge remote-tracking branch 'origin/main' into fix/lwpolyline-vertex-ids
# Conflicts:
#	crates/doc/src/foreign.rs
2026-12-02 15:44:22 +05:00
FredApps 9bbe7b69a3 Merge remote-tracking branch 'origin/main' into yan-3580 2026-12-02 08:59:06 +01:00
FredApps 8cde239e64 Text Style: Apply writes only the fields the dialog changed; a refused number says why
Apply and the unsaved-changes Yes sent the whole staged style, so a change made to another
field of the style by another route since the edit began was written back over. They now send
only the fields that differ from the style as the first edit found it.

A refused height, width factor or oblique angle went back to its value without a word. The
dialog now says what the field accepts, in a live region, until an entry is accepted. The shared
expr_field is unchanged.
2026-12-02 08:58:58 +01:00
code-compliant 15c3c9564a Answer two review findings: continue text with a usable height, name annotative rows
Enter at TEXT's start point does not continue with a height that neither the last text nor TEXTSIZE can give. An annotative style's row says so in its accessible name, which starts with the visible style name. The Escape test for another window now fails if any control of the dialog takes the focus.
2026-12-02 10:37:25 +08:00
FredApps f288082ff3 Merge main into ACADVER fix, keeping shared test registration 2026-12-02 02:35:24 +01:00
code-compliant 0fd046c4c1 Keep a click on an editor over the drawing from leaving the keys with the dialog
The grace for a closed list's last focused item now applies only to a list that a key closed. A list that a click closed gives the focus to what was clicked, so a click on an editor over the drawing while a list was open takes the keys from the dialog at once.
2026-12-02 07:20:37 +08:00
code-compliant 7bd33b7ff1 Give a closed list's focus back only to a control that is still there and enabled
The focus owed to the control that opened a list or menu is given two passes after the list closed, once what the choice did has been drawn: to the control if it is still there and enabled, else to the chosen style. A button the choice turned off, a row it hid and a style it deleted no longer take the focus back. The dialog keeps the keys through the passes in which the closed list's last item still looks focused.
2026-12-02 07:05:34 +08:00
code-compliant 9ce7cde286 Put the focus on the chosen style after Delete from the style list's menu
The menu's Delete removes the row that held the focus, as the Delete button does, so the focus goes to the chosen style here too.
2026-12-02 06:39:51 +08:00
code-compliant 0cf540495f Put the focus on the chosen style when Apply, Set Current or Delete turns itself off
Each of the three buttons disables itself after it works, and egui drops the focus of a control that turns off, so a person using the keyboard was left with no focused control. The focus now goes to the chosen style.
2026-12-02 06:23:44 +08:00
code-compliant 6050f3c396 Let the window under the pointer decide who has the keys, even when a list is open
A press counts for the dialog only when the dialog is the topmost window under the pointer, takes nothing from an item of an open list or menu, and takes the keys from the dialog for any other window, the drawing or a bar. So a click on another window's title bar that closes an open list no longer leaves the next Escape with the dialog.
2026-12-02 06:07:15 +08:00
code-compliant 3371028cdf Add a Rename button to Text Style and tighten who has the keys
Rename is now a button beside Delete, so it can be reached by the keyboard, and its field takes the focus when it shows; the focus returns to the styles when the rename ends. A choice made by key in the style filter list and the font style list closes the list. The dialog counts focus on a foreground layer as its own only while a list or menu is open, so an editor over the drawing keeps its Escape; and a click counts only when the dialog is the topmost window under the pointer, so a window over the dialog does not give it the keys.
2026-12-02 05:47:15 +08:00
code-compliant 206d40bc0d Give the focus back after any list or menu closes by a key, and skip a return target that is gone
One check after the dialog draws replaces the three per-box helpers: when a list or menu closed by Escape, Enter or Space while the dialog had the keys, the focus returns to the control of the dialog that last had it. A popup that closed earlier in the same pass still counts as open for the Escape test. The return target saved when the dialog opened is used only if it still exists (a menu item that opened the dialog is gone). The key ownership is updated before a drawing switch rebuilds the state.
2026-12-02 05:19:42 +08:00
code-compliant f796d5c8fc Remember who has the keys in the Text Style dialog
The dialog has the keys while the focus is in it, and keeps them when egui drops the focus (an Escape, a click on blank space, a control that goes away, a list or menu that closes). The focus moving to another window, or a click outside the dialog, takes them away, so an Escape for a command running in the drawing, or for another window, is left alone. A list closed by Escape, Enter or Space gives the focus back to its box only while the dialog has the keys.
2026-12-02 04:38:41 +08:00
code-compliant 03bf451124 Give the focus back to a combo box when Escape closes its list
egui drops the focus as an Escape arrives, so after the font or style list closed, nothing held the focus and the next Escape did not reach the dialog. The three lists now return the focus to their box when Escape closes them. One long line is split as rustfmt wants.
2026-12-02 04:15:50 +08:00
code-compliant 2659b44569 Keep the Text Style dialog's focus handling to its own keys, and name its preview
Escape closes or cancels something in the dialog only when the focus was in it one pass earlier (egui drops the focus as the key arrives), so an Escape for a command running in the drawing is left to the command. The dialog takes the focus again each time it opens, including after another dialog replaced it, and after a drawing switch removed the field that held it; the focus returns to what had it only if the dialog held it. When the filter hides the chosen style, the focus goes to the first style shown, or the filter. The style preview is named by its heading. The Tab test now checks every enabled control and the opposite order back, and the focus-return test checks the focus itself.
2026-12-02 03:53:54 +08:00
code-compliant e5f62c9546 Let Escape cancel the font list, the New page or a rename before it closes Text Style
The font list closes itself on Escape while the dialog draws, so the check that left it alone saw no open popup and the dialog closed as well. The state is now read before the dialog draws. On the New page and during a rename, Escape now acts as Cancel and puts the focus back on the styles, as it already did for the unsaved-changes question.
2026-12-02 03:10:01 +08:00
code-compliant f5a70b0e98 Regenerate the parity checklist for the new style commands
cargo xtask parity now counts 488 registered commands (the Text Style
commands this pull request adds among them) instead of 482. The file is
generated, so it is regenerated rather than edited.
2026-12-02 00:55:45 +08:00
code-compliant 13aa3a5cc6 test(acadver): move the ACADVER tests into the engine's shared integration binary
The five cases move from tests/acadver.rs to tests/it/acadver.rs unchanged, apart from the I/O
setup: the save case installs the suite's real file hooks (refedit_xref::hooks) in place of its
own copy, and uses a folder under Cargo's temporary directory for integration tests.
2026-12-01 23:47:22 +08:00
code-compliant 3fe6d7e954 test(sysvars): make the TEXTEVAL session check able to fail; put the $ names note on its list 2026-12-01 23:47:07 +08:00
code-compliant 5950cbce24 Keep the Chinese command labels main requires complete
Moving these two rows out made chinese_menus_and_commands_are_fully_translated
fail: both are labels of engine commands (-style and style.fonts), and that
test, which main already has, requires the zh catalog to name every command.
They stay here rather than moving to the craft-i18n pull request, rather than
weakening the check. The 26 Ukrainian rows are not required by any check and do
move.
2026-12-01 23:41:49 +08:00
code-compliant 88a3069ea2 Let the keyboard use the Text Style dialog and leave it
The dialog opened without taking the focus, so a person without a pointer was
left on the drawing behind it and every key went past the dialog; Escape did
nothing, so the only way out was to find a button; and the style filter was
named "List", which is not the heading a person sees over it.

The dialog now takes the focus on open, and on each page it shows (the
question, the new style's name, the styles). Escape closes it, cancelling an
unanswered question instead of dropping the edits, and closing gives the focus
back to what had it. The filter is named by its heading.

The tests drive open, choose, apply and the question with key events only, and
fail without these changes.
2026-12-01 22:33:56 +08:00
code-compliant 20e2efebf7 fix(sysvars): refuse text from programs and routines, read unknown DIMASSOC as off, save REGENMODE
DIMASO, TEXTEVAL and REGENMODE now take only a number from a program or a routine: numeric text
and booleans are refused. Digits typed at the SETVAR prompt, by hand or through (command), still
work.

DIMASO reads 1 only for DIMASSOC 1 or 2. For any other stored mode it reads 0, and DIMASO 1 turns
associativity on from it too.

A new drawing now has REGENMODE 1 in its header, so a save writes $REGENMODE.
2026-12-01 20:32:12 +08:00
code-compliant a193f64e04 style(tests): keep the module list in order after the merge 2026-12-01 20:32:11 +08:00
code-compliant 494dbd965b Take the new text fields from the previewed style
Main's Text gained backwards and upside_down; the dialog's preview sets them
from the style it draws, so a preview shows the effects the style has.
2026-12-01 20:17:01 +08:00
code-compliant bea1843497 Move the Text Style translations to the craft-i18n pull request
Feature pull requests add English only (AGENTS.md rule 16). The 26 Ukrainian
and 2 Simplified Chinese rows move to storytold/craft-i18n; the English keys,
the UI wiring and the managers/textstyle entry in the translation report stay
here, so the new strings show in English until the translations land.
2026-12-01 16:49:39 +08:00
code-compliant f9284510ea Merge remote-tracking branch 'origin/main' into assist/pr-1089-text-style 2026-12-01 14:53:48 +08:00
code-compliant 723997489a Merge remote-tracking branch 'origin/main' into fix/acadver-release-text 2026-12-01 14:45:18 +08:00
code-compliant 0bc5f721fb Merge remote-tracking branch 'origin/main' into fix/sysvars-dimaso-texteval-regenmode-popups 2026-12-01 14:45:16 +08:00
Dylan M. Taylor 41928f5611 Complete shared dependency API compatibility 2026-11-29 12:17:16 -05:00
Dylan M. Taylor f9c31fe169 Adapt to repinned craft-libs APIs and checks 2026-11-29 11:45:38 -05:00
Dylan M. Taylor 9f7d3fa401 Repin craft-libs to main 9949e08 2026-11-29 11:19:03 -05:00
Magzhan ZhakudaandClaude Opus 5.5 e9ac879b83 Vertex identifiers: compare in the read orientation, skip application groups
Review follow-ups: the points kept with the identifiers are stored as the
reader gives them (mirrored in x when the normal points down), and only that
orientation matches, so a reversed polyline symmetric about x = 0 no longer
keeps its identifiers. A group 91 inside an application's 102 group is not
read as an identifier. The edit test asserts that no identifier is written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 03:17:09 +05:00
Magzhan ZhakudaandClaude Opus 5.5 ffde4b3bbe DXF/DWG: a lightweight polyline keeps its vertex identifiers
A LWPOLYLINE's vertex identifiers (group 91, DXF 2010 and later) were
dropped on read, so every save wrote the polyline without them. Geometric
constraints name a polyline's segments by them. They are now kept with the
entity's extras and written back (DXF 2010+, and DWG through the bridge)
while every vertex is where it was read; once a vertex is moved, added,
removed or reordered, none are written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 02:43:43 +05:00
code-compliant 0db2d73e02 Fix Text Style lookup for extensionless fonts 2026-11-27 21:39:26 +08:00
code-compliant fcb2188143 Test text style changes before selection 2026-11-27 10:00:56 +08:00
code-compliant ab183249f9 Fix text style prompts and preserve drawing edits 2026-11-27 09:51:27 +08:00
code-compliant cd4912b003 Merge main and adapt text style preview 2026-11-27 08:40:51 +08:00
code-compliant 61d1f267cf Merge latest main into text-follows-style 2026-11-26 15:25:39 +08:00
code-compliant b9c9162b14 Merge main into text-follows-style 2026-11-26 15:18:53 +08:00
code-compliant bbf613e944 Merge remote-tracking branch 'origin/main' into fix/sysvars-dimaso-texteval-regenmode-popups
# Conflicts:
#	crates/engine/src/settings.rs
2026-11-25 20:24:51 +08:00
code-compliant 91acccc36a DIMASO: no change leaves the drawing unmodified; its remembered mode is not a variable and not a roundtrip loss 2026-11-25 20:04:14 +08:00
code-compliant dec54a9ded DIMASO keeps its remembered mode in the drawing header, so undo restores it; any number of $ before the four names 2026-11-25 18:22:02 +08:00
code-compliant 38a239b1e9 Keep DIMASO's remembered mode per drawing and take the DXF $ names
DIMASO remembered the DIMASSOC mode it turned off in the session settings,
so two open drawings switched between restored each other's mode: with 1 in
the first and 2 in the second, the first came back as 2. The remembered mode
now lives in the drawing's own state, which is not saved, so each open
drawing keeps its own.

$DIMASO, $TEXTEVAL, $REGENMODE and $POPUPS were unknown to getvar, and
setvar took $POPUPS and out-of-range $REGENMODE because only the header's
name lookup stripped the $. Those four names now read, take values and
report read-only exactly as their plain forms, in any case and with spaces
around them. No other name changes: $ANGBASE keeps LISP's radians (only the
plain name converts) and setvar $OSMODE is still not the session's OSMODE.

Tests: DIMASO 1 restores 1 in the first drawing and 2 in the second after
switching; each $ form reads, writes and refuses like its plain name,
including $REGENMODE 2 and $POPUPS; and $ANGBASE, $OSMODE keep their own
handling.
2026-11-25 17:55:54 +08:00
code-compliant 60ac79d4b5 Read and set the legacy variables DIMASO, TEXTEVAL, REGENMODE and POPUPS
DIMASO has no value of its own: it reports DIMASSOC as 0 or 1, and setting it to 0 turns DIMASSOC off while remembering the mode it had, so setting it back to 1 restores that mode (2 when none was seen). Every other value is refused and changes nothing.

TEXTEVAL is a session setting (0 by default) kept for routines that switch it around their prompts; no prompt reads it yet. REGENMODE is the drawing's, 1 by default, and is saved as $REGENMODE (group 70) and read back. POPUPS is read-only and always 1.
2026-11-25 17:35:54 +08:00
code-compliant a65a9b36b5 ACADVER: a $ in the name does not get past read-only; listings show the release text without a drawing 2026-11-25 16:46:10 +08:00
code-compliant 808ae34499 sysvars: ACADVER reports the program's release, not the file version
(getvar "ACADVER") and the GETVAR command gave the drawing's $ACADVER file
version code (AC1015), and SETVAR accepted a new value for it. AutoCAD
documents ACADVER as a read-only text variable holding the program's release
number, which (atof) reads back as a number.

GETVAR now gives "24.3s (CADCraft)" (24.3), and SETVAR and SETVAR's typed name
prompt report it as read-only. The drawing's $ACADVER is untouched, so a
drawing read from a 2000 DXF still saves as one.

Tests: crates/engine/tests/acadver.rs.
2026-11-25 16:07:18 +08:00
SlopapaloozaandClaude Opus 5.5 ebeee968b5 Review fixes: TEXT refuses an unknown justification; its params string
From CodeRabbit's reviews of #1089:
- TEXT's Justify question refuses an answer that is no option ("Invalid
  option keyword.") and asks again, as MTEXT's does; it kept the previous
  justification and went on. Enter leaves the question, as Style's does (it
  asked again, with Esc, which ends TEXT, the only way out).
- The `text` params string lost a line continuation (a run of spaces showed
  in the command list, the CLI and MCP).
- The hostile TEXT input test fails on a caught panic (an internal error)
  instead of discarding every result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:22 -05:00
SlopapaloozaandClaude Opus 5.5 2eaf90df4b New text follows its style: fixed and paper heights, width factor, oblique, TEXT's Style option
TEXT, MTEXT and their JSON forms now set text the way its style says, as AutoCAD does:

- A fixed-height style (height > 0) isn't asked for a height: TEXT goes from the start point
  to the rotation, MTEXT starts at that height, and the JSON forms default to it (an explicit
  `height` is kept). TEXTSIZE is left alone. MTEXT's Style option takes a fixed style's height.
- An annotative style asks for "Specify paper text height", the size the text measures on
  paper.
- New TEXT takes the style's width factor and obliquing angle (it had 1 and 0). Later style
  changes don't change existing text, as in AutoCAD.
- TEXT's Style option works: a style name (made current, then the status line again) or ? to
  list the styles; an unknown name is refused and asked again.
- Enter at TEXT's start point continues directly below the last TEXT in the space, with its
  style, height, rotation and justification, and asks only for the text. With no text in
  the drawing it ends the command.
- The status line gives the height the style fixes and the justification in use.
- `text` takes `style` (default: the current style).

Left for later: Align and Fit take one point, not the baseline's two ends, and
the line being typed isn't previewed on the canvas.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:22 -05:00
SlopapaloozaandClaude Opus 5.5 d8cf5fbb62 -STYLE: imports by name, as #2239 requires
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:22 -05:00
SlopapaloozaandClaude Opus 5.5 bf3e607bd6 Review fixes: font files named in capitals; a rename keeps the waiting edits
From CodeRabbit's reviews of #1083:
- The dialog matched a style's font without its extension ("arialn")
  against the installed file's stem in its own case, so ARIALN.TTF wasn't
  found: the dialog said "not installed" and disabled Font Style for a font
  the renderer finds and draws. The stems are compared in any case now.
- Renaming the chosen style renames the edits waiting for Apply with it, so
  setting every value back no longer leaves Apply on (and Close asking)
  because of the old name.
- The preview is drawn on the drawing area's color (theme::Tokens), as the
  canvas is, instead of white or the raster default.
- Closing the dialog clears a New page or a rename left open, so the next
  STYLE opens on the styles.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 6042310fc7 Review fixes: -STYLE's annotative answers and big font, the dialog's rename
From CodeRabbit's review of #1083 (its finding on the text styles that
dimension overrides use is fixed in #954, where the rename that follows
them is):
- -STYLE: Enter at "Create annotative text style?" says yes, as the prompt
  now shows (it showed the style's current setting while Enter said yes),
  and No asks for the text height again instead of a paper height.
- -STYLE keeps the big font of the style a new one starts from.
- The Text Style dialog's Rename takes only a name the rename accepts, so a
  refused one no longer leaves the selection on no style and drops the
  edits waiting for Apply.
- The dialog test's "Styles in use" check now hides a style that exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 1ec5d20c84 Text Style dialog (STYLE) with installed fonts, and -STYLE
STYLE (ST, Format ▸ Text Style...) opens a Text Style dialog like AutoCAD's: the drawing's
text styles (all, or those in use; annotative ones marked) with a preview of the selected one,
and Set Current, New, Rename and Delete (off for Standard, the current style and styles in
use). The selected style's Font Name and Font Style are picked from the installed fonts by
family and style, with a search; Use Big Font is offered for SHX fonts; Annotative switches
Height to Paper Text Height; the effects are Upside down, Backwards, Width Factor and Oblique
Angle. Edits wait for Apply (one undo step), and choosing another style, Set Current, New or
Close with edits not applied asks whether to save them, as AutoCAD does. Match text
orientation to layout and Vertical are shown unavailable: CADCraft doesn't keep or draw them.

The fonts come from the fonts crate's new installed_fonts(), which reads only each font file's
table directory and naming table (typographic family and subfamily first, English names
preferred), so listing every installed font is cheap (145 faces in about 60 ms on Windows 11).
`style.fonts` gives the same list to MCP clients and scripts.

-STYLE asks in AutoCAD's order, so scripts written for AutoCAD run: name (or ? to list),
font, height or Annotative (then orientation and paper height), width factor, obliquing
angle, backwards, upside down, and vertical for SHX fonts; the style then becomes current.
Unusable answers are asked again. As JSON it takes the style command's parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 723810f768 -DIMSTYLE: imports by name, as #2239 requires; the managers' modules in order
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 60e22f38c4 Review fixes: overrides written as taken, style names, the manager keeps a refused edit
From CodeRabbit's second to fourth reviews of #1042:
- dimstyle.overrides writes each header variable with the value the style
  took (a lineweight named ByLayer is -1), so SETVAR can't refuse one
  halfway through, after `clear` and the earlier values.
- -DIMSTYLE Save and Restore check the name before touching the drawing, so
  a refused call leaves no empty undo step, and Apply to objects none of
  which is a dimension makes none either.
- New dimension styles and renames take the names -DIMSTYLE takes (no `~`,
  which its Restore reads as "compare with", and no wildcards), in the
  `dimstyle` and `dimstyle.rename` commands and in the manager's New and
  Rename, which ask the engine (cmd::usable_dim_style_name). A style read
  from a file keeps its name.
- The manager's OK goes back to the list only when its commands succeed: a
  value the engine refuses keeps the editing page open with every edit.
- Compare offers the style overrides too (the current style with them), so
  comparing them with their style shows what they change.
- The manager opens on its list again after its window is closed, not on the
  page left open, and its preview is drawn on the drawing area's color
  (theme::Tokens), as the canvas is.
- The manager's Rename takes only a name the rename accepts, so renaming a
  style onto another's name no longer leaves the list on that other style.
- The -DIMSTYLE tests apply to a line that's there, and the hostile-input
  test fails on a caught panic (an internal error).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 ba63055fd3 Review fixes: -DIMSTYLE matcher, clear after checks, Override's whole set, ~ in names
From CodeRabbit's review of #1042:
- -DIMSTYLE's list matches style names with QSELECT's wildcard matcher (with
  one backtrack point) instead of a recursive one that a pattern of many `*`
  made exponential: one `list` call could hang the session.
- dimstyle.overrides checks every value (against the style alone when
  `clear` is given) before clearing, so a refused call keeps the overrides.
- The Dimension Style Manager's Override sends what differs from the style
  as the whole override set (`clear` first): a value set back to the style's
  drops its override, and undoing every override drops them all.
- A refused answer at -DIMSTYLE asks the same question again (a ~name that
  names no style used to fall back to the first prompt), and words at
  "Select dimension" ask for the dimension again.
- dimstyle.saveas takes names as -DIMSTYLE does, so no `~` (which Restore
  reads as "compare with").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
eldrirandClaude Opus 5.5 cec2e0c04a Dimension Style Manager (DIMSTYLE) and -DIMSTYLE
DIMSTYLE (D, DST, DDIM, Format and Dimension menus) opens AutoCAD's Dimension Style Manager:
the drawing's styles (all, or those in use) with the current style's <style overrides> under it,
a preview drawn with the chosen settings, and Set Current, New, Modify, Override, Compare,
Rename and Delete. Modify, Override and New edit every style variable on AutoCAD's seven tabs
(Lines, Symbols and Arrows, Text, Fit, Primary Units, Alternate Units, Tolerances), from the
engine's table of dimension properties; a fixed-height text style shows the height it fixes.
OK changes the style, sets the current style's overrides, or creates the new style, each as one
undo step; programmatic calls never open the dialog.

-DIMSTYLE asks as AutoCAD does: ANnotative, Save (asks before redefining a name in use),
Restore (~name lists how a style differs from the current settings, or pick a dimension),
STatus, Variables, Apply and ?. As JSON it takes {option, ...}. dimstyle.overrides sets the
current style's overrides in one step, and changes nothing when one value is unusable.

An empty leader arrowhead now reads as closed filled, as it is drawn (it read as DIMBLK's).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 8fb5e95f15 Dimension style shortcut commands: imports by name, as #2239 requires
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
eldrirandClaude Opus 5.5 5f4a17cb7c Dimension shortcut menu: Remove Style Overrides, Dimension Style, Precision, Align Text
With dimensions selected, the canvas shortcut menu adds AutoCAD's dimension items:
Align Text ▸ (DIMTEDIT Home/Angle/Left/Center/Right), Dimension Style ▸ (the drawing's styles,
which the selected dimensions take, then Save as New Style), Precision ▸ (DIMDEC, or DIMADEC
for angular dimensions, as overrides) and Remove Style Overrides (available while one of them
overrides its style).

Two commands behind them: dimoverride.clear clears the selected dimensions' overrides, and
dimstyle.saveas makes a new dimension style of a dimension's settings, its overrides included,
gives it to the dimension and clears its overrides (the current style is unchanged). From the
menu it uses the selected dimension, or asks for one, then asks for the name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 1c02f239c3 Properties palette: the described rows' shared inputs in one struct, within #2239's limit
#2239 denies functions with more than seven arguments. `described_row` took eight; the drawing,
the handles, the angle settings and the shared text style now come together as `Rows`, which
the row destructures under the same names. Nothing changes in behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
SlopapaloozaandClaude Opus 5.5 ea0d0e9595 Review fixes: picking the color a row already has is no edit; directions typed as measured
From CodeRabbit's reviews of #994:
- The palette's color menu sent the color number while the row's value is
  the color's name, so picking the color a row already showed still ran
  properties.set (and made an undo step). The menu now compares by name and
  sends nothing for the color already set.
- A rotation (a direction row) typed in the palette is read as the drawing
  measures directions (AngleSettings::direction): a surveyor's bearing such
  as N45dE is absolute, and `<<a` / `<<<a` measure from +X counterclockwise.
  Both were turned by ANGBASE before (or refused, for `<<`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
eldrirandClaude Opus 5.5 5c24bc3dcf Properties palette: text, mtext and dimension rows from properties.describe
The palette draws the groups the engine describes for text, mtext and dimensions after its own
General group, so a dimension's text height (and every other dimension style setting) is edited
there as an override of the selected dimensions, and TEXT and MTEXT get their style,
justification, obliquing, line spacing and position rows. Several objects of one type edit
together, with *VARIES* where they differ.

Rows read values as the command line does (distances in any unit format, angles in the
drawing's angle units); unreadable text and values the engine refuses are reported. An
overridden dimension row has its label in the accent color, and right-clicking it puts the
style's value back. A fixed-height text style's height shows read-only with the reason.

A few engine labels are renamed to translate cleanly and fit the label column; every label the
engine gives the palette has a Ukrainian row, and `cargo xtask i18n` reports any that go missing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
SlopapaloozaandClaude Opus 5.5 5689203791 Dimensions: an explicit text rotation sizes the dimension line's gap
A linear or aligned dimension broke its line around the text as DIMTIH and DIMTOH turn it,
and only then applied an explicit text rotation (DIMTEDIT Angle, or Text rotation in the
Properties palette). Text turned along a vertical dimension line drew over the line, which
left a gap only the height of horizontal text, whatever the text offset (DIMGAP). The gap, the
fit check and the text's clearance now take the text as turned.

Found by testing #1042 (Dievartis). A test checks that no part of the dimension line crosses
text turned along it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
SlopapaloozaandClaude Opus 5.5 b99ea8905e properties.set: one function per kind of object, within #2239's clippy limits
#2239 denies a cognitive complexity over 30 and wildcard imports. properties.set's per-object
edit (complexity 90) becomes one function per kind of object (line, circle, arc, text and its
position, mtext and its line spacing, insert, dimension and its prefix and suffix, hatch) and
one for the properties every object has; what the call checked before any object changes
travels in a `Call`. set.rs and props.rs import by name. Nothing changes in behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
SlopapaloozaandClaude Opus 5.5 c1c97ed00e Review fixes: SOLID drops the gradient, all objects checked first, Align rotation, DIMPOST rows
From CodeRabbit's second to fourth reviews of #954, and codyvogt (from #1371's):
- The Properties pattern edit and HATCHEDIT share one helper
  (hatch::set_pattern) and one rule for the names a hatch takes: SOLID drops
  a gradient fill too, a blank name changes nothing (it's reported as
  ignored), and a name no pattern has is refused, as HATCHEDIT refuses it (a hatch's own
  name matches in any case).
- properties.set refuses a call that names an object that isn't there before
  it edits any, so a bad handle late in the list no longer leaves the
  earlier objects edited.
- A prefix or suffix edit goes into the DIMPOST/DIMAPOST the dimension has
  after the call's other edits (its new style, cleared overrides), not the
  ones it had before.
- The prefix and suffix rows are marked overridden when DIMPOST or DIMAPOST
  is, and their "Use the style's value" clears that variable.
- Rotating aligned or fit TEXT turns its baseline's second point with it
  (the renderer takes their direction from the two points).
- Justify Align or Fit measures the baseline from the text as the call
  leaves it (its new contents, style, height, width factor and rotation).
- `scale` is an insert's or hatch's scale only; it no longer also becomes a
  DIMSCALE override of a dimension in the selection (that's `dimScale`).
- A text style that only a dimension's text style override names is in use,
  so style.delete refuses it (a rename follows those overrides already).
- Editing a text or dimension style redraws the dimensions read from a file
  only when the style changed: making it current keeps their geometry.
- docs/mcp.md's example finds the dimension's handle with query_entities
  before it describes and sets it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
SlopapaloozaandClaude Opus 5.5 a551f206e8 Review fixes: hatch pattern lines, closed-filled ends, measurements, layer after checks
From CodeRabbit's review of #954:
- A Properties pattern edit follows HATCHEDIT: a library pattern drops the
  hatch's own lines, a loaded .pat pattern brings its lines, and any other
  name keeps them (the moved code cleared them unconditionally).
- Closed filled chosen for Arrow 1 or Arrow 2 is stored as _CLOSEDFILLED: an
  empty per-end arrowhead draws DIMBLK's, so "" changed nothing under a tick.
- The Measurement row writes angles in the dimension's angle format
  (DIMAUNIT, DIMADEC, DIMAZIN) as the renderer does, and equal measurements
  written differently (units, precision) show *VARIES*.
- Text height with fixed-height text styles of different heights shows
  *VARIES* instead of the dimensions' shared DIMTXT.
- properties.set creates a new layer only after every check, so a refused
  call leaves no layer behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
eldrirandClaude Opus 5.5 b70c8609c9 Properties: describe and set every text, mtext and dimension property
properties.describe lists the Properties palette's rows for a selection: General for every
object; Text and Geometry for TEXT and MTEXT; Misc, Lines & Arrows, Text, Fit, Primary Units,
Alternate Units and Tolerances for dimensions. Each row carries the properties.set key that
changes it, the value the objects share (or *VARIES*), the value in the drawing's units, whether
it can be edited (a fixed-height text style makes a dimension's text height read-only and says
so), and for dimensions whether the dimension overrides its style there. A mixed selection gets
the General group; `type` limits the description to one object type.

properties.set takes those keys: TEXT style, justify (keeping the point the text is placed by),
oblique, positionX/Y/Z and the second point of aligned and fit text; MTEXT style, justify,
lineSpacing, lineSpacingDistance and lineSpacingStyle, position; dimension style variables by
field or DIM* name as overrides of each dimension, clearOverrides, clear, textRotation,
textPositionX/Y, prefix and suffix. The reply lists the keys no selected object took.

Editing a dimension style or a text style now redraws the dimensions read from files that use it
(they kept drawing, and saving, the *D block they were read with), and renaming a text style
follows a dimension's own text style override.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
199 changed files with 8649 additions and 786 deletions
+2 -2
View File
@@ -32,8 +32,8 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/zh_shared.tsv` | @V1dalTheAbidal | [craft-i18n #444](https://github.com/storytold/craft-i18n/pull/444), [pinned Simplified Chinese CADCraft catalog](https://github.com/storytold/craft-i18n/blob/9fa32aecf2759cd61bb216a958df68da619798f3/locales/zh-hans/cadcraft.tsv#L201) | MIT OR Apache-2.0 | Exact generated one-row projection for offline builds; AI-assisted, not native-speaker reviewed. |
| `vendor/wgpu-hal/` | wgpu developers; Metal language probe by CADCraft contributors | [wgpu-hal 30.0.1](https://crates.io/crates/wgpu-hal/30.0.1) ([gfx-rs/wgpu 40f4a34e](https://github.com/gfx-rs/wgpu/tree/40f4a34ebaf56f9a046231f54125ad046239d3f3/wgpu-hal)), same patch as [storytold/craft-anything vendor/wgpu-hal](https://github.com/storytold/craft-anything/tree/6c7d1f07f9f33643714bd203e1e004f04481f28e/vendor/wgpu-hal) | MIT OR Apache-2.0 | Graphics dependency, patched in `src/metal/adapter.rs` only (#1631); see `vendor/wgpu-hal/CADCRAFT.md`. |
| `licenses/jpeg-encoder-0.6.1/` | jpeg-encoder contributors and Independent JPEG Group | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1) | (MIT OR Apache-2.0) AND IJG | Dependency license and SIMD notices; source hashes in SOURCE.json. |
| `licenses/dwg/acadrust-MPL-2.0.txt` | acadrust contributors | [acadrust 0.6.6](https://crates.io/crates/acadrust/0.6.6), [hakanaktt/acadrust](https://github.com/hakanaktt/acadrust), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MPL-2.0 | DWG read/write dependency, used unmodified through craft-dwg. Full licence text is also in NOTICE. |
| `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | Albert Domenech (ACadSharp) and acadrust contributors | [ACadSharp](https://github.com/DomCR/ACadSharp), via [acadrust 0.6.6 third-party notices](https://github.com/hakanaktt/acadrust/blob/v0.6.6/THIRD_PARTY_NOTICES.md), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MIT (ACadSharp, via acadrust) | Upstream notice for MIT code ported into acadrust's DWG reader and writer. Full text is also in NOTICE. |
| `licenses/dwg/acadrust-MPL-2.0.txt` | acadrust contributors | [acadrust 0.6.9](https://github.com/storytold/acadrust/blob/468b9d8e317755209020d5d3f2f1c8a76210c47f/LICENSE) | MPL-2.0 | DWG read/write dependency, used unmodified through craft-dwg. Full licence text is also in NOTICE. |
| `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | Albert Domenech (ACadSharp) and acadrust contributors | [ACadSharp](https://github.com/DomCR/ACadSharp), via [acadrust 0.6.9 third-party notices](https://github.com/storytold/acadrust/blob/468b9d8e317755209020d5d3f2f1c8a76210c47f/THIRD_PARTY_NOTICES.md) | MIT (ACadSharp, via acadrust) | Upstream notice for MIT code ported into acadrust's DWG reader and writer. Full text is also in NOTICE. |
| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 173cc737](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full monochrome fallback. Registered by the production default font definitions; dependency assets unmodified here, no font file copied into this repository. |
| `krilla 0.8.2 / icc/sGrey-v2-magic.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v2-magic.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v2-magic.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `4110169287e5f1b5149ca9f1da1814d32943905bba8030e849d1a3b729a19481`. |
| `krilla 0.8.2 / icc/sGrey-v4.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v4.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v4.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `00c0f94e09127520a17dc0e1d9264b5702081d96dbdb1549ee88e3631ce42a9d`. |
Generated
+396 -137
View File
File diff suppressed because it is too large Load Diff
+43 -38
View File
@@ -16,12 +16,12 @@ 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 = "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" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "8945bdb09b36245a1d442438ce8876377ef430d0" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
cadcraft-color = { path = "crates/color" }
cadcraft-doc = { path = "crates/doc" }
cadcraft-constraints = { path = "crates/constraints" }
@@ -31,19 +31,24 @@ 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 = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
# Agents in the open window: the agent settings, the ArtCraft Launcher's switch, the connection file and
# the CLI's live client (`agents`), shared by every Craft app.
craft-control = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
# The agent link host (the window's control server for agents) and the Agents page of Options.
craft-automation = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
# SVG/SVGZ import and export geometry (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
# 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 = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
# 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 = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", default-features = false }
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", default-features = false }
# Delimited text (CSV/TSV) parsing (shared Craft library).
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4.6.11"
clap_mangen = { version = "0.3.3", features = ["env"] }
@@ -77,12 +82,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 = "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"] }
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", 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 }
@@ -93,7 +98,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 = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", features = ["ui"] }
rfd = "0.18"
arboard = { version = "3.6", default-features = false }
@@ -125,27 +130,27 @@ 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 = "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" }
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
# wgpu-hal that picks a Metal language version the system compiler accepts, not the OS's alone
# (#1631; upstream gfx-rs/wgpu#10687). See vendor/wgpu-hal/CADCRAFT.md for when to remove it.
wgpu-hal = { path = "vendor/wgpu-hal" }
# Keep the complete egui family and native event bridge on reviewed fork commits.
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" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
winit = { git = "https://github.com/storytold/winit.git", rev = "3fd7ae64762f82a73b78bd24f453f82c4291067d" }
+10 -12
View File
@@ -10,11 +10,10 @@ docs/brand/LICENSE-brand.txt.
Third-party material
Software dependencies are listed in Cargo.lock. One is under a weak-copyleft licence: the acadrust
crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) 0.6.6 is licensed under the
Mozilla Public License 2.0 and is used unmodified as a separate library via craft-dwg. Its source
is available from crates.io and the repository above. The licence text and upstream third-party
notices are retained in licenses/dwg/, copied verbatim from craft-libs at
8fa4db64a9bb943520259ea95331a303ba788f21, the revision this repository pins.
crate (DWG reading and writing) 0.6.9 is licensed under the Mozilla Public License 2.0
and is used as a separate library via craft-dwg. Its source is available at
https://github.com/storytold/acadrust/tree/468b9d8e317755209020d5d3f2f1c8a76210c47f. The licence text and
upstream third-party notices are retained in licenses/dwg/.
acadrust's DWG reader and writer include code ported and adapted from ACadSharp
(https://github.com/DomCR/ACadSharp), Copyright (c) 2021 Albert Domenech, under the MIT License.
@@ -432,13 +431,12 @@ SOFTWARE.
## DWG Format References
DWG field layouts and version behavior are based on the Open Design Alliance (ODA) DWG
specification and reverse engineering, including comparison with drawings produced by CAD
applications. LibreDWG is used as a secondary cross-check for selected field names and
layouts. The Reed-Solomon tests cite numeric reference values from LibreDWG's
`src/reedsolomon.c` to validate the Rust implementation; those values are test data, not
translated routines. The repository history and source review found no LibreDWG routines
ported into the implementation. The source comments identify the specific cross-checks.
The Open Design Alliance (ODA) DWG specification is the primary published reference for
the binary layouts documented by this project. Where the specification is incomplete or
ambiguous, implementation details are checked against native DWG files produced by CAD
applications. Source comments and regression tests identify the evidence used for each
layout and behavior. ACadSharp remains the attributed origin of the existing reader and
writer code described above.
CADCraft's icons, drafting font, hatch patterns and linetypes are drawn or defined in code.
+14
View File
@@ -396,6 +396,20 @@ RISC-V (riscv64) packages are `cadcraft-<ver>-linux-riscv64.deb`,
`cadcraft-<ver>-linux-riscv64.rpm`, and `cadcraft-<ver>-linux-riscv64.tar.gz`. They are
cross-compiled and need glibc 2.39 or newer (Ubuntu 24.04+, Debian 13+).
**Wayland:** on a Wayland desktop the app uses the native Wayland backend, which is sharp at
fractional scales, works with input methods and accepts files dropped from the file manager. If
the native backend misbehaves on your desktop, run the app through XWayland instead with
`CADCRAFT_X11=1` (this needs the X11 libraries: libX11, libX11-xcb, libXcursor, libXi and
libxkbcommon-x11):
```sh
CADCRAFT_X11=1 cadcraft
```
GNOME on Wayland draws no window frames, so there CADCraft's title bar carries the window
buttons, in GNOME's order. **Options ▸ Display ▸ Use system title bar** shows a basic frame
instead. `CADCRAFT_TITLEBAR=app` or `CADCRAFT_TITLEBAR=system` overrides the detection.
### FreeBSD
| Build | File |
+48 -8
View File
@@ -11,6 +11,7 @@ use std::path::{Path, PathBuf};
use cadcraft_engine::geom::{Bounds2, Vec2};
use cadcraft_io::Format;
use cadcraft_mcp::args::{blank_env_is_unset, name_env_vars};
use cadcraft_mcp::live::WhenAppClosed;
use clap::builder::{OsStringValueParser, PathBufValueParser, TypedValueParser};
use clap::error::ErrorKind;
use clap::parser::ValueSource;
@@ -262,12 +263,23 @@ pub(crate) struct CommandsArgs {
pub(crate) compact: bool,
}
/// Run the MCP server on stdio: a headless drawing session, or a bridge to the running app
/// Run the MCP server on stdio: the open CADCraft window while ArtCraft Launcher › Settings › AI
/// agents lets agents use it, otherwise a headless drawing session
#[derive(Args)]
pub(crate) struct McpArgs {
/// Bridge to the app's control channel (its --control port, e.g. 127.0.0.1:7979)
/// Deprecated: plain `mcp` finds the open window by itself while the ArtCraft Launcher lets
/// agents use CADCraft. Bridges to the app's --control port (e.g. 127.0.0.1:7979); goes in a
/// later release
#[arg(long, value_name = "HOST:PORT", value_parser = connect_addr)]
pub(crate) connect: Option<String>,
/// Never the open window: a headless drawing session, also while the ArtCraft Launcher lets
/// agents use CADCraft
#[arg(long, conflicts_with = "connect")]
pub(crate) headless: bool,
/// While agents may use CADCraft but it is closed: `launch` (open it and wait), `headless`
/// (work without a window) or `error`. Default: Options › AI Agents › When CADCraft is closed
#[arg(long, value_name = "CHOICE", value_parser = when_closed, conflicts_with_all = ["connect", "headless"])]
pub(crate) when_closed: Option<WhenAppClosed>,
/// Reach the app at the first call instead of at startup, so the server can start before the
/// app is open
#[arg(long, requires = "connect")]
@@ -404,6 +416,8 @@ pub(crate) enum ValueError {
CmdJson(#[from] serde_json::Error),
#[error("expected a number of 0 or more, got `{0}`")]
Tolerance(String),
#[error("expected one of launch, headless, error, got `{0}`")]
WhenClosed(String),
}
/// Why `parse` refuses flags clap accepted: clap prints it as a usage error (exit 2).
@@ -523,8 +537,12 @@ fn out_is_input(cli: &Cli) -> Option<UsageError> {
/// The backend `cadcraft-cli mcp` serves from.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum McpTarget {
/// An in-process drawing session (no `--connect`), optionally confined to the two folders.
/// An in-process drawing session (`--headless`), optionally confined to the two folders.
Headless { read_root: Option<String>, write_root: Option<String> },
/// Plain `mcp`: the open window while the ArtCraft Launcher's switch lets agents use CADCraft,
/// otherwise a headless session with the two folders (`cadcraft_mcp::Live`); headless without
/// the suite's `AI-MCP` flag, as before.
Live { read_root: Option<String>, write_root: Option<String>, when_closed: Option<WhenAppClosed> },
/// The running app's control channel at `HOST:PORT`; `lazy`: reached at the first call;
/// `launch`: opened then if it isn't running.
Connect { addr: String, lazy: bool, launch: bool },
@@ -533,10 +551,12 @@ pub(crate) enum McpTarget {
impl McpArgs {
/// What these arguments ask the server to talk to.
pub(crate) fn target(&self) -> McpTarget {
let (read_root, write_root) = (self.automation_read_root.clone(), self.automation_write_root.clone());
match &self.connect {
// `--launch` connects at the first call too (the app opens then).
Some(addr) => McpTarget::Connect { addr: addr.clone(), lazy: self.lazy || self.launch, launch: self.launch },
None => McpTarget::Headless { read_root: self.automation_read_root.clone(), write_root: self.automation_write_root.clone() },
None if self.headless => McpTarget::Headless { read_root, write_root },
None => McpTarget::Live { read_root, write_root, when_closed: self.when_closed },
}
}
}
@@ -553,6 +573,11 @@ fn connect_addr(s: &str) -> Result<String, ValueError> {
if valid { Ok(s.to_string()) } else { Err(ValueError::Connect) }
}
/// `mcp --when-closed`: one of [`WhenAppClosed::NAMES`].
fn when_closed(s: &str) -> Result<WhenAppClosed, ValueError> {
WhenAppClosed::parse(s.trim()).ok_or_else(|| ValueError::WhenClosed(s.to_string()))
}
/// The values of `id` with their command-line indices.
fn indexed<'a, T: Clone + Send + Sync + 'static>(m: &'a ArgMatches, id: &str) -> impl Iterator<Item = (usize, &'a T)> {
let at = m.indices_of(id).into_iter().flatten();
@@ -665,10 +690,21 @@ mod tests {
}
}
/// Without `--connect` the server runs headless, confining nothing unless asked.
/// Plain `mcp` looks for the open window (headless while the launcher doesn't let agents in);
/// `--headless` never does. Neither confines anything unless asked.
#[test]
fn mcp_without_connect_is_headless() {
assert_eq!(mcp(&[]).unwrap(), McpTarget::Headless { read_root: None, write_root: None });
fn plain_mcp_looks_for_the_window_and_headless_never_does() {
assert_eq!(mcp(&[]).unwrap(), McpTarget::Live { read_root: None, write_root: None, when_closed: None });
assert_eq!(mcp(&["--headless"]).unwrap(), McpTarget::Headless { read_root: None, write_root: None });
assert_eq!(
mcp(&["--when-closed", "headless"]).unwrap(),
McpTarget::Live { read_root: None, write_root: None, when_closed: Some(WhenAppClosed::Headless) }
);
assert!(mcp(&["--when-closed", "later"]).unwrap_err().to_string().contains("launch, headless, error"));
// A closed-app choice means nothing without the window, and --connect names its own app.
for conflict in [&["--headless", "--when-closed", "error"][..], &["--headless", "--connect", "127.0.0.1:7979"]] {
assert_eq!(mcp(conflict).unwrap_err().kind(), clap::error::ErrorKind::ArgumentConflict, "{conflict:?}");
}
}
/// The automation roots confine a headless server; `--connect` is refused with the reason
@@ -676,9 +712,13 @@ mod tests {
#[test]
fn mcp_automation_roots_confine_a_headless_server_only() {
assert_eq!(
mcp(&["--automation-read-root", "/work", "--automation-write-root=/work/out"]).unwrap(),
mcp(&["--headless", "--automation-read-root", "/work", "--automation-write-root=/work/out"]).unwrap(),
McpTarget::Headless { read_root: Some("/work".into()), write_root: Some("/work/out".into()) }
);
assert_eq!(
mcp(&["--automation-read-root", "/work"]).unwrap(),
McpTarget::Live { read_root: Some("/work".into()), write_root: None, when_closed: None }
);
let e = mcp(&["--connect", "127.0.0.1:7979", "--automation-read-root", "/work"]).unwrap_err().to_string();
assert!(e.contains("headless MCP server") && e.contains("#1585"), "{e}");
let e = mcp(&["--automation-write-root=/work", "--connect", "127.0.0.1:7979"]).unwrap_err().to_string();
+84 -13
View File
@@ -1,25 +1,96 @@
use std::path::{Path, PathBuf};
use super::args::{McpArgs, McpTarget};
use super::error::{CliError, Result};
/// Serve MCP on stdin and stdout against the running app or a headless session held to any roots given.
/// Serve MCP on stdin and stdout: plain `mcp` against the open window while the ArtCraft Launcher
/// lets agents use CADCraft, otherwise (and with `--headless`) a headless session held to any roots
/// given; `--connect` against an app's `--control` port.
pub(crate) fn mcp(a: &McpArgs) -> Result {
let backend: Box<dyn cadcraft_mcp::Backend> = match a.target() {
McpTarget::Connect { addr, lazy: true, launch } => Box::new(cadcraft_mcp::Remote::lazy(&addr, launch)),
McpTarget::Connect { addr, .. } => match cadcraft_mcp::Remote::connect(&addr) {
Ok(r) => Box::new(r),
Err(source) => return Err(CliError::McpConnect { addr, source }),
},
McpTarget::Headless { read_root, write_root } => {
let roots = cadcraft_engine::file_access::AutomationRoots::new(
read_root.as_deref().map(std::path::Path::new),
write_root.as_deref().map(std::path::Path::new),
)
.map_err(CliError::AutomationRoots)?;
Box::new(cadcraft_mcp::Headless::default().with_automation_roots(roots))
McpTarget::Connect { addr, lazy, launch } => {
let remote = if lazy {
cadcraft_mcp::Remote::lazy(&addr, launch)
} else {
cadcraft_mcp::Remote::connect(&addr).map_err(|source| CliError::McpConnect { addr, source })?
};
// Once the bridge serves: a failed start says only why it failed.
eprintln!(
"cadcraft-cli: `mcp --connect` is deprecated and goes in a later release; plain `cadcraft-cli mcp` finds the open CADCraft window while ArtCraft Launcher › Settings › AI agents lets agents use it"
);
Box::new(remote)
}
McpTarget::Live { read_root, write_root, when_closed } => {
match config_dir(a.settings.config_dir.as_deref()).filter(|_| cadcraft_mcp::live::mcp_flag()) {
Some(dir) => {
// Roots that can't be opened stop the server now, as they do headless.
headless(read_root.as_deref(), write_root.as_deref())?;
let mut cfg = cadcraft_mcp::LiveConfig::new(dir);
cfg.when_closed = when_closed;
cfg.read_root = read_root.map(PathBuf::from);
cfg.write_root = write_root.map(PathBuf::from);
cfg.launch = std::env::current_exe().ok().and_then(|cli| cadcraft_mcp::live::launcher(&cli));
Box::new(cadcraft_mcp::Live::new(cfg))
}
// Without the suite's flag (or a settings folder) agents work without a window, as before.
None => headless(read_root.as_deref(), write_root.as_deref())?,
}
}
McpTarget::Headless { read_root, write_root } => headless(read_root.as_deref(), write_root.as_deref())?,
};
let stdin = std::io::stdin();
let stdout = std::io::stdout();
cadcraft_mcp::Server::new(backend).serve(stdin.lock(), stdout.lock())?;
Ok(())
}
/// A headless session held to the roots given, if any.
fn headless(read_root: Option<&str>, write_root: Option<&str>) -> Result<Box<dyn cadcraft_mcp::Backend>> {
let roots =
cadcraft_engine::file_access::AutomationRoots::new(read_root.map(Path::new), write_root.map(Path::new)).map_err(CliError::AutomationRoots)?;
Ok(Box::new(cadcraft_mcp::Headless::default().with_automation_roots(roots)))
}
/// The app's settings folder, where it publishes the agent connection: `--config-dir` or
/// `CADCRAFT_CONFIG_DIR` (`given`; blank: none), else a portable copy's `CADCraftData` beside the
/// CLI, else the platform's, as the app resolves it.
fn config_dir(given: Option<&Path>) -> Option<PathBuf> {
let exe_dir = std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_path_buf));
config_dir_from(given, exe_dir.as_deref(), |k| std::env::var_os(k))
}
/// [`config_dir`] with the CLI in `exe_dir` and `var` looking the platform's variables up.
fn config_dir_from(given: Option<&Path>, exe_dir: Option<&Path>, var: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
match given {
Some(dir) if dir.to_str().is_some_and(|d| d.trim().is_empty()) => None,
Some(dir) => Some(dir.to_path_buf()),
None => match exe_dir.filter(|d| d.join("portable.txt").is_file()) {
Some(exe) => Some(exe.join("CADCraftData")),
None => cadcraft_engine::settings_dir::platform(var),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::OsString;
/// The CLI looks for the connection where the app publishes it: `--config-dir` (or its
/// variable), a portable copy's folder beside it, or the platform's.
#[test]
fn the_settings_folder_is_the_apps() {
let exe = std::env::temp_dir().join(format!("cadcraft-cli-portable-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&exe);
std::fs::create_dir_all(&exe).unwrap();
let none = |_: &str| None::<OsString>;
let given = Path::new("/private/cc");
assert_eq!(config_dir_from(Some(given), Some(&exe), none), Some(given.to_path_buf()));
assert_eq!(config_dir_from(Some(Path::new(" ")), Some(&exe), none), None);
assert_eq!(config_dir_from(None, Some(&exe), none), cadcraft_engine::settings_dir::platform(none));
std::fs::write(exe.join("portable.txt"), b"").unwrap();
assert_eq!(config_dir_from(None, Some(&exe), none), Some(exe.join("CADCraftData")));
assert_eq!(config_dir_from(Some(given), Some(&exe), none), Some(given.to_path_buf()), "the folder given wins");
std::fs::remove_dir_all(exe).unwrap();
}
}
@@ -14,6 +14,9 @@ fn mcp(args: &[&str], input: &str) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli"))
.arg("mcp")
.args(args)
// No settings folder: plain `mcp` can't find a window and serves headless, whatever the
// ArtCraft Launcher's switch says on this computer.
.env("CADCRAFT_CONFIG_DIR", "")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
@@ -81,6 +84,8 @@ fn connect_with_address_routes_to_that_endpoint() {
assert!(instructions.contains(&format!("connected to CADCraft at {addr}")), "{instructions}");
let text = r.iter().find(|v| v["id"] == 2).and_then(|v| v["result"]["content"][0]["text"].as_str()).unwrap_or_default();
assert!(text.contains("loopback"), "{r:?}");
// Still served for one release, with the way forward on stderr.
assert!(String::from_utf8_lossy(&out.stderr).contains("`mcp --connect` is deprecated"));
}
#[test]
+3 -1
View File
@@ -151,7 +151,9 @@ fn subcommand_help_requests() {
"mcp --help",
&["mcp", "--help"],
0,
Line("Run the MCP server on stdio: a headless drawing session, or a bridge to the running app"),
Line(
"Run the MCP server on stdio: the open CADCraft window while ArtCraft Launcher › Settings › AI agents lets agents use it, otherwise a headless drawing session",
),
Empty,
),
case(
+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 = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", version = "0.1.0" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
+9 -1
View File
@@ -40,6 +40,12 @@ winresource = "0.1"
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
winit = { version = "0.30", default-features = false, features = ["x11"] }
# Checks that the X11 libraries are installed before choosing XWayland (see main.rs). Already in
# the build through winit, at this version.
x11-dl = "2.21"
# Checks for libxkbcommon-x11 too, which winit's X11 backend needs for the keyboard and panics
# without. Already in the build through winit, at this version and with this feature.
xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
# View ▸ Theme ▸ System: the desktop's light/dark choice from the XDG desktop portal
# (desktop_theme.rs). Already in Cargo.lock through accesskit; pinned to that version so nothing
# is built twice.
@@ -47,13 +53,15 @@ zbus = { version = "=5.19.0", default-features = false, features = ["async-io",
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
craft-update = { workspace = true }
# The ArtCraft Launcher's switch and the agent link (main.rs `agents`).
craft-automation = { workspace = true, features = ["ui", "agents"] }
rfd = { workspace = true }
sys-locale = "0.3"
[target.'cfg(target_os = "macos")'.dependencies]
muda = { version = "0.22", 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"] }
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", 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"] }
+8 -8
View File
@@ -12,7 +12,7 @@ const CONFIG_DIR: &str = "CADCRAFT_CONFIG_DIR";
const LOCALE: &str = "CADCRAFT_LOCALE";
const VSYNC: &str = "CADCRAFT_VSYNC";
const STENCIL: &str = "CADCRAFT_STENCIL";
const WAYLAND: &str = "CADCRAFT_WAYLAND";
const X11: &str = "CADCRAFT_X11";
const NO_NATIVE_MENU: &str = "CADCRAFT_NO_NATIVE_MENU";
const SYSTEM_CURSOR: &str = "CADCRAFT_SYSTEM_CURSOR";
const FONTALT: &str = "CADCRAFT_FONTALT";
@@ -27,7 +27,7 @@ pub(crate) const VARS: &[(&str, &str)] = &[
STENCIL,
"0 opens the window without a stencil buffer, 1 keeps it on every attempt; unset, a start that can't draw with it drops it (clipped layout viewports then draw unclipped)",
),
(WAYLAND, "1 keeps the native Wayland backend instead of XWayland; 0 or unset is off"),
(X11, "1 runs through XWayland instead of the native Wayland backend, as a fallback, when the X11 libraries load; 0 or unset is off"),
(NO_NATIVE_MENU, "macOS: 1 keeps the menus inside the window; 0 or unset is off"),
(SYSTEM_CURSOR, "1 uses the system cursor instead of the drawn crosshair; 0 or unset is off"),
(FONTALT, "the font that replaces a missing one"),
@@ -54,9 +54,9 @@ pub(crate) struct Env {
/// `renderer`). Some old drivers (Mesa on Intel HD 4000, old Intel drivers on Windows) accept a
/// stencil pass and then present a black window.
pub(crate) stencil: Switch,
/// Keep the native Wayland backend instead of XWayland.
/// Run through XWayland instead of the native Wayland backend.
#[cfg_attr(not(all(unix, not(target_os = "macos"))), allow(dead_code))]
pub(crate) wayland: Switch,
pub(crate) x11: Switch,
/// macOS: keep the menus inside the window.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) no_native_menu: Switch,
@@ -121,7 +121,7 @@ impl Env {
locale: text(LOCALE),
vsync: switch(VSYNC),
stencil: switch(STENCIL),
wayland: switch(WAYLAND),
x11: switch(X11),
no_native_menu: switch(NO_NATIVE_MENU),
system_cursor: switch(SYSTEM_CURSOR),
font_alt: text(FONTALT),
@@ -223,7 +223,7 @@ mod tests {
(LOCALE, "cs-CZ"),
(VSYNC, " On "),
(STENCIL, "No"),
(WAYLAND, "0"),
(X11, "0"),
(NO_NATIVE_MENU, "yes"),
(SYSTEM_CURSOR, "maybe"),
(FONTALT, "Noto Sans"),
@@ -238,7 +238,7 @@ mod tests {
locale: Some("cs-CZ".into()),
vsync: Switch::On,
stencil: Switch::Off,
wayland: Switch::Off,
x11: Switch::Off,
no_native_menu: Switch::On,
system_cursor: Switch::Default,
font_alt: Some("Noto Sans".into()),
@@ -249,7 +249,7 @@ mod tests {
let read = Env::from_vars(env(&blank));
assert_eq!(read.config_dir, None, "an empty variable means no directory, not the working directory");
assert_eq!((read.locale, read.font_alt, read.font_fallback), (None, None, None));
assert_eq!([read.vsync, read.stencil, read.wayland, read.no_native_menu, read.system_cursor], [Switch::Default; 5]);
assert_eq!([read.vsync, read.stencil, read.x11, read.no_native_menu, read.system_cursor], [Switch::Default; 5]);
}
#[test]
+108 -7
View File
@@ -428,6 +428,32 @@ fn log_version() -> String {
format!("{} ({})", reported_version(), option_env!("CADCRAFT_BUILD_SHA").unwrap_or("dev"))
}
/// Agents in the open window: while the ArtCraft Launcher's switch (Settings › AI agents) names
/// CADCraft, the agent link serves the control channel for `cadcraft-cli mcp` and publishes
/// `agent-connection.json` in the settings folder (`cadcraft_ui_egui::agents`). `--control` manages
/// its own server for the whole run instead. A Nightly build is not the app the launcher's switch
/// names, so it takes no agents this way.
fn agents(control_port: Option<u16>, settings_dir: Option<std::path::PathBuf>, ctx: &egui::Context) -> cadcraft_ui_egui::agents::Agents {
use craft_automation::agents::{AgentLink, AgentSwitch, remove_stale_connection};
if is_nightly() {
return Default::default();
}
// A file a crashed launch left behind names a port nothing serves.
if let Some(dir) = &settings_dir {
remove_stale_connection(dir);
}
let wake = ctx.clone();
// The launcher's app list names CADCraft by its catalog id.
let switch = AgentSwitch::watch(profile_root::APP_ID, move || wake.request_repaint());
match control_port {
Some(port) => cadcraft_ui_egui::agents::Agents::managed_by_launch(port, switch, settings_dir),
None => {
let link = AgentLink::new(settings_dir.clone(), format!("CADCraft {}", cadcraft_engine::build_version()));
cadcraft_ui_egui::agents::Agents::new(link, switch, settings_dir)
}
}
}
/// Whether this start runs the isolated Nightly flavor.
fn is_nightly() -> bool {
launch_profile::current().is_nightly()
@@ -498,6 +524,38 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
Some(launch.passthrough_args)
}
/// Whether the libraries winit's X11 backend opens at startup are installed (libX11, libXcursor,
/// libX11-xcb and libXi; libX11-xcb brings in libxcb; and libxkbcommon-x11, for the keyboard).
/// The deb and rpm only recommend them, and a forced X11 backend without them fails to start
/// (winit panics when libxkbcommon-x11 is missing).
#[cfg(all(unix, not(target_os = "macos")))]
fn x11_libraries_load() -> bool {
use x11_dl::{xcursor::Xcursor, xinput2::XInput2, xlib::Xlib, xlib_xcb::Xlib_xcb};
let missing = [Xlib::open().err(), Xcursor::open().err(), Xlib_xcb::open().err(), XInput2::open().err()];
let mut missing: Vec<String> = missing.into_iter().flatten().map(|e| e.to_string()).collect();
if xkbcommon_dl::x11::xkbcommon_x11_option().is_none() {
missing.push("libxkbcommon-x11.so.0 could not be loaded".into());
}
if !missing.is_empty() {
log::warn!("CADCRAFT_X11: X11 libraries missing, using the native Wayland backend: {}", missing.join("; "));
}
missing.is_empty()
}
/// Whether to force winit's X11 backend (XWayland on a Wayland desktop): an X display is there,
/// `CADCRAFT_X11` is on, and the X11 libraries load. The libraries are probed last, only when X11
/// would otherwise be chosen.
#[cfg(all(unix, not(target_os = "macos")))]
fn use_x11(display: bool, setting: Switch, x11_libraries_load: impl FnOnce() -> bool) -> bool {
display && setting == Switch::On && x11_libraries_load()
}
/// Whether a display variable names something: set and not empty, as winit reads them.
#[cfg(all(unix, not(target_os = "macos")))]
fn set(v: Option<&std::ffi::OsStr>) -> bool {
v.is_some_and(|v| !v.is_empty())
}
/// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe.
fn main() -> eframe::Result {
// A copy of this program started to read or write a DWG file does only that. It is started
@@ -589,9 +647,21 @@ fn main() -> eframe::Result {
cadcraft_engine::fonts::ttf::set_fallback_fonts(list);
}
let surface = cadcraft_ui_egui::gpu::surface_config(vars.vsync, cfg!(all(unix, not(target_os = "macos"))));
// 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);
// winit runs natively on a Wayland desktop: sharp at fractional scales, with working input
// methods, and file drops from the file manager through storytold/winit's W15 patch.
// CADCRAFT_X11=1 runs through XWayland instead, as a fallback where the native backend
// misbehaves; 0, off or unset leaves it off. The X11 libraries are only recommended by the
// packages, so without them the setting is ignored rather than failing.
#[cfg(all(unix, not(target_os = "macos")))]
let forced_x11 = use_x11(set(std::env::var_os("DISPLAY").as_deref()), vars.x11, x11_libraries_load);
#[cfg(not(all(unix, not(target_os = "macos"))))]
let forced_x11 = false;
// Read before the window opens: Use system title bar decides the window's frame.
let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref());
// Where the desktop leaves the window frame to the app (GNOME on Wayland), the framework's title
// bar carries the window buttons, unless Options ▸ Display ▸ Use system title bar is on.
let title_bar = cadcraft_ui_egui::title_bar::decide(forced_x11, restored.as_ref().is_some_and(|ui| ui.system_title_bar));
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11).or_else(|| title_bar.as_ref().map(|t| t.decision().clone()));
let persistence_path = vars
.portable_storage_file
.clone()
@@ -620,9 +690,6 @@ fn main() -> eframe::Result {
d
});
}
// winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file
// 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 forced_x11 {
options.event_loop_builder = Some(Box::new(|b| {
@@ -666,7 +733,6 @@ fn main() -> eframe::Result {
{
app.services.start_pick = Some(start_pick(cc.egui_ctx.clone()));
}
let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref());
if let Some(ui) = restored {
app.ui = ui;
}
@@ -716,6 +782,9 @@ fn main() -> eframe::Result {
app.session.set_lisp_support_dir(Some(support));
}
app.integrated_titlebar = cadcraft_ui_egui::framework::draws_title_row(frame.as_ref());
if let Some(title_bar) = title_bar {
app.set_title_bar(title_bar);
}
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
}
@@ -725,6 +794,7 @@ fn main() -> eframe::Result {
let rx = control_server::start(port, cc.egui_ctx.clone());
app = app.with_control(rx);
}
app.agents = agents(control_port, vars.config_dir.clone(), &cc.egui_ctx);
if sample {
let _ = app.run("ui.sample", serde_json::json!({}));
}
@@ -781,6 +851,37 @@ mod tests {
use super::{filters_for_save, follow_desktop, nightly_version_line, saved_window, version_string, window_options, without_tiny_window};
use crate::renderer::STENCIL_BITS;
/// A Wayland desktop without the X11 libraries (libxkbcommon-x11 removed, or a package
/// installed without its recommendations) crashed at startup: X11 was forced through XWayland
/// and winit panicked loading them. Native Wayland is now the default, `CADCRAFT_X11=1` asks
/// for X11 only when the libraries load, and probing them never panics, whichever of them
/// this machine has.
#[test]
#[cfg(all(unix, not(target_os = "macos")))]
fn x11_only_when_asked_for_and_the_libraries_load() {
use super::{use_x11, x11_libraries_load};
use cadcraft_ui_egui::switch::Switch;
let unprobed = || -> bool { panic!("the libraries are probed only when X11 would be chosen") };
assert!(!use_x11(true, Switch::Default, unprobed), "native Wayland by default");
assert!(!use_x11(true, Switch::Off, unprobed), "CADCRAFT_X11=0 leaves it off");
assert!(!use_x11(false, Switch::On, unprobed), "no X display");
assert!(use_x11(true, Switch::On, || true));
assert!(!use_x11(true, Switch::On, || false), "missing X11 libraries: native Wayland, no crash");
let loaded = x11_libraries_load();
assert_eq!(use_x11(true, Switch::On, || loaded), loaded);
}
/// An empty `DISPLAY` names no X server, so `CADCRAFT_X11=1` can't force X11 with it.
#[test]
#[cfg(all(unix, not(target_os = "macos")))]
fn an_empty_display_is_no_display() {
use super::set;
use std::ffi::OsStr;
assert!(set(Some(OsStr::new(":0"))));
assert!(!set(Some(OsStr::new(""))));
assert!(!set(None));
}
#[test]
fn save_dialog_offers_dwg_with_the_drawing_format_first() {
let first = |name: &str| filters_for_save(name)[0].1;
+4
View File
@@ -50,6 +50,7 @@ fn snapshot(ui: &UiState) -> Result<Value, String> {
"propertiesAll": ui.properties_all,
"inWindowMenu": ui.in_window_menu,
"historyLines": ui.history_lines,
"systemTitleBar": ui.system_title_bar,
}))
}
@@ -219,6 +220,7 @@ mod tests {
ui.toolset_tab = "Modeling".into();
ui.collapsed_groups = vec!["Solid".into()];
ui.history_lines = 5;
ui.system_title_bar = true;
ui.dialog = Some("layers".into());
ui.start_tab = true;
first.save_if_changed(&ui, Instant::now()).unwrap();
@@ -226,6 +228,7 @@ mod tests {
let value: Value = serde_json::from_slice(&bytes).unwrap();
assert!(value["workspace"].get("dialog").is_none());
assert!(value["workspace"].get("startTab").is_none());
assert_eq!(value["workspace"]["systemTitleBar"], true, "read before the window opens");
let (_, restored, error) = Workspace::at(Some(path.clone()));
assert!(error.is_none());
let restored = restored.unwrap();
@@ -340,6 +343,7 @@ mod tests {
assert_eq!(restored.toolset_tab, "Modeling");
assert_eq!(restored.collapsed_groups, ["Draw"]);
assert_eq!(restored.history_lines, 7);
assert!(!restored.system_title_bar, "older files keep the app's window buttons");
assert_eq!(serde_json::to_value(restored.docking).unwrap(), serde_json::to_value(UiState::default().docking).unwrap());
}
fs::remove_dir_all(directory).unwrap();
+172 -6
View File
@@ -7,9 +7,15 @@
//! it draws at paper size × that view's annotation scale, and only in views whose scale it
//! supports unless `ANNOALLVISIBLE` is 1. Model space is seen at `CANNOSCALE`, a layout viewport
//! at its viewport scale, and paper space itself at 1:1.
//!
//! An object supporting several scales can sit somewhere else at one of them ([`AnnoMove`]): its
//! grips move it at the current scale only, and ANNORESET puts every scale back where the current
//! one is. What moves is the object's position ([`shift_position`]).
use serde::{Deserialize, Serialize};
use cadcraft_geom::{Mat3, Vec2};
use crate::{Common, Drawing, Entity, EntityKind};
/// A named annotation scale: `paper_units` on paper show `drawing_units` of the drawing.
@@ -87,6 +93,13 @@ pub fn imperial_scales() -> Vec<AnnoScale> {
v
}
/// How far an annotative object sits from its shared position at the scale named `scale`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AnnoMove {
pub scale: String,
pub by: Vec2,
}
/// Kinds that can be annotative.
pub fn can_be_annotative(k: &EntityKind) -> bool {
matches!(
@@ -105,6 +118,7 @@ pub fn is_annotative(e: &Entity) -> bool {
pub fn set_annotative(e: &mut Entity, on: bool, current: &AnnoScale) {
if !on {
e.common.anno_scales.clear();
e.common.anno_moves.clear();
} else if can_be_annotative(&e.kind) && e.common.anno_scales.is_empty() {
e.common.anno_scales.push(current.clone());
}
@@ -115,8 +129,9 @@ pub fn set_annotative(e: &mut Entity, on: bool, current: &AnnoScale) {
pub enum AnnoDraw {
/// Not annotative: as stored.
Plain,
/// Annotative, at this factor (drawing units per paper unit).
Scaled(f64),
/// Annotative, at `factor` (drawing units per paper unit), its position moved `by` at that
/// scale.
Scaled { factor: f64, by: Vec2 },
/// Annotative and not supporting the view's scale, with `ANNOALLVISIBLE` 0.
Hidden,
}
@@ -130,6 +145,76 @@ impl Common {
pub fn supports_scale(&self, name: &str) -> bool {
self.anno_scales.iter().any(|s| s.name.eq_ignore_ascii_case(name))
}
/// How far the object sits from its shared position at the scale named `name`.
pub fn moved_at(&self, name: &str) -> Vec2 {
self.anno_moves.iter().find(|m| m.scale.eq_ignore_ascii_case(name)).map(|m| m.by).filter(|v| v.is_finite()).unwrap_or(Vec2::ZERO)
}
/// How far the object sits from its shared position at its scale with the ratio `factor`.
pub fn moved_at_factor(&self, factor: f64) -> Vec2 {
self.anno_scales.iter().find(|s| s.has_factor(factor)).map_or(Vec2::ZERO, |s| self.moved_at(&s.name))
}
/// Move the object `by` at the scale named `name` only (an offset that comes to nothing is
/// dropped).
pub fn move_at(&mut self, name: &str, by: Vec2) {
if !by.is_finite() {
return;
}
let to = self.moved_at(name) + by;
self.anno_moves.retain(|m| !m.scale.eq_ignore_ascii_case(name));
if to.len() > 1e-12 * (1.0 + by.len()) && self.anno_moves.len() < MAX_SCALES {
self.anno_moves.push(AnnoMove { scale: name.to_string(), by: to });
}
}
/// Turn the offsets with `m`'s linear part (MOVE leaves them, ROTATE turns them, SCALE sizes
/// them, MIRROR mirrors them), as the shared position goes through `m`.
pub fn transform_moves(&mut self, m: &Mat3) {
for mv in &mut self.anno_moves {
let v = m.apply_vec(mv.by);
mv.by = if v.is_finite() { v } else { Vec2::ZERO };
}
}
}
/// Move the position of `k` by `by`: a text's, MText's or block reference's whole object, a
/// multileader's landing and content (its arrowheads stay), a dimension's text. Other kinds stay.
pub fn shift_position(k: &mut EntityKind, by: Vec2) {
if !by.is_finite() || by == Vec2::ZERO {
return;
}
let add = |p: &mut cadcraft_geom::Vec3| {
p.x += by.x;
p.y += by.y;
};
match k {
EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Insert(_) => k.transform(&Mat3::translate(by)),
EntityKind::MLeader(m) => {
add(&mut m.landing);
if let Some(t) = &mut m.text {
add(&mut t.insert);
}
if let Some(b) = &mut m.block {
add(&mut b.insert);
}
}
EntityKind::Dimension(d) => {
add(&mut d.text_mid);
d.user_text_pos = true;
d.block = None;
}
_ => {}
}
}
/// Whether grip `index` of `k` is its position grip: moving it moves what [`shift_position`]
/// moves.
pub fn is_position_grip(k: &EntityKind, index: usize) -> bool {
match k {
EntityKind::Text(_) | EntityKind::MText(_) => true,
EntityKind::Insert(_) => index == 0,
EntityKind::Dimension(_) => index == 3,
EntityKind::MLeader(m) => index == m.leaders.iter().map(Vec::len).sum::<usize>(),
_ => false,
}
}
/// How `e` draws in a view whose annotation scale is `view` (drawing units per paper unit). An
@@ -139,14 +224,56 @@ pub fn anno_draw(e: &Entity, view: f64, all_visible: bool) -> AnnoDraw {
return AnnoDraw::Plain;
}
if e.common.supports_factor(view) {
return AnnoDraw::Scaled(if view.is_finite() && view > 0.0 { view } else { 1.0 });
let factor = if view.is_finite() && view > 0.0 { view } else { 1.0 };
return AnnoDraw::Scaled { factor, by: e.common.moved_at_factor(view) };
}
match e.common.anno_scales.first() {
Some(s) if all_visible => AnnoDraw::Scaled(s.factor()),
Some(s) if all_visible => AnnoDraw::Scaled { factor: s.factor(), by: e.common.moved_at(&s.name) },
_ => AnnoDraw::Hidden,
}
}
/// `e` at each of its scales other than the one it shows at in a view of scale `view` (see
/// [`anno_draw`]): at that scale's size and position, no longer annotative (so it draws as it
/// is). AutoCAD shows these faded while the object is selected (SELECTIONANNODISPLAY). Empty when
/// `e` isn't annotative, supports one scale or doesn't show in that view; scales of the same
/// ratio come once. At most `budget` are made, and `budget` goes down by each one: a selection
/// shares one budget, taken before any geometry is copied.
pub fn anno_others(e: &Entity, view: f64, all_visible: bool, budget: &mut usize) -> Vec<Entity> {
if *budget == 0 {
return Vec::new();
}
let AnnoDraw::Scaled { factor, .. } = anno_draw(e, view, all_visible) else {
return Vec::new();
};
let mut seen = vec![factor];
let mut out = Vec::new();
for s in e.common.anno_scales.iter().take(MAX_SCALES).filter(|s| s.is_valid()) {
if *budget == 0 {
break;
}
let f = s.factor();
if seen.iter().any(|g| same_factor(*g, f)) {
continue;
}
seen.push(f);
*budget -= 1;
let mut other = anno_placed(e, f, e.common.moved_at(&s.name));
other.common.anno_scales.clear();
other.common.anno_moves.clear();
out.push(other);
}
out
}
/// `e` as it draws at annotation scale `f` with its position moved `by` there: [`anno_scaled`],
/// then [`shift_position`].
pub fn anno_placed(e: &Entity, f: f64, by: Vec2) -> Entity {
let mut out = anno_scaled(e, f);
shift_position(&mut out.kind, by);
out
}
/// `e` as it draws at annotation scale `f`: its paper sizes (text height and width, dimension
/// overall scale, multileader arrow, landing and content, hatch pattern scale, block scale and
/// attributes) multiplied by `f`. A dimension is drawn from its definition at that scale, not
@@ -225,13 +352,52 @@ impl Drawing {
/// (paper space shows every annotative object), elsewhere (model space, or an object not in
/// the drawing yet) as [`anno_draw`] at the current annotation scale.
pub fn anno_draw(&self, e: &Entity) -> AnnoDraw {
self.anno_draw_in(e, None)
}
/// How top-level object `e` draws where it is edited: through an active viewport whose
/// annotation scale is `view` (drawing units per paper unit, the viewport's scale, as the
/// renderer draws model space there), else as [`Drawing::anno_draw`].
pub fn anno_draw_in(&self, e: &Entity, view: Option<f64>) -> AnnoDraw {
if !is_annotative(e) {
return AnnoDraw::Plain;
}
if !self.model.contains(e.handle) && self.layouts.iter().any(|l| l.entities.contains(e.handle)) {
return AnnoDraw::Scaled(1.0);
return AnnoDraw::Scaled { factor: 1.0, by: e.common.moved_at_factor(1.0) };
}
let view = view.filter(|f| f.is_finite() && *f > 0.0).unwrap_or_else(|| self.current_anno_scale().factor());
anno_draw(e, view, self.anno_all_visible())
}
/// The scale `e` shows at outside a viewport (see [`Drawing::anno_draw`]): its name and
/// factor, `None` when `e` isn't annotative or doesn't show.
pub fn anno_shown_scale(&self, e: &Entity) -> Option<AnnoScale> {
self.anno_shown_scale_in(e, None)
}
/// The scale `e` shows at in view `view` (see [`Drawing::anno_draw_in`]).
pub fn anno_shown_scale_in(&self, e: &Entity, view: Option<f64>) -> Option<AnnoScale> {
match self.anno_draw_in(e, view) {
AnnoDraw::Scaled { factor, .. } => e.common.anno_scales.iter().find(|s| s.has_factor(factor)).cloned(),
_ => None,
}
}
/// `e` at its other scales outside a viewport (see [`anno_others`], which takes from
/// `budget`); none in a layout's paper space, which shows annotative objects at 1:1 only.
pub fn anno_others(&self, e: &Entity, budget: &mut usize) -> Vec<Entity> {
if !is_annotative(e) || (!self.model.contains(e.handle) && self.layouts.iter().any(|l| l.entities.contains(e.handle))) {
return Vec::new();
}
anno_others(e, self.current_anno_scale().factor(), self.anno_all_visible(), budget)
}
/// `e` as it draws outside a viewport: an annotative object at its scale and position there,
/// anything else (and a hidden annotative object) as stored.
pub fn anno_shown(&self, e: &Entity) -> EntityKind {
self.anno_shown_in(e, None)
}
/// `e` as it draws in view `view` (see [`Drawing::anno_draw_in`]).
pub fn anno_shown_in(&self, e: &Entity, view: Option<f64>) -> EntityKind {
match self.anno_draw_in(e, view) {
AnnoDraw::Scaled { factor, by } => anno_placed(e, factor, by).kind,
_ => e.kind.clone(),
}
anno_draw(e, self.current_anno_scale().factor(), self.anno_all_visible())
}
/// Whether new objects of this kind are annotative: text and MText with an annotative text
/// style, dimensions with an annotative dimension style, multileaders with an annotative
+5
View File
@@ -98,6 +98,10 @@ pub struct Common {
/// The annotation scales an annotative object supports (empty: not annotative).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub anno_scales: Vec<crate::AnnoScale>,
/// Where an annotative object sits apart from its shared position at some of its scales
/// (moved with its grips at that scale; ANNORESET clears them).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub anno_moves: Vec<crate::AnnoMove>,
/// Other applications' extended data (xdata) as read from the drawing file: whole
/// applications, each from its `1001` group on. It is part of the object, so a copy of the
/// object (COPY, MIRROR, ARRAY, paste) carries it, as in AutoCAD.
@@ -119,6 +123,7 @@ impl Default for Common {
extrusion: Vec3::Z,
plot_style: "ByLayer".into(),
anno_scales: Vec::new(),
anno_moves: Vec::new(),
xdata: Vec::new(),
}
}
+3 -1
View File
@@ -645,7 +645,9 @@ fn bounds_of<'a>(
match d.anno_draw(e) {
crate::AnnoDraw::Plain => {}
crate::AnnoDraw::Hidden => return Bounds2::EMPTY,
crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, in_drawing, off_counts, frozen),
crate::AnnoDraw::Scaled { factor, by } => {
return bounds_in(d, &crate::anno_placed(e, factor, by), 0, blocks, in_drawing, off_counts, frozen);
}
}
}
bounds_in(d, e, depth, blocks, in_drawing, off_counts, frozen)
+26
View File
@@ -45,6 +45,31 @@ pub struct ForeignExtra {
/// Unmodelled groups of the record's own last subclass, written just before its xdata. Filled
/// on save from the entity itself ([`crate::Viewport::extra`]), so that copies keep them.
pub tail: Vec<RawTag>,
/// A lightweight polyline's vertex identifiers (group 91, DXF 2010 and later) as read: one per
/// vertex in the polyline's order; empty when the file gave none. Geometric constraints name the
/// polyline's segments by them, so they are written back while the polyline's vertices are
/// where they were read ([`vertex_ids_for`]).
pub vertex_ids: Vec<VertexId>,
}
/// A vertex of a lightweight polyline as it was read: its identifier and its point as the
/// polyline has it once read (a polyline whose normal points down is read mirrored in x).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct VertexId {
/// The identifier (group 91); 0 for a vertex without one.
pub id: i32,
pub x: f64,
pub y: f64,
}
/// The identifiers `kept` gives the vertices at `points`, in their order, while every vertex is
/// where it was read. `None` once a vertex was added, removed, moved or the order changed: the
/// identifiers no longer say which vertex is which.
pub fn vertex_ids_for(kept: &[VertexId], points: impl ExactSizeIterator<Item = (f64, f64)> + Clone) -> Option<Vec<i32>> {
if kept.is_empty() || kept.len() != points.len() {
return None;
}
kept.iter().zip(points).all(|(k, (x, y))| k.x == x && k.y == y).then(|| kept.iter().map(|k| k.id).collect())
}
impl ForeignExtra {
@@ -55,6 +80,7 @@ impl ForeignExtra {
&& self.color_book.is_none()
&& self.props.is_empty()
&& self.tail.is_empty()
&& self.vertex_ids.is_empty()
}
}
+2
View File
@@ -154,6 +154,8 @@ impl Header {
// Annotation scale of model space; annotative objects of other scales show (1) or not.
h.set_str("CANNOSCALE", "1:1");
h.set_i64("ANNOALLVISIBLE", 1);
// Written to DXF as $REGENMODE; a header variable the drawing lacks is not written.
h.set_i64("REGENMODE", 1);
h
}
+9 -12
View File
@@ -367,19 +367,16 @@ impl Drawing {
}
let Some(cv) = serde_json::to_value(&cand).ok().and_then(|c| c.get(*field).cloned()) else { continue };
let same = match (base.get(*field), &cv) {
// Text style and arrow block names compare without case.
// An empty dimension linetype names ByBlock. DWG can spell that builtin explicitly.
(Some(serde_json::Value::String(a)), serde_json::Value::String(b))
if matches!(
*field,
"textStyle"
| "arrowBlock"
| "arrowBlock1"
| "arrowBlock2"
| "leaderArrowBlock"
| "dimLinetype"
| "extLinetype1"
| "extLinetype2"
) =>
if matches!(*field, "dimLinetype" | "extLinetype1" | "extLinetype2") =>
{
let a = if a.is_empty() { "ByBlock" } else { a };
let b = if b.is_empty() { "ByBlock" } else { b };
a.eq_ignore_ascii_case(b)
}
(Some(serde_json::Value::String(a)), serde_json::Value::String(b))
if matches!(*field, "textStyle" | "arrowBlock" | "arrowBlock1" | "arrowBlock2" | "leaderArrowBlock") =>
{
a.eq_ignore_ascii_case(b)
}
+18
View File
@@ -1160,3 +1160,21 @@ fn layout_lookups_by_name_cost_about_the_same_for_any_table_size() {
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());
}
#[test]
fn dimension_linetype_overrides_compare_effective_names() {
let mut d = Drawing::default();
for var in ["DIMLTYPE", "DIMLTEX1", "DIMLTEX2"] {
d.header.set_str(var, "byBLOCK");
}
assert!(d.dim_overrides().is_empty());
let style = d.dim_styles.iter_mut().find(|s| s.name.eq_ignore_ascii_case("Standard")).unwrap();
style.dim_linetype = "ByBlock".into();
style.ext_linetype1 = "DASHED".into();
style.ext_linetype2 = "ByLayer".into();
d.header.set_str("DIMLTYPE", "");
d.header.set_str("DIMLTEX1", "dashed");
d.header.set_str("DIMLTEX2", "ByBlock");
assert_eq!(d.dim_overrides(), serde_json::Map::from_iter([("extLinetype2".into(), serde_json::json!("ByBlock"))]));
}
+2
View File
@@ -19,6 +19,8 @@ cadcraft-constraints = { workspace = true }
cadcraft-fonts = { workspace = true }
cadcraft-render = { workspace = true }
craft-docpath = { workspace = true }
# The agent settings (Options › AI Agents) the app and `cadcraft-cli mcp` share.
craft-control = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
+104
View File
@@ -0,0 +1,104 @@
//! The agent settings of Options › AI Agents, shared by the app and `cadcraft-cli mcp`: the
//! control port agents connect on, the folders they may open from and save to, and what the CLI
//! does while CADCraft is closed. They are kept in [`FILE`] in the settings folder, beside the
//! connection file the app publishes for agents, so the CLI reads them without the app.
//!
//! Only the person changes them, in the Options dialog: the OPTIONS JSON form has no such keys,
//! so an agent can't widen its own folders through a command.
use std::io;
use std::path::Path;
use std::sync::Arc;
pub use craft_control::agents::{AgentSettings, WhenAppClosed};
use crate::file_access::AutomationRoots;
/// The settings file in the settings folder.
pub const FILE: &str = "agent-settings.json";
/// The largest settings file read; the settings are a few short fields.
const MAX_BYTES: usize = 64 * 1024;
/// The agent settings saved in the settings folder `dir`; the defaults when none are saved or the
/// file can't be read (the reason is logged), so neither the app nor the CLI fails over them.
pub fn load(dir: &Path) -> AgentSettings {
let path = dir.join(FILE);
match crate::capped_read::read_capped(&path, MAX_BYTES) {
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
log::warn!("agent settings {}: {e}; using the defaults", path.display());
AgentSettings::default()
}),
Err(e) if e.kind() == io::ErrorKind::NotFound => AgentSettings::default(),
Err(e) => {
log::warn!("agent settings {}: {e}; using the defaults", path.display());
AgentSettings::default()
}
}
}
/// Saves `settings` in the settings folder `dir` (made if missing), replacing the file whole.
pub fn save(dir: &Path, settings: &AgentSettings) -> io::Result<()> {
let json = serde_json::to_vec_pretty(settings).map_err(io::Error::other)?;
crate::atomic_write::write_atomic_making_folders(&dir.join(FILE), &json)
}
/// The roots agent requests run in, for the agent folders `read` and `write`. A folder that is
/// missing or can't be opened grants nothing in its direction, and with neither every file is
/// refused: leaving the roots out would confine nothing. The error names the folders that could
/// not be used.
pub fn roots(read: Option<&Path>, write: Option<&Path>) -> (Arc<AutomationRoots>, Option<String>) {
let mut problems = Vec::new();
let read = read.filter(|r| AutomationRoots::new(Some(r), None).map_err(|e| problems.push(e)).is_ok());
let write = write.filter(|w| AutomationRoots::new(None, Some(w)).map_err(|e| problems.push(e)).is_ok());
let roots = AutomationRoots::new(read, write).ok().flatten().unwrap_or_else(AutomationRoots::none);
(roots, (!problems.is_empty()).then(|| problems.join("; ")))
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::file_access::{check_read, check_write, confine};
fn temp(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("cadcraft-agent-settings-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// What the dialog saves is what the CLI reads; a damaged file reads as the defaults.
#[test]
fn saved_settings_read_back_and_a_damaged_file_is_the_defaults() {
let dir = temp("round-trip");
let mut settings = AgentSettings::default();
settings.read_root = "/agents/in".into();
settings.when_app_closed = WhenAppClosed::Headless;
save(&dir, &settings).unwrap();
assert_eq!(load(&dir), settings);
std::fs::write(dir.join(FILE), b"{not json").unwrap();
assert_eq!(load(&dir), AgentSettings::default());
std::fs::remove_dir_all(dir).unwrap();
}
/// Agent folders that can't be used refuse every file instead of confining nothing.
#[test]
fn folders_that_cannot_be_used_refuse_every_file() {
let dir = temp("roots");
let file = dir.join("plan.dxf");
let (roots, problem) = roots(Some(&dir.join("missing")), None);
assert!(problem.is_some());
confine(Some(&roots), || {
assert!(check_read(&file).is_err());
assert!(check_write(&file).is_err());
});
let (roots, problem) = super::roots(Some(&dir), Some(&dir.join("gone")));
assert!(problem.is_some(), "the missing write folder is named");
confine(Some(&roots), || {
assert!(check_read(&file).is_ok(), "the usable read folder still applies");
assert!(check_write(&file).is_err());
});
std::fs::remove_dir_all(dir).unwrap();
}
}
+23 -2
View File
@@ -3,6 +3,7 @@
//! objects show (ANNOALLVISIBLE) and the current annotation scale (CANNOSCALE with
//! ANNOAUTOSCALE).
use cadcraft_doc::geom::Vec2;
use cadcraft_doc::{AnnoScale, Drawing, EntityKind, Handle, MAX_SCALES, is_annotative};
use serde_json::{Value, json};
@@ -136,6 +137,7 @@ fn remove_scale(d: &mut Drawing, h: Handle, name: &str) -> Removed {
return;
}
e.common.anno_scales.retain(|s| !s.name.eq_ignore_ascii_case(name));
e.common.anno_moves.retain(|m| !m.scale.eq_ignore_ascii_case(name));
r = Removed::Yes;
});
r
@@ -216,8 +218,27 @@ fn with_handles(s: &Session, p: &Value, mut extra: Value) -> Value {
fn run_annoreset(s: &mut Session, p: &Value) -> Result<Value> {
let (hs, _) = annotative_targets(s, p, "annoreset")?;
// One position serves every scale of an object, so they are always in step.
Ok(json!({ "objects": hs.len(), "message": format!("{} annotative object(s) synchronized", hs.len()) }))
// Every scale goes where the object shows now (in the active viewport, at its scale): that
// offset becomes the shared position.
let view = s.anno_view();
let d = s.doc_mut()?;
let mut moved = 0;
for h in &hs {
let Some(e) = d.entity(*h) else { continue };
if e.common.anno_moves.is_empty() || d.layer(&e.common.layer).is_some_and(|l| l.locked) {
continue;
}
let by = match d.anno_draw_in(e, view) {
cadcraft_doc::AnnoDraw::Scaled { by, .. } => by,
_ => Vec2::ZERO,
};
d.modify_entity(*h, |e| {
cadcraft_doc::shift_position(&mut e.kind, by);
e.common.anno_moves.clear();
})?;
moved += 1;
}
Ok(json!({ "objects": hs.len(), "reset": moved, "message": format!("{} annotative object(s) synchronized", hs.len()) }))
}
fn run_annoupdate(s: &mut Session, p: &Value) -> Result<Value> {
+1 -1
View File
@@ -24,7 +24,7 @@ mod radial;
use angular::{AngularM, ArcLenM, run_angular, run_arclen};
pub(super) use common::segment_at;
use common::{DimText, add_dim, assoc_enabled, circle_of, dim, pick_at};
use common::{DimText, add_dim, assoc_enabled, circle_at, circle_of, dim};
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};
+56
View File
@@ -120,6 +120,62 @@ pub(super) fn pick_at(s: &Session, p: Vec2) -> Option<Handle> {
s.pick_object(&s.space(), p, ap).ok().flatten()
}
/// Most objects of a block reference looked at for one pick (nested references included).
const MAX_NESTED_PICK: usize = 100_000;
/// The circle or arc picked at `p`, in drawing coordinates: a circle or arc of the drawing, or
/// one inside the block reference picked there (nested references too), as AutoCAD's DIMRADIUS,
/// DIMDIAMETER and DIMJOGGED take one (#1967). Inside a reference it is the object under the
/// cursor, so a pick on a block's line is not a circle; one the reference scales unevenly is
/// drawn as an ellipse and is not taken either.
pub(super) fn circle_at(s: &Session, p: Vec2) -> Option<(Vec2, f64)> {
let h = pick_at(s, p)?;
// A circle with no size (a zero radius read from a file) makes a degenerate dimension.
let usable = |(c, r): &(Vec2, f64)| c.is_finite() && r.is_finite() && *r > 0.0;
if let Some(c) = circle_of(s, h) {
return Some(c).filter(usable);
}
let d = s.doc().ok()?;
let EntityKind::Insert(ins) = &d.entity(h)?.kind else { return None };
let ap = crate::cmd::curves::pick_aperture(s);
let mut nearest: Option<(f64, Option<(Vec2, f64)>)> = None;
let mut budget = MAX_NESTED_PICK;
// Inside a layout viewport, what its frozen layers hold isn't drawn there.
let frozen = s.state().ok().and_then(|st| st.active_viewport().map(|(_, vp)| vp.frozen_layers)).unwrap_or_default();
let inside = crate::snap::Inside::drawn(&frozen);
crate::snap::block_leaves(d, ins, &cadcraft_geom::Mat3::IDENTITY, None, 0, &mut budget, inside, &mut |entity, m, _| {
let k = &entity.kind;
// Measured on what is drawn, as any pick measures (text inside its box, a SOLID inside
// its fill, a ray only ahead of its start), on the object placed by the reference. A curve
// the reference scales unevenly is drawn as an ellipse, which placing the object doesn't
// make, so it is measured on its exactly placed primitives instead.
let dist = match (k, m.similarity_scale()) {
(EntityKind::Circle(_) | EntityKind::Arc(_) | EntityKind::Ellipse(_), None) => {
k.prims().iter().map(|pr| crate::cmd::curves::prim_distance(&crate::snap::xform_prim(pr, m), p)).fold(f64::INFINITY, f64::min)
}
_ => {
let mut placed = k.clone();
placed.transform(m);
crate::select::entity_distance(d, &cadcraft_doc::Entity::new(Handle(0), placed), p, ap / 4.0)
}
};
if !dist.is_finite() || dist > ap {
return;
}
let circle = m.similarity_scale().and_then(|scale| match k {
EntityKind::Circle(c) => Some((m.apply(c.center.xy()), c.radius * scale)),
EntityKind::Arc(a) => Some((m.apply(a.center.xy()), a.radius * scale)),
_ => None,
});
// The nearest wins; at the same distance, a circle or arc over anything else.
let better = nearest.is_none_or(|(best, held)| dist < best || (dist <= best && held.is_none() && circle.is_some()));
if better {
nearest = Some((dist, circle));
}
});
nearest.and_then(|(_, c)| c).filter(usable)
}
/// The straight or curved piece of `h` picked at `p`: a line, an arc, or the polyline segment nearest `p`.
pub(in crate::cmd) fn segment_at(s: &Session, h: Handle, p: Vec2) -> Option<Segment> {
match &s.doc().ok()?.entity(h)?.kind {
+2 -2
View File
@@ -1,4 +1,4 @@
use super::common::{DimText, add_dim, circle_of, dim, pick_at, text_at};
use super::common::{DimText, add_dim, circle_at, circle_of, dim, text_at};
use super::{Accept, DimKind, EntityKind, Input, Interactive, Prompt, Result, Session, Step, Value, Vec2, bad, json, point_param, targets};
fn radial(s: &mut Session, p: &Value, diameter: bool) -> Result<Value> {
@@ -75,7 +75,7 @@ impl Interactive for RadialM {
}
match (self.target, i) {
(None, Input::Point(p)) => {
match pick_at(s, p).and_then(|h| circle_of(s, h)) {
match circle_at(s, p) {
Some(t) => self.target = Some(t),
None => s.echo("Object selected is not a circle or arc."),
}
+2 -2
View File
@@ -8,7 +8,7 @@ use serde_json::{Value, json};
use super::super::helpers::v3;
use super::super::machines::{SelOutcome, SelectPhase};
use super::super::{CommandSpec, bad, bool_or, point_param, point_req, size_param, str_param, targets};
use super::{DimText, add_dim, circle_of, dim, dims_of, pick_at};
use super::{DimText, add_dim, circle_at, circle_of, dim, dims_of};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
@@ -332,7 +332,7 @@ impl Interactive for JoggedM {
return Ok(Step::Continue);
}
match (self.circle, self.center, self.at, i) {
(None, _, _, Input::Point(p)) => match pick_at(s, p).and_then(|h| circle_of(s, h)) {
(None, _, _, Input::Point(p)) => match circle_at(s, p) {
Some(t) => self.circle = Some(t),
None => s.echo("Object selected is not a circle or arc."),
},
+1
View File
@@ -86,6 +86,7 @@ pub(crate) fn paste(s: &mut Session, m: &Mat3) -> Result<Vec<Handle>> {
let old_h = e.handle;
let mut e = adopt(d, e, &renames);
e.kind.transform(m);
e.common.transform_moves(m);
d.ensure_layer(&e.common.layer);
out.push(e.handle);
copies.push((old_h, e.handle));
+20 -18
View File
@@ -604,24 +604,26 @@ pub fn seg_param(s: &Segment, p: Vec2) -> f64 {
/// Distance from `p` to an entity's geometry (prims; text and blocks by insertion point).
pub fn kind_distance(k: &EntityKind, p: Vec2) -> f64 {
k.prims()
.iter()
.map(|pr| match pr {
Prim::Seg(s) => s.closest(p).dist(p),
Prim::Circle(c) => c.closest(p).dist(p),
Prim::Ellipse(e) => e.closest(p).dist(p),
Prim::Spline(sp) => {
let pts = sp.tessellate(1e-3);
pts.windows(2).filter_map(|w| Some(Line::new(*w.first()?, *w.get(1)?).closest(p).dist(p))).fold(f64::INFINITY, f64::min)
}
Prim::Point(q) => q.dist(p),
Prim::Infinite { base, dir, .. } => Line::new(*base, *base + *dir).project(p).dist(p),
Prim::Fill(f) => {
let n = f.len();
(0..n).filter_map(|i| Some(Line::new(*f.get(i)?, *f.get((i + 1) % n)?).closest(p).dist(p))).fold(f64::INFINITY, f64::min)
}
})
.fold(f64::INFINITY, f64::min)
k.prims().iter().map(|pr| prim_distance(pr, p)).fold(f64::INFINITY, f64::min)
}
/// Distance from `p` to one primitive.
pub fn prim_distance(pr: &Prim, p: Vec2) -> f64 {
match pr {
Prim::Seg(s) => s.closest(p).dist(p),
Prim::Circle(c) => c.closest(p).dist(p),
Prim::Ellipse(e) => e.closest(p).dist(p),
Prim::Spline(sp) => {
let pts = sp.tessellate(1e-3);
pts.windows(2).filter_map(|w| Some(Line::new(*w.first()?, *w.get(1)?).closest(p).dist(p))).fold(f64::INFINITY, f64::min)
}
Prim::Point(q) => q.dist(p),
Prim::Infinite { base, dir, .. } => Line::new(*base, *base + *dir).project(p).dist(p),
Prim::Fill(f) => {
let n = f.len();
(0..n).filter_map(|i| Some(Line::new(*f.get(i)?, *f.get((i + 1) % n)?).closest(p).dist(p))).fold(f64::INFINITY, f64::min)
}
}
}
// ---------------- splines ----------------
+96 -13
View File
@@ -373,12 +373,12 @@ pub fn specs() -> Vec<CommandSpec> {
.noundo(),
CommandSpec::new("close", "Close", run_close).menu(&["File", "Close"]).key("Cmd+W").params("{index?}").noundo(),
CommandSpec::new("closeall", "Close All", run_closeall).menu(&["File", "Close All"]).enabled(always).noundo(),
CommandSpec::new("qsave", "Save", run_qsave_reporting).menu(&["File", "Save"]).key("Cmd+S").alias(&["save"]).params("{path?}").noundo(),
CommandSpec::new("qsave", "Save", run_qsave_reporting).menu(&["File", "Save"]).key("Cmd+S").alias(&["save"]).params("{path?, overwrite?: bool}").noundo(),
CommandSpec::new("saveas", "Save As...", run_saveas_reporting)
.menu(&["File", "Save As..."])
.key("Cmd+Shift+S")
.params(
"{path, version?: 2000|2004|2007|2010|2013|2018, binary?: bool, portableFonts?: bool (Windows fonts for Linux ones, in this file)}",
"{path, version?: 2000|2004|2007|2010|2013|2018, binary?: bool, portableFonts?: bool (Windows fonts for Linux ones, in this file), overwrite?: bool}",
)
.noundo(),
CommandSpec::new("document.switch", "Switch Drawing", run_switch).params("{index}").enabled(always).noundo(),
@@ -483,6 +483,7 @@ pub struct ReadFile {
binary_dxf: bool,
name: String,
path: Option<String>,
disk: Option<crate::disk_stamp::DiskStamp>,
}
/// Read and decode `path` (the slow half of `OPEN {path}`). Needs no session; runs anywhere.
@@ -513,8 +514,8 @@ pub fn read_file(path: &std::path::Path) -> std::result::Result<ReadFile, String
/// Add a [`read_file`] result to the session as the active drawing: the fast half of OPEN.
pub fn finish_open(s: &mut Session, f: ReadFile) -> Result<Value> {
let ReadFile { drawing, binary_dxf, name, path } = f;
let i = add_read(s, drawing, binary_dxf, &name, path);
let ReadFile { drawing, binary_dxf, name, path, disk } = f;
let i = add_read(s, drawing, binary_dxf, &name, path, disk);
super::blocks::xref::after_open(s, i);
super::image::after_open(s, i);
Ok(opened(s, i, true))
@@ -548,15 +549,24 @@ fn read_bytes(bytes: &[u8], name: &str, path: Option<String>) -> Result<ReadFile
}
}
}
Ok(ReadFile { drawing, binary_dxf: craft_dxf::is_binary(bytes), name: name.to_string(), path })
let disk = path.as_ref().map(|_| crate::disk_stamp::DiskStamp::of(bytes));
Ok(ReadFile { drawing, binary_dxf: craft_dxf::is_binary(bytes), name: name.to_string(), path, disk })
}
fn add_read(s: &mut Session, drawing: Drawing, binary_dxf: bool, name: &str, path: Option<String>) -> usize {
fn add_read(
s: &mut Session,
drawing: Drawing,
binary_dxf: bool,
name: &str,
path: Option<String>,
disk: Option<crate::disk_stamp::DiskStamp>,
) -> usize {
let notes = drawing.read_notes.clone();
let i = s.open_drawing(drawing, &file_name(name), path);
if let Some(st) = s.docs.get_mut(i) {
// QSAVE keeps a binary DXF binary.
st.binary_dxf = binary_dxf;
st.disk = disk;
}
for note in notes {
s.echo(note);
@@ -565,8 +575,8 @@ fn add_read(s: &mut Session, drawing: Drawing, binary_dxf: bool, name: &str, pat
}
pub(crate) fn open_bytes(s: &mut Session, bytes: &[u8], name: &str, path: Option<String>) -> Result<usize> {
let ReadFile { drawing, binary_dxf, name, path } = read_bytes(bytes, name, path)?;
Ok(add_read(s, drawing, binary_dxf, &name, path))
let ReadFile { drawing, binary_dxf, name, path, disk } = read_bytes(bytes, name, path)?;
Ok(add_read(s, drawing, binary_dxf, &name, path, disk))
}
/// OPEN's reply: the drawing's index and what reading it left out.
@@ -669,18 +679,90 @@ fn run_closeall(s: &mut Session, _p: &Value) -> Result<Value> {
ok()
}
pub(crate) fn save_to(s: &mut Session, path: &str) -> Result<(usize, Vec<String>)> {
pub(crate) fn save_to(s: &mut Session, path: &str, overwrite: bool) -> Result<(usize, Vec<String>)> {
let opts = SaveAs { binary: s.state()?.binary_dxf && is_dxf(path), ..SaveAs::default() };
save_as(s, "save", path, &opts)
save_as(s, "save", path, &opts, overwrite)
}
/// `overwrite`: save over the drawing's own file although another program changed it.
fn overwrite_param(cmd: &str, p: &Value) -> Result<bool> {
match p.get("overwrite") {
None | Some(Value::Null) => Ok(false),
Some(Value::Bool(b)) => Ok(*b),
Some(_) => Err(bad(cmd, "`overwrite` must be true or false")),
}
}
/// Whether `a` and `b` name the same file: the same text, or the same file once resolved
/// (`./plan.dxf` and `plan.dxf`, a relative and an absolute path, a link).
#[cfg(not(target_arch = "wasm32"))]
fn same_file(a: &str, b: &str) -> bool {
a == b || matches!((std::fs::canonicalize(a), std::fs::canonicalize(b)), (Ok(a), Ok(b)) if a == b)
}
/// What saving the active drawing to `path` would replace, before anything is written: whether the
/// drawing's own file still holds what was opened or last saved here. [`OnDisk::Same`] when there is
/// nothing to compare: another file, a file that is gone, not a drawing file, or a target the
/// automation roots refuse (the save refuses it first, [`check_disk`]). The drawing's own path is
/// resolved only where it may be read. A user's save asks with this; [`check_disk`] refuses with it.
///
/// [`OnDisk::Same`]: crate::disk_stamp::OnDisk::Same
pub fn on_disk(s: &Session, path: &str) -> crate::disk_stamp::OnDisk {
use crate::disk_stamp::OnDisk;
#[cfg(not(target_arch = "wasm32"))]
{
let Ok(st) = s.state() else { return OnDisk::Same };
let Some(stamp) = st.disk else { return OnDisk::Same };
if !is_drawing_file(path) || crate::file_access::check_write(path).is_err() {
return OnDisk::Same;
}
let own = st.path.as_deref().filter(|own| *own == path || (crate::file_access::check_read(own).is_ok() && same_file(own, path)));
if own.is_none() {
return OnDisk::Same;
}
crate::disk_stamp::compare(std::path::Path::new(path), stamp, MAX_DRAWING_BYTES)
}
#[cfg(target_arch = "wasm32")]
{
let _ = (s, path);
OnDisk::Same
}
}
/// Refuse to save over the drawing's own file when it no longer holds what was opened or last
/// saved here (another program or person wrote it, and a save would silently replace their work),
/// or when it can't be read to tell ([`on_disk`]).
///
/// The file is compared only where the save may go: with automation roots in force
/// ([`crate::file_access`]), a target outside the write root is refused first, as the write
/// itself would be.
fn check_disk(s: &Session, cmd: &str, path: &str, overwrite: bool) -> Result<()> {
if overwrite || !is_drawing_file(path) || s.state()?.disk.is_none() {
return Ok(());
}
#[cfg(not(target_arch = "wasm32"))]
crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?;
let keep = "Nothing was saved. Save under another name (saveas), or reopen the file to see what it holds; \
`overwrite: true` replaces it anyway.";
match on_disk(s, path) {
crate::disk_stamp::OnDisk::Same => Ok(()),
crate::disk_stamp::OnDisk::Changed => {
Err(bad(cmd, format!("{path} changed on disk after it was opened: another program or person saved it. {keep}")))
}
crate::disk_stamp::OnDisk::Unchecked(e) => {
Err(bad(cmd, format!("{path} may have changed on disk after it was opened: it could not be read to check ({e}). {keep}")))
}
}
}
/// 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. Also an
/// image's notes ([`write_noted`]).
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(usize, Vec<String>)> {
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs, overwrite: bool) -> 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."));
}
check_disk(s, cmd, path, overwrite)?;
// A saved drawing carries the folder's plot style tables its layouts use.
if is_drawing_file(path) {
let st = s.state_mut()?;
@@ -974,6 +1056,7 @@ fn commit_save(s: &mut Session, path: &str, bytes: &[u8], store: impl FnOnce(&st
st.saved = st.drawing().clone();
st.path = Some(path.to_string());
st.title = file_name(path);
st.disk = Some(crate::disk_stamp::DiskStamp::of(bytes));
// A BEgin group still open when the drawing is saved ends there.
st.end_undo_group();
Ok(bytes.len())
@@ -993,7 +1076,7 @@ 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, notes) = save_to(s, &path)?;
let (n, notes) = save_to(s, &path, overwrite_param("qsave", p)?)?;
let mut r = saved(&path, n);
report_notes(s, &mut r, notes);
Ok(r)
@@ -1002,7 +1085,7 @@ fn run_save(s: &mut Session, p: &Value) -> Result<Value> {
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, notes) = save_as(s, "saveas", &path, &opts)?;
let (n, notes) = save_as(s, "saveas", &path, &opts, overwrite_param("saveas", p)?)?;
let mut r = saved(&path, n);
report_notes(s, &mut r, notes);
if is_drawing_file(&path) {
+43 -26
View File
@@ -1,13 +1,13 @@
//! `grip.*` commands: the undoable, scriptable form of grip editing (see `crate::grips`).
use cadcraft_doc::{Entity, EntityKind, Handle};
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle};
use cadcraft_geom::{Mat3, Vec2, Vec3};
use serde_json::{Value, json};
use super::curves;
use super::{CommandSpec, bad, bool_or, point_param, point_req, str_param, targets};
use crate::grips::{GripAction, GripMode, grip_action, mode_matrix, stretch_grip};
use crate::grips::{GripAction, GripMode, grip_action, mode_matrix, shown_grips, stretch_shown};
use crate::{EngineError, Result, Session};
pub fn specs() -> Vec<CommandSpec> {
@@ -46,25 +46,28 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result<Value> {
return Err(EngineError::Other("The object is on a locked layer.".into()));
}
let e = curves::entity(s, h)?;
let k = stretch_grip(&e.kind, i, to).ok_or_else(|| bad(cmd, "no such grip, or the result would be degenerate"))?;
let mut edits = vec![(h, k)];
let view = s.anno_view();
let doc = s.doc()?;
let ne = stretch_shown(doc, &e, i, to, view).ok_or_else(|| bad(cmd, "no such grip, or the result would be degenerate"))?;
let mut edits = vec![(h, ne)];
// The other `handles` with a grip on the same point stretch with it (connected objects stay
// connected); locked ones and edits that would be degenerate are left alone.
let from = e.kind.grips().get(i).copied().unwrap_or(to);
let from = shown_grips(doc, &e, view).get(i).copied().unwrap_or(to);
let tol = 1e-9 * (1.0 + from.len());
for o in targets(s, p)? {
if o == h || edits.iter().any(|(x, _)| *x == o) || curves::is_locked(s, o) {
continue;
}
let Ok(oe) = curves::entity(s, o) else { continue };
if let Some(j) = oe.kind.grips().iter().position(|g| g.near(from, tol))
&& let Some(k) = stretch_grip(&oe.kind, j, to)
if let Some(j) = shown_grips(doc, &oe, view).iter().position(|g| g.near(from, tol))
&& let Some(ne) = stretch_shown(doc, &oe, j, to, view)
{
edits.push((o, k));
edits.push((o, ne));
}
}
let d = s.doc_mut()?;
for (o, k) in &mut edits {
for (o, ne) in &mut edits {
let (k, moves) = (&mut ne.kind, &ne.common.anno_moves);
// A dimension's text moved by its grip: with DIMTMOVE 0 the dimension line follows.
if let cadcraft_doc::EntityKind::Dimension(dm) = k
&& let Some(cadcraft_doc::EntityKind::Dimension(old)) = d.entity(*o).map(|e| &e.kind)
@@ -73,14 +76,17 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result<Value> {
let st = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides);
st.follow_text(dm, d.header.f64("DIMSCALE", 1.0));
}
d.modify_entity(*o, |e| e.kind = k.clone())?;
d.modify_entity(*o, |e| {
e.kind = k.clone();
e.common.anno_moves = moves.clone();
})?;
}
Ok(json!({ "handle": h.hex(), "handles": edits.iter().map(|(o, _)| o.hex()).collect::<Vec<_>>() }))
}
/// Z coordinate of grip `index` on `kind` (matching `EntityKind::grips()` order), when the
/// entity stores a 3D position for that grip.
pub(super) fn grip_z(kind: &EntityKind, index: usize) -> Option<f64> {
fn grip_z(kind: &EntityKind, index: usize) -> Option<f64> {
let text_z = |t: &cadcraft_doc::Text| match (t.halign, t.valign) {
(cadcraft_doc::HAlign::Left, cadcraft_doc::VAlign::Baseline) | (cadcraft_doc::HAlign::Aligned | cadcraft_doc::HAlign::Fit, _) => t.insert.z,
_ => t.align_pt.unwrap_or(t.insert).z,
@@ -151,10 +157,17 @@ fn base_point(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec2>
.or_else(|| hs.first().copied())
.ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?;
let i = index_param(cmd, p)?;
let g = curves::entity(s, h)?.kind.grips();
let g = shown_grips(s.doc()?, &curves::entity(s, h)?, s.anno_view());
g.get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))
}
/// The displayed grip's planar point and its Z, when the entity has one.
pub(super) fn shown_grip_location(d: &Drawing, e: &Entity, index: usize, view: Option<f64>) -> Option<(Vec2, Option<f64>)> {
let kind = d.anno_shown_in(e, view);
let point = kind.grips().get(index).copied()?;
Some((point, grip_z(&kind, index)))
}
/// 3D base point for SCALE: explicit `base` (with optional Z or ELEVATION), or the selected grip's
/// full 3D position so the grip stays stationary in all three coordinates.
fn base_point_3d(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec3> {
@@ -169,8 +182,8 @@ fn base_point_3d(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec
.ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?;
let i = index_param(cmd, p)?;
let e = curves::entity(s, h)?;
let g = e.kind.grips().get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))?;
Ok(match grip_z(&e.kind, i) {
let (g, z) = shown_grip_location(s.doc()?, &e, i, s.anno_view()).ok_or_else(|| bad(cmd, "no such grip"))?;
Ok(match z {
Some(z) => Vec3::new(g.x, g.y, z),
None => super::modify::at_elevation(s, g),
})
@@ -201,7 +214,7 @@ fn run_grip_stretch(s: &mut Session, p: &Value) -> Result<Value> {
None => {
let base = match point_param(p, "base") {
Some(b) => b,
None => curves::entity(s, h0)?.kind.grips().get(i0).copied().ok_or_else(|| bad(cmd, "no such grip"))?,
None => shown_grips(s.doc()?, &curves::entity(s, h0)?, s.anno_view()).get(i0).copied().ok_or_else(|| bad(cmd, "no such grip"))?,
};
point_req(cmd, p, "to")? - base
}
@@ -245,8 +258,9 @@ const MAX_GRIPS: usize = 1000;
/// The objects as they'd be after moving the grips `hot` by `delta`, with the grips of `others`
/// that sit on a hot grip's point (connected objects stay connected). Locked objects and edits
/// that would be degenerate are left out; several hot grips of one object move together.
pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle], delta: Vec2) -> Vec<(Handle, EntityKind)> {
pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle], delta: Vec2) -> Vec<(Handle, Entity)> {
let Ok(d) = s.doc() else { return Vec::new() };
let view = s.anno_view();
// Every grip to move, per object, with its target point.
let mut moves: Vec<(Handle, Vec<(usize, Vec2)>)> = Vec::new();
let mut add = |h: Handle, i: usize, to: Vec2| match moves.iter_mut().find(|(x, _)| *x == h) {
@@ -258,14 +272,14 @@ pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle],
None => moves.push((h, vec![(i, to)])),
};
for &(h, i) in hot.iter().take(MAX_GRIPS) {
let Some(from) = d.entity(h).and_then(|e| e.kind.grips().get(i).copied()) else { continue };
let Some(from) = d.entity(h).and_then(|e| shown_grips(d, e, view).get(i).copied()) else { continue };
add(h, i, from + delta);
let tol = 1e-9 * (1.0 + from.len());
for &o in others.iter().take(MAX_GRIPS) {
if o == h {
continue;
}
if let Some(j) = d.entity(o).and_then(|e| e.kind.grips().iter().position(|g| g.near(from, tol))) {
if let Some(j) = d.entity(o).and_then(|e| shown_grips(d, e, view).iter().position(|g| g.near(from, tol))) {
add(o, j, from + delta);
}
}
@@ -276,16 +290,16 @@ pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle],
continue;
}
let Some(e) = d.entity(h) else { continue };
let mut k = e.kind.clone();
let mut ne = (**e).clone();
let mut changed = false;
for (i, to) in mv {
if let Some(nk) = stretch_grip(&k, i, to) {
k = nk;
if let Some(n) = stretch_shown(d, &ne, i, to, view) {
ne = n;
changed = true;
}
}
if changed {
out.push((h, k));
out.push((h, ne));
}
}
out
@@ -297,16 +311,19 @@ pub(super) fn stretch_grips(s: &mut Session, hot: &[(Handle, usize)], others: &[
let edits = stretched(s, hot, others, delta);
let d = s.doc_mut()?;
let mut out = Vec::new();
for (h, k) in edits {
for (h, ne) in edits {
if copy {
let (Some(sp), Some(e)) = (d.space_of(h), d.entity(h).map(|e| (**e).clone())) else { continue };
let Some(sp) = d.space_of(h) else { continue };
let nh = d.new_handle();
if let Some(st) = d.space_mut(&sp) {
st.push(Entity { handle: nh, kind: k, ..e });
st.push(Entity { handle: nh, ..ne });
out.push(nh);
}
} else {
d.modify_entity(h, |e| e.kind = k)?;
d.modify_entity(h, |e| {
e.kind = ne.kind;
e.common.anno_moves = ne.common.anno_moves;
})?;
out.push(h);
}
}
+10 -4
View File
@@ -104,14 +104,16 @@ impl GripEdit {
if self.hot.contains(&(h, i)) || self.hot.len() >= MAX_HOT {
return Ok(());
}
let p = s.grips_of(h)?.get(i).copied().ok_or_else(|| other("no such grip"))?;
let d = s.doc()?;
let e = d.entity(h).ok_or_else(|| other("no such object"))?;
let (p, z) = super::gripcmds::shown_grip_location(d, e, i, s.anno_view()).ok_or_else(|| other("no such grip"))?;
// After the lookup: a missing object or grip stays the error it was.
if !shown(s, h) {
return Ok(());
}
if self.hot.is_empty() {
self.base = p;
self.base_z = s.doc().ok().and_then(|d| d.entity(h)).and_then(|e| super::gripcmds::grip_z(&e.kind, i));
self.base_z = z;
self.targets.push(h);
self.targets.extend(s.selection().into_iter().filter(|x| *x != h && shown(s, *x)));
} else if !self.targets.contains(&h) {
@@ -131,7 +133,7 @@ impl GripEdit {
continue;
}
let Some(e) = st.doc.entity(h).filter(|e| st.shows(e)) else { continue };
let gs = e.kind.grips();
let gs = crate::grips::shown_grips(&st.doc, e, s.anno_view());
// The nearest grip of this object within the tolerance.
let best = gs
.iter()
@@ -491,7 +493,11 @@ impl Interactive for GripEdit {
};
let Ok(d) = s.doc() else { return Vec::new() };
let mut out: Vec<EntityKind> = if self.mode == GripMode::Stretch {
super::gripcmds::stretched(s, &self.hot, &self.targets, c - base).into_iter().take(500).map(|(_, k)| k).collect()
super::gripcmds::stretched(s, &self.hot, &self.targets, c - base)
.into_iter()
.take(500)
.map(|(_, e)| d.anno_shown_in(&e, s.anno_view()))
.collect()
} else {
match self.matrix(c) {
Some(m) => self
+9 -1
View File
@@ -1,5 +1,6 @@
//! Layouts, paper-space viewports, page setup and plotting: LAYOUT (new/delete/rename/copy/saveas),
//! MVIEW / VPORTS, viewport scale/lock/layer settings, PAGESETUP, PLOT and EXPORTPDF.
//! MVIEW / VPORTS, viewport scale/lock/layer settings, PAGESETUP / -PAGESETUP, PLOT / -PLOT and
//! EXPORTPDF.
//!
//! Plotting goes through the host's [`super::file::IoHooks::plot`] hook so the engine stays
//! I/O-agnostic.
@@ -14,6 +15,7 @@ use super::{CommandSpec, bad, bool_or, find_command, point_param, point_value, s
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
use viewports::MviewM;
mod plot_prompts;
mod plotstyle;
pub(crate) use plotstyle::keep_used_folder_copies;
mod prompts;
@@ -92,6 +94,12 @@ pub fn specs() -> Vec<CommandSpec> {
.key("Cmd+P")
.alias(&["print"])
.params("{path? (else returns base64 `data`), layout?: current|\"Model\", device?: \"CADCraft PDF\"|\"CADCraft PNG\"|\"CADCraft SVG\" | a plotter from PLOTTERMANAGER | \"None\" (default: a layout's page setup device; Model, or \"None\": no device, PDF; a device sets the output format and the papers), paper?: the device's paper (default: a layout keeps its page setup's; Model takes the device's default), landscape?, fit?: bool, scale?: number | \"1:50\", center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?: bool, plotTransparency?: bool (default: the page setup's; PLOTTRANSPARENCYOVERRIDE 0/2 overrides it), plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]]} (typed or from the menu: the Plot dialog)"),
CommandSpec::new("-pagesetup", "Page Setup Manager...", run_pagesetup)
.params("as PAGESETUP (typed: asks the layout, then each page setup option in turn, and stores the answers)")
.interactive(|_| Ok(Box::new(plot_prompts::PlotM::page_setup()))),
CommandSpec::new("-plot", "Print...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "plot")?, "plot"))
.params("as PLOT (typed: asks for a detailed configuration or not, the plot options, the output file, whether to save them to the page setup, then plots)")
.interactive(|_| Ok(Box::new(plot_prompts::PlotM::plot()))),
CommandSpec::new("exportpdf", "Export to PDF...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "exportpdf")?, "exportpdf"))
.menu(&["File", "Export to PDF..."])
.params("{path? (else returns base64 `data`), layout?, device? (its papers; the output stays PDF), paper?, landscape?, fit?, scale?, center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?, plotTransparency?, plotArea?, window?} (as PLOT)"),
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -190,10 +190,11 @@ pub(crate) fn explode_kind(d: &cadcraft_doc::Drawing, e: &Entity) -> Option<Vec<
// An annotative object explodes into plain objects as it draws at the current annotation scale.
if cadcraft_doc::is_annotative(e) {
let mut se = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Scaled(f) => cadcraft_doc::anno_scaled(e, f),
cadcraft_doc::AnnoDraw::Scaled { factor, by } => cadcraft_doc::anno_placed(e, factor, by),
_ => e.clone(),
};
se.common.anno_scales.clear();
se.common.anno_moves.clear();
return explode_kind(d, &se);
}
match &e.kind {
+5 -1
View File
@@ -7,7 +7,10 @@ use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, er
pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<Vec<Handle>> {
refuse_ole_frames(s, hs, m, copy)?;
edit_entities(s, hs, copy, |e| e.kind.transform(m))
edit_entities(s, hs, copy, |e| {
e.kind.transform(m);
e.common.transform_moves(m);
})
}
/// MIRROR's default hatch policy retains the fill direction while reflecting its boundary.
@@ -40,6 +43,7 @@ pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64,
refuse_ole_frames(s, hs, &m, copy)?;
edit_entities(s, hs, copy, |e| {
e.kind.transform(&m);
e.common.transform_moves(&m);
e.kind.scale_heights(base.z, f);
e.common.thickness *= f;
})
+65 -21
View File
@@ -1,7 +1,8 @@
use cadcraft_doc::Drawing;
use cadcraft_geom::Bounds2;
use super::{
Arc, EngineError, Entity, EntityKind, Handle, Line, PolyVertex, Polyline, Prim, Result, Segment, Session, TAU, Vec2, angle_in_sweep, arc,
Arc, EngineError, Entity, EntityKind, Handle, Line, Mat3, PolyVertex, Polyline, Prim, Result, Segment, Session, TAU, Vec2, angle_in_sweep, arc,
ccw_sweep, intersect_ext, line, lwpoly, norm_angle,
};
@@ -34,15 +35,17 @@ pub(crate) fn edge_segments_over(s: &Session, edges: Edges, exclude: Handle, ove
let space = s.space();
let store = d.space(&space).ok_or(EngineError::NoDocument)?;
let mut out = Vec::new();
// One bound for the objects visited inside all the references together: Quick mode looks at
// every reference of the space on every preview, so a bound for each reference alone would
// leave the whole look unbounded. References past the bound give no edges inside them.
let mut budget = crate::snap::MAX_BLOCK_LEAVES;
let mut add = |kind: &EntityKind| {
if edges.implied
&& let Some(segs) = implied_edge(kind)
{
out.extend(segs);
return;
}
for p in kind.prims() {
out.extend(prim_to_segments(&p));
push_edge(&mut out, d, kind, edges.implied, None);
// A block reference is an edge by what it draws: the objects inside it that are drawn,
// nested references expanded, each placed by the reference and giving the edges the same
// object gives outside a block. The reference's own attributes are not among them.
if let EntityKind::Insert(ins) = kind {
crate::snap::reference_leaves(d, ins, &mut budget, &mut |part, place| push_edge(&mut out, d, part, edges.implied, Some(place)));
}
};
// An object is an edge when it is one of `edges.only` (all of them: `None`). A trim leaves
@@ -84,15 +87,56 @@ pub(crate) fn edge_segments_over(s: &Session, edges: Edges, exclude: Handle, ove
Ok(out)
}
/// `k` as an implied edge (EDGEMODE 1), for lines, arcs and open polylines.
fn implied_edge(k: &EntityKind) -> Option<Vec<Segment>> {
/// Adds to `out` the segments `kind` gives as a cutting or boundary edge (`implied`: EDGEMODE 1,
/// [`implied_edge`]). `place`: the transform of the block reference that draws `kind`, for an
/// object inside one; a circle or an arc under a non-uniform scale is then the ellipse it is
/// drawn as. A proxy gives the graphics drawing `d` draws of it ([`drawn_prims`]).
fn push_edge(out: &mut Vec<Segment>, d: &Drawing, kind: &EntityKind, implied: bool, place: Option<&Mat3>) {
let prims = match implied.then(|| implied_edge(kind, place)).flatten() {
Some(prims) => prims,
None => drawn_prims(d, kind).iter().map(|p| placed(p, place)).collect(),
};
for p in &prims {
out.extend(prim_to_segments(p));
}
}
/// The primitives `kind` gives as an edge. A proxy (a record kept as read) gives those of the
/// graphics it draws in drawing `d`: a graphic that is hidden or on a layer that is off or frozen
/// is not drawn and is no edge, in a block reference and in the drawing itself.
fn drawn_prims(d: &Drawing, kind: &EntityKind) -> Vec<Prim> {
match kind {
EntityKind::Unknown(u) => crate::snap::drawn_graphics(d, u, &[]).flat_map(|g| g.kind.prims()).collect(),
k => k.prims(),
}
}
/// `p` where the block reference with transform `place` draws it (`None`: as it is).
fn placed(p: &Prim, place: Option<&Mat3>) -> Prim {
match place {
Some(m) => crate::snap::xform_prim(p, m),
None => p.clone(),
}
}
/// `k` as an implied edge (EDGEMODE 1), for lines, arcs and open polylines. `place`: the transform
/// of the block reference that draws `k`, for an object inside one. A line is placed first and
/// run on after, so it runs on as far in drawing units as outside a block whatever the scale of
/// the references above it; an arc is made whole and then placed.
fn implied_edge(k: &EntityKind, place: Option<&Mat3>) -> Option<Vec<Prim>> {
const FAR: f64 = 1e8;
let whole = |a: &Arc| Segment::Arc { arc: Arc { start: 0.0, end: TAU - 1e-12, ..*a }, ccw: true };
let whole = |a: &Arc| placed(&Prim::Seg(Segment::Arc { arc: Arc { start: 0.0, end: TAU - 1e-12, ..*a }, ccw: true }), place);
// Run a segment on past its start and/or its end.
let run_on = |sg: Segment, back: bool, fwd: bool| match sg {
Segment::Line(l) => {
let d = (l.b - l.a).normalized();
Segment::Line(Line::new(if back { l.a - d * FAR } else { l.a }, if fwd { l.b + d * FAR } else { l.b }))
let (a, b, d) = match place {
// The direction is taken once the line is placed, and only a line with no length
// at all has none: a line very short in its block or drawn very short by a small
// scale still runs on along itself.
Some(m) => (m.apply(l.a), m.apply(l.b), crate::snap::placed_dir(l.b - l.a, m)),
None => (l.a, l.b, (l.b - l.a).normalized()),
};
Prim::Seg(Segment::Line(Line::new(if back { a - d * FAR } else { a }, if fwd { b + d * FAR } else { b })))
}
Segment::Arc { arc, .. } => whole(&arc),
};
@@ -100,14 +144,14 @@ fn implied_edge(k: &EntityKind) -> Option<Vec<Segment>> {
EntityKind::Line(l) => Some(vec![run_on(Segment::Line(Line::new(l.a.xy(), l.b.xy())), true, true)]),
EntityKind::Arc(a) => Some(vec![whole(&Arc::new(a.center.xy(), a.radius, a.start, a.end))]),
EntityKind::LwPolyline(p) if !p.closed => {
let mut segs = Polyline { vertices: p.vertices.clone(), closed: false }.segments();
let segs = Polyline { vertices: p.vertices.clone(), closed: false }.segments();
let last = segs.len().checked_sub(1)?;
for (i, sg) in segs.iter_mut().enumerate() {
if i == 0 || i == last {
*sg = run_on(*sg, i == 0, i == last);
}
}
Some(segs)
Some(
segs.iter()
.enumerate()
.map(|(i, sg)| if i == 0 || i == last { run_on(*sg, i == 0, i == last) } else { placed(&Prim::Seg(*sg), place) })
.collect(),
)
}
_ => None,
}
+1
View File
@@ -202,6 +202,7 @@ fn chspace(s: &mut Session, hs: &[Handle], to: Option<&str>, vp: Option<Handle>)
}
let mut e = e;
e.kind.transform(&m);
e.common.transform_moves(&m);
d.remove_entity(*h);
if let Some(st) = d.space_mut(&target) {
st.push(e);
+2 -2
View File
@@ -70,8 +70,8 @@ pub(crate) fn editor_for(s: &Session, h: Handle) -> Option<crate::TextEditor> {
// Annotative text and dimensions are drawn scaled to the current annotation scale: the box
// follows what is drawn. Multiline text keeps its stored height (it is written back from it).
let scaled = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Scaled(f) if matches!(e.kind, EntityKind::Text(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_)) => {
Some(cadcraft_doc::anno_scaled(e, f))
cadcraft_doc::AnnoDraw::Scaled { factor, by } if matches!(e.kind, EntityKind::Text(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_)) => {
Some(cadcraft_doc::anno_placed(e, factor, by))
}
_ => None,
};
+2
View File
@@ -35,6 +35,7 @@ pub const PROFILE_VARS: &[&str] = &[
"QPMODE",
"SELECTIONEFFECT",
"SELECTIONPREVIEW",
"SELECTIONANNODISPLAY",
"PREVIEWEFFECT",
"PREVIEWFILTER",
"GRIPS",
@@ -168,6 +169,7 @@ pub fn reset(s: &mut Session) {
st.selectionpreview = d.selectionpreview;
st.previeweffect = d.previeweffect;
st.previewfilter = d.previewfilter;
st.selectionannodisplay = d.selectionannodisplay;
st.grips = d.grips;
st.gripobjlimit = d.gripobjlimit;
st.selectionarea = d.selectionarea;
+12 -4
View File
@@ -211,7 +211,7 @@ pub fn find_device(name: &str) -> Option<PlotterConfig> {
}
/// The paper of `dev` called `name`, also by a standard size's short name (`A3`, `Letter`…).
fn device_paper<'a>(dev: &'a PlotterConfig, name: &str) -> Option<&'a DevicePaper> {
pub(crate) fn device_paper<'a>(dev: &'a PlotterConfig, name: &str) -> Option<&'a DevicePaper> {
dev.paper(name).or_else(|| dev.paper(cadcraft_render::paper_size(name)?.name))
}
@@ -293,6 +293,14 @@ fn path_output(path: &str) -> Option<PlotOutput> {
PlotOutput::parse(&std::path::Path::new(path).extension()?.to_string_lossy())
}
/// Why `dev` cannot write the file `path`: the path's extension asks for another format than the
/// device writes. `None` for a path the device can write (its own format, or an extension that
/// names none).
pub(crate) fn path_refusal(dev: &PlotterConfig, path: &str) -> Option<String> {
let want = path_output(path)?;
(dev.output != want).then(|| format!("plotter `{}` writes {}, but the path asks for {}", dev.name, dev.output.as_str(), want.as_str()))
}
/// The options PLOT / EXPORTPDF hand the plotter with `device` and the device's papers
/// resolved: `device` (else the layout's page setup device) picks the output (`output`: pdf,
/// png or svg; EXPORTPDF always writes PDF) and `resolution`; a paper of the device becomes
@@ -330,10 +338,10 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result<Value> {
format!("can't tell the format of `{path}`: give a path ending in .png, .svg or .pdf, or set `output` to png, svg or pdf"),
));
}
if let (Some(want), Some(dev), true) = (by_path, &dev, given.is_some_and(|n| !n.is_empty()))
&& dev.output != want
if let (Some(_), Some(dev), true) = (by_path, &dev, given.is_some_and(|n| !n.is_empty()))
&& let Some(why) = str_param(p, "path").and_then(|path| path_refusal(dev, path))
{
return Err(bad(cmd, format!("plotter `{}` writes {}, but the path asks for {}", dev.name, dev.output.as_str(), want.as_str())));
return Err(bad(cmd, why));
}
// An `output` that says another format than the path's extension is refused too, as a device
// that does is: either way the file would not hold what its name says.
+32 -2
View File
@@ -103,7 +103,12 @@ pub fn specs() -> Vec<CommandSpec> {
.params("{name, value}")
.transparent()
.interactive(|_| Ok(Box::new(SetvarM::default()))),
CommandSpec::new("getvar", "Get Variable", run_getvar).params("{name}").enabled(always).noundo(),
CommandSpec::new("getvar", "Get Variable", run_getvar)
.params("{name}")
.enabled(always)
.noundo()
.transparent()
.interactive(|_| Ok(Box::new(GetvarM))),
CommandSpec::new("sysvars", "List System Variables", |s, _| Ok(crate::sysvars::list(s))).enabled(always).noundo(),
]
}
@@ -237,7 +242,7 @@ impl Interactive for SetvarM {
}
}
}
(Some(n), Input::Text(t)) => match crate::sysvars::set(s, &n, &Value::String(t)) {
(Some(n), Input::Text(t)) => match crate::sysvars::set(s, &n, &crate::sysvars::typed_value(&n, t)) {
Ok(()) => {
s.touch();
Ok(Step::Done)
@@ -252,6 +257,31 @@ impl Interactive for SetvarM {
}
}
/// GETVAR at the command line: "Enter variable name", then the value is echoed, so a drawing's
/// settings (`GETVAR DIMSCALE`) can be read without changing them (#3273). Run without a name it
/// said only that `name` was required.
struct GetvarM;
impl Interactive for GetvarM {
fn name(&self) -> &'static str {
"GETVAR"
}
fn prompt(&self, _s: &Session) -> Prompt {
// Space ends the name, as for SETVAR.
Prompt::new("Enter variable name", Accept { number: true, ..Accept::TEXT })
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if let Input::Text(t) = i {
let n = t.trim().to_ascii_uppercase();
match crate::sysvars::get(s, &n) {
Some(v) => s.echo(format!("{n} = {}", show_value(&v))),
None => s.echo(format!("Unknown variable {n}. Type SETVAR ? to list variables.")),
}
}
Ok(Step::Done)
}
}
fn run_getvar(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("getvar", "`name` is required"))?;
let v = crate::sysvars::get(s, name).ok_or_else(|| bad("getvar", format!("unknown variable `{name}`")))?;
+56
View File
@@ -0,0 +1,56 @@
//! What a drawing file held when this session last read or wrote it.
//!
//! CADCraft keeps no file open while a drawing is edited: it reads the bytes and later replaces the
//! file atomically. Nothing then stops another program (another CAD program on a shared folder, a
//! sync client, another CADCraft) from saving the same file in between, and a plain save would
//! silently replace that work. A save over the drawing's own file therefore first checks that the
//! file still holds what was read or last written, and refuses otherwise (QSAVE/SAVEAS
//! `overwrite: true` replaces it anyway).
use std::hash::{DefaultHasher, Hasher};
/// The length and a 64-bit hash of a file's bytes. The hash only has to notice a change made by
/// someone else within this process's lifetime, so the standard library's hasher is enough.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DiskStamp {
len: u64,
hash: u64,
}
impl DiskStamp {
pub fn of(bytes: &[u8]) -> Self {
let mut h = DefaultHasher::new();
h.write(bytes);
DiskStamp { len: bytes.len() as u64, hash: h.finish() }
}
}
/// What a file holds compared with a [`DiskStamp`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum OnDisk {
/// It holds what the stamp says, or it is gone (a file that is gone has nothing to lose).
Same,
/// It holds something else.
Changed,
/// It could not be read; the reason.
Unchecked(String),
}
/// What the file at `path` holds compared with `stamp`. Only a file of the stamp's length is read,
/// up to `max` or that length if this session wrote more.
#[cfg(not(target_arch = "wasm32"))]
pub fn compare(path: &std::path::Path, stamp: DiskStamp, max: usize) -> OnDisk {
match std::fs::metadata(path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return OnDisk::Same,
Err(e) => return OnDisk::Unchecked(e.to_string()),
Ok(meta) if meta.len() != stamp.len => return OnDisk::Changed,
Ok(_) => {}
}
let cap = max.max(usize::try_from(stamp.len).unwrap_or(usize::MAX));
match crate::capped_read::read_capped(path, cap) {
Ok(bytes) if DiskStamp::of(&bytes) == stamp => OnDisk::Same,
Ok(_) => OnDisk::Changed,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => OnDisk::Same,
Err(e) => OnDisk::Unchecked(e.to_string()),
}
}
+10
View File
@@ -48,6 +48,9 @@ pub struct DocState {
/// The Block Editor (BEDIT), when it is open: `doc` is then the editor's drawing, and the
/// drawing itself waits in it ([`DocState::drawing`]).
pub block_edit: Option<blockedit::BlockEdit>,
/// What the drawing's file held when it was read or last saved here: a save over it checks
/// that nobody else wrote it in between ([`crate::disk_stamp`]).
pub disk: Option<crate::disk_stamp::DiskStamp>,
/// The user was told that the current UCS is tilted ([`Session::note_tilted_ucs`]).
pub ucs_tilted_noted: bool,
/// What the last erase removed, for OOPS.
@@ -87,6 +90,7 @@ impl DocState {
uid: NEXT_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
binary_dxf: false,
block_edit: None,
disk: None,
ucs_tilted_noted: false,
erased: Default::default(),
fonts_noted: String::new(),
@@ -171,6 +175,12 @@ impl DocState {
_ => None,
}
}
/// The annotation scale model space is edited at in the active MSPACE viewport: the
/// viewport's scale (drawing units per paper unit, as the renderer draws it there); `None`
/// outside one (the current annotation scale applies).
pub fn anno_view(&self) -> Option<f64> {
self.active_viewport().map(|(_, v)| v.view_height / v.height).filter(|f| f.is_finite() && *f > 0.0)
}
/// The layers frozen in the active MSPACE viewport (VPLAYER, "VP Freeze"): that viewport does
/// not draw their objects, so picks, selections and grips made through it leave them out.
/// Empty in paper space and on the Model tab.
+6
View File
@@ -74,6 +74,12 @@ impl AutomationRoots {
Ok(Some(Arc::new(Self { read, write })))
}
/// Roots that grant nothing: every read and write is refused. For agents whose folders can't
/// be used, where leaving the roots out would confine nothing.
pub fn none() -> Arc<Self> {
Arc::new(Self { read: None, write: None })
}
/// The read root, absolute with its links followed.
pub fn read_root(&self) -> Option<&Path> {
self.read.as_deref()
@@ -9,6 +9,8 @@
pub const FILES: &[&str] = &[
"-hatch",
"-linetype",
"-pagesetup",
"-plot",
"-plottermanager",
"-wblock",
"-xref",
+3 -2
View File
@@ -185,8 +185,9 @@ pub fn grip_dims(s: &Session) -> Vec<GripDim> {
return Vec::new();
}
let Some((h, i)) = s.current_prompt().and_then(|p| p.grip) else { return Vec::new() };
let Some(e) = s.doc().ok().and_then(|d| d.entity(h)) else { return Vec::new() };
let all = dims_of(&e.kind, i);
let Ok(d) = s.doc() else { return Vec::new() };
let Some(e) = d.entity(h) else { return Vec::new() };
let all = dims_of(&d.anno_shown_in(e, s.anno_view()), i);
let st = &s.settings;
match st.dyndivis {
0 => all.into_iter().take(1).collect(),
+51 -2
View File
@@ -4,7 +4,7 @@
//! The UI calls [`Session::grip_edit`]; every edit runs through a `grip.*` command so it is
//! undoable and reachable from scripts, the control channel and MCP.
use cadcraft_doc::{DimKind, EntityKind, Handle, LwPolyline};
use cadcraft_doc::{DimKind, Drawing, Entity, EntityKind, Handle, LwPolyline};
use cadcraft_geom::{Arc, EPS, Mat3, Polyline, Vec2, Vec3, norm_angle};
use serde::{Deserialize, Serialize};
use serde_json::json;
@@ -564,10 +564,59 @@ impl Session {
/// Grip points of an object (the indices `grip_edit` takes).
pub fn grips_of(&self, handle: Handle) -> Result<Vec<Vec2>> {
self.doc()?.entity(handle).map(|e| e.kind.grips()).ok_or_else(|| EngineError::Other("no such object".into()))
let d = self.doc()?;
d.entity(handle).map(|e| shown_grips(d, e, self.anno_view())).ok_or_else(|| EngineError::Other("no such object".into()))
}
}
/// The grip points of `e` as it shows (the indices `grip_edit` takes): an annotative object's at
/// the annotation scale it shows at and its position there. `view`: the active viewport's scale
/// in MSPACE ([`crate::DocState::anno_view`]), else the current annotation scale applies.
pub fn shown_grips(d: &Drawing, e: &Entity, view: Option<f64>) -> Vec<Vec2> {
d.anno_shown_in(e, view).grips()
}
/// `e` with grip `index` of [`shown_grips`] moved to `to`, or `None` when that grip can't move
/// there. An annotative object's position grip moves it at the scale it shows at only when it
/// supports several scales; its other grips change its shape at every scale (the edit is taken
/// back to paper size).
pub fn stretch_shown(d: &Drawing, e: &Entity, index: usize, to: Vec2, view: Option<f64>) -> Option<Entity> {
let with = |kind: EntityKind| Some(Entity { kind, ..e.clone() });
let (Some(scale), cadcraft_doc::AnnoDraw::Scaled { factor, by }) = (d.anno_shown_scale_in(e, view), d.anno_draw_in(e, view)) else {
return with(stretch_grip(&e.kind, index, to)?);
};
let shown = cadcraft_doc::anno_placed(e, factor, by).kind;
let from = *shown.grips().get(index)?;
let delta = to - from;
if !delta.is_finite() {
return None;
}
if cadcraft_doc::is_position_grip(&e.kind, index) {
if e.common.anno_scales.len() > 1 {
let mut out = e.clone();
out.common.move_at(&scale.name, delta);
return Some(out);
}
let stored = *e.kind.grips().get(index)?;
return with(stretch_grip(&e.kind, index, stored + delta)?);
}
// A shape grip: stretch the object as it shows, then take it back to paper size.
let mut k = stretch_grip(&shown, index, to)?;
cadcraft_doc::shift_position(&mut k, -by);
let k = match (k, &e.kind) {
(EntityKind::Dimension(mut dm), EntityKind::Dimension(old)) => {
// A dimension's geometry isn't scaled: only its style scale was.
dm.overrides = old.overrides.clone();
if by != Vec2::ZERO {
dm.user_text_pos = old.user_text_pos;
}
EntityKind::Dimension(dm)
}
(k, _) => cadcraft_doc::anno_scaled(&Entity { kind: k, ..e.clone() }, 1.0 / factor).kind,
};
with(k)
}
/// Polyline helper kept public for the UI: segment midpoints are grips too.
pub fn polyline_grip_count(p: &LwPolyline) -> usize {
p.vertices.len() + Polyline { vertices: p.vertices.clone(), closed: p.closed }.segments().len().min(p.vertices.len())
+15
View File
@@ -7,6 +7,8 @@
//! [`Session::input`], [`Session::cmdline`]) exactly like typing at AutoCAD's command line.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
#[cfg(not(target_arch = "wasm32"))]
pub mod agent_settings;
pub mod array_live;
pub mod assoc;
@@ -18,6 +20,7 @@ pub mod blockedit;
#[cfg(not(target_arch = "wasm32"))]
pub mod capped_read;
pub mod cmd;
pub mod disk_stamp;
pub mod doc_path;
pub mod drawlock;
pub mod file_access;
@@ -61,6 +64,13 @@ pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices, patte
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use prompt::{Accept, AttribAsk, AttribEntry, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
/// The most selected objects [`Session::selection_anno_others`] shows at their other scales (as
/// grips, a big selection is drawn without them).
pub const MAX_ANNO_OTHERS: usize = 200;
/// The most faded representations [`Session::selection_anno_others`] makes for a whole selection
/// (each selected object can support many scales).
pub const MAX_ANNO_FADED: usize = 1000;
mod doc_state;
mod error;
mod last_used;
@@ -416,6 +426,11 @@ impl Session {
Ok(h)
}
/// The annotation scale of the active MSPACE viewport ([`DocState::anno_view`]).
pub fn anno_view(&self) -> Option<f64> {
self.state().ok().and_then(DocState::anno_view)
}
/// World units per pixel at the current view.
pub fn pixel_size(&self) -> f64 {
let v = self.state().map(DocState::view).unwrap_or_default();
+1 -1
View File
@@ -286,7 +286,7 @@ fn convert_angles(kind: &str, tags: &mut [Tag], f: fn(f64) -> f64) {
fn tag_value(t: &Tag) -> Value {
match &t.value {
craft_dxf::Value::Str(s) | craft_dxf::Value::Hex(s) => Value::str(s),
craft_dxf::Value::Str(s) | craft_dxf::Value::Hex(s) | craft_dxf::Value::Invalid(s) => Value::str(s),
craft_dxf::Value::Real(r) => Value::Real(*r),
craft_dxf::Value::Int(i) => Value::Int(i32::try_from(*i).unwrap_or(if *i < 0 { i32::MIN } else { i32::MAX })),
craft_dxf::Value::Bool(b) => Value::Int(i32::from(*b)),
+9 -8
View File
@@ -360,15 +360,16 @@ fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> {
if !is_blank_mtext(text) {
return None;
}
let f = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Plain => 1.0,
cadcraft_doc::AnnoDraw::Scaled(f) if f.is_finite() && f > 0.0 => f,
cadcraft_doc::AnnoDraw::Scaled(_) => 1.0,
// As it is drawn: at the current scale, where that scale places it.
let (f, by) = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Plain => (1.0, Vec2::ZERO),
cadcraft_doc::AnnoDraw::Scaled { factor, by } if factor.is_finite() && factor > 0.0 => (factor, by),
cadcraft_doc::AnnoDraw::Scaled { .. } => (1.0, Vec2::ZERO),
cadcraft_doc::AnnoDraw::Hidden => return None,
};
let scaled;
let e = if f != 1.0 {
scaled = cadcraft_doc::anno_scaled(e, f);
let e = if f != 1.0 || by != Vec2::ZERO {
scaled = cadcraft_doc::anno_placed(e, f, by);
&scaled
} else {
e
@@ -497,8 +498,8 @@ fn drawn_text(d: &Drawing, e: &Entity) -> Option<Vec<Vec<Vec2>>> {
let e = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Plain => e,
cadcraft_doc::AnnoDraw::Hidden => return None,
cadcraft_doc::AnnoDraw::Scaled(f) => {
scaled = cadcraft_doc::anno_scaled(e, f);
cadcraft_doc::AnnoDraw::Scaled { factor, by } => {
scaled = cadcraft_doc::anno_placed(e, factor, by);
&scaled
}
};
+35
View File
@@ -720,6 +720,41 @@ impl Session {
self.picking_objects() && self.settings.selectionpreview & bit != 0
}
/// The selected annotative objects at their other scales, drawn faded while they are selected
/// (SELECTIONANNODISPLAY): each at that scale's size and position, as
/// [`cadcraft_doc::anno_others`] gives them. In model space the current scale is CANNOSCALE;
/// inside an active viewport it is the viewport's scale. Empty with SELECTIONANNODISPLAY 0. At
/// most [`MAX_ANNO_OTHERS`] selected objects are looked at, and at most [`MAX_ANNO_FADED`]
/// representations made for all of them together.
pub fn selection_anno_others(&self) -> Vec<Entity> {
let Ok(st) = self.state() else { return Vec::new() };
if !self.settings.selectionannodisplay {
return Vec::new();
}
let d = &st.doc;
let vp_scale = st.anno_view();
let mut out = Vec::new();
let mut budget = crate::MAX_ANNO_FADED;
for h in st.selection.iter().take(crate::MAX_ANNO_OTHERS) {
if budget == 0 {
break;
}
match vp_scale {
Some(f) => {
if let Some(e) = d.model.get(*h) {
out.extend(cadcraft_doc::anno_others(e, f, d.anno_all_visible(), &mut budget));
}
}
None => {
if let Some(e) = d.entity(*h) {
out.extend(d.anno_others(e, &mut budget));
}
}
}
}
out
}
/// Whether selected objects show grips while `selected` objects are selected (GRIPS,
/// GRIPOBJLIMIT).
pub fn shows_grips(&self, selected: usize) -> bool {
+7
View File
@@ -110,6 +110,8 @@ pub struct Settings {
/// SELECTIONPREVIEW bits: the object under the cursor is highlighted (1) when no command is
/// active, (2) when a command asks for objects.
pub selectionpreview: u8,
/// SELECTIONANNODISPLAY: a selected annotative object also shows faded at its other scales.
pub selectionannodisplay: bool,
/// PREVIEWEFFECT: how that object is highlighted: 0 dashed, 1 thicker, 2 dashed and thicker.
pub previeweffect: u8,
/// PREVIEWFILTER bits: objects the cursor never highlights: 1 on locked layers, 2 xrefs,
@@ -149,6 +151,9 @@ pub struct Settings {
/// ATTDIA: INSERT typed or from a menu asks for attribute values in the Edit Attributes
/// dialog; on by default, as in AutoCAD (Initial value 1).
pub attdia: bool,
/// TEXTEVAL: 1 lets a routine's input be read as LISP where it would be text (default: 0).
/// Kept for routines that switch it around their prompts; no prompt reads it yet.
pub texteval: bool,
}
impl Default for Settings {
@@ -204,6 +209,7 @@ impl Default for Settings {
highlight: true,
selectioneffect: 1,
selectionpreview: 3,
selectionannodisplay: true,
previeweffect: 2,
previewfilter: 3,
grips: 1,
@@ -220,6 +226,7 @@ impl Default for Settings {
auditctl: false,
attreq: true,
attdia: true,
texteval: false,
}
}
}
+82 -20
View File
@@ -713,7 +713,7 @@ fn leaves_with_sources(
sink: &mut Sink<'_>,
src: &mut Sources,
) {
block_leaves(d, ins, &Mat3::IDENTITY, z, 0, budget, frozen, &mut |be, m, z| leaf_with_source(be, m, z, handle, sink, src));
block_leaves(d, ins, &Mat3::IDENTITY, z, 0, budget, Inside::drawn(frozen), &mut |be, m, z| leaf_with_source(be, m, z, handle, sink, src));
}
/// The snaps on `be`, an object drawn inside the drawing's object `handle` and placed by `m` and
@@ -1013,8 +1013,9 @@ fn distance_to_prim(p: &Prim, cursor: Vec2) -> f64 {
prim_segments(p).iter().map(|s| fix_circle(s).closest(cursor).dist(cursor)).fold(f64::INFINITY, f64::min)
}
/// Upper bound on the block-reference objects one snap query looks at (hostile files).
const MAX_BLOCK_LEAVES: usize = 20_000;
/// Upper bound on the block-reference objects one snap query, or one look for TRIM and EXTEND
/// edges, looks at (hostile files).
pub(crate) const MAX_BLOCK_LEAVES: usize = 20_000;
/// Collects snap candidates and the primitives near the cursor.
struct Sink<'a> {
@@ -1166,7 +1167,7 @@ impl Sink<'_> {
fn dimension(&mut self, d: &Drawing, dm: &cadcraft_doc::Dimension, budget: &mut usize, frozen: &[String]) {
match dm.block.as_ref().and_then(|n| d.block(n)) {
Some(blk) => {
block_leaves(d, &dimension_reference(blk, dm), &Mat3::IDENTITY, None, 0, budget, frozen, &mut |be, m, _| {
block_leaves(d, &dimension_reference(blk, dm), &Mat3::IDENTITY, None, 0, budget, Inside::drawn(frozen), &mut |be, m, _| {
self.object(&be.kind, Some(m))
});
}
@@ -1210,20 +1211,50 @@ fn dim_def_points(dm: &cadcraft_doc::Dimension) -> Vec<Vec2> {
pts.into_iter().map(|p| p.xy()).filter(|p| p.is_finite()).collect()
}
/// Which of the objects inside a block reference [`block_leaves`] visits.
#[derive(Clone, Copy)]
pub(crate) struct Inside<'a> {
/// Layers frozen in the viewport, whose objects are left out like those of a layer the
/// drawing has off or frozen.
frozen: &'a [String],
/// Whether a dimension and a record kept as read give the objects they draw (a snap finds
/// those) or come as they are, like the same object outside a block.
expand: bool,
}
impl<'a> Inside<'a> {
/// Everything the reference draws, down to the objects a dimension or a kept record draws.
pub(crate) fn drawn(frozen: &'a [String]) -> Self {
Inside { frozen, expand: true }
}
}
/// Calls `f` with each object inside the block reference `ins` that is drawn and the transform
/// placing it in the reference's space, nested references expanded ([`block_leaves`]). `budget`
/// is how many objects the caller's whole walk may still visit and goes down by those visited
/// here: one count, started at [`MAX_BLOCK_LEAVES`], bounds a walk over every reference of a
/// drawing as it bounds a snap query. A dimension and a record kept as read come as they are, so
/// what an object gives inside a reference is what the same object gives outside one. TRIM and
/// EXTEND take their edges inside a reference from here.
pub(crate) fn reference_leaves(d: &Drawing, ins: &Insert, budget: &mut usize, f: &mut dyn FnMut(&EntityKind, &Mat3)) {
block_leaves(d, ins, &Mat3::IDENTITY, None, 0, budget, Inside { frozen: &[], expand: false }, &mut |be, m, _| f(&be.kind, m));
}
/// Calls `f` with each object drawn by a block reference and the transform placing it, nested
/// references expanded (within [`MAX_BLOCK_DEPTH`] levels and `budget` objects); objects that
/// aren't drawn (hidden, on a layer that is off or frozen, attribute definitions) are left out.
/// The objects inside a block reference, each with its transform and, when every reference on
/// the way is in plan (`z`, from [`plan_z`]), how its Z maps to the drawing's.
/// the way is in plan (`z`, from [`plan_z`]), how its Z maps to the drawing's. `inside` says
/// which of them come ([`Inside`]).
#[allow(clippy::too_many_arguments)]
fn block_leaves(
pub(crate) fn block_leaves(
d: &Drawing,
ins: &Insert,
m: &Mat3,
z: Option<(f64, f64)>,
depth: usize,
budget: &mut usize,
frozen: &[String],
inside: Inside<'_>,
f: &mut dyn FnMut(&Entity, &Mat3, Option<(f64, f64)>),
) {
if depth >= MAX_BLOCK_DEPTH {
@@ -1249,22 +1280,33 @@ fn block_leaves(
return;
}
*budget -= 1;
if !drawn_inside(d, be, frozen) {
if !drawn_inside(d, be, inside.frozen) {
continue;
}
match &be.kind {
EntityKind::AttDef(_) => {}
EntityKind::Insert(inner) => {
let zz = z.and_then(|z| plan_z(&be.common, inner, z));
block_leaves(d, inner, &mm, zz, depth + 1, budget, frozen, f);
block_leaves(d, inner, &mm, zz, depth + 1, budget, inside, f);
}
// A dimension draws its block, as at the top level.
EntityKind::Dimension(dm) if let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n)) => {
EntityKind::Dimension(dm) if let Some(blk) = dm.block.as_ref().filter(|_| inside.expand).and_then(|n| d.block(n)) => {
let r = dimension_reference(blk, dm);
let zz = z.and_then(|z| plan_z(&be.common, &r, z));
block_leaves(d, &r, &mm, zz, depth + 1, budget, frozen, f);
block_leaves(d, &r, &mm, zz, depth + 1, budget, inside, f);
}
EntityKind::Unknown(u) if inside.expand => graphics_leaves(d, u, &mm, z, depth + 1, budget, inside.frozen, f),
// A record kept as read that comes as it is spends one count for each graphic
// it holds as well, drawn or not: whoever takes it goes through them all to
// find the drawn ones, in every reference.
EntityKind::Unknown(u) => {
if u.graphics.len() > *budget {
*budget = 0;
return;
}
*budget -= u.graphics.len();
f(be, &mm, z);
}
EntityKind::Unknown(u) => graphics_leaves(d, u, &mm, z, depth + 1, budget, frozen, f),
_ => f(be, &mm, z),
}
}
@@ -1310,20 +1352,30 @@ fn graphics_leaves(
frozen: &[String],
f: &mut dyn FnMut(&Entity, &Mat3, Option<(f64, f64)>),
) {
for g in &u.graphics {
if matches!(g.kind, EntityKind::Hatch(_)) || !drawn_inside(d, g, frozen) {
continue;
}
for g in drawn_graphics(d, u, frozen) {
match &g.kind {
EntityKind::Insert(inner) => {
let zz = z.and_then(|z| plan_z(&g.common, inner, z));
block_leaves(d, inner, m, zz, depth, budget, frozen, f);
block_leaves(d, inner, m, zz, depth, budget, Inside::drawn(frozen), f);
}
_ => f(g, m, None),
}
}
}
/// The graphics of the record kept as read `u` that are drawn, as the renderer draws them: like
/// a block's contents, so not the hidden ones nor those on a layer that is off, frozen or among
/// `frozen` (the layers frozen in the viewport); those on layer 0 take the layer of the record.
/// The fill hatches are left out too, each filled shape's outline being drawn as well. A snap
/// and a TRIM or EXTEND edge both take a proxy's geometry from here.
pub(crate) fn drawn_graphics<'a>(
d: &'a Drawing,
u: &'a cadcraft_doc::Unknown,
frozen: &'a [String],
) -> impl Iterator<Item = &'a cadcraft_doc::Entity> {
u.graphics.iter().filter(move |g| !matches!(g.kind, EntityKind::Hatch(_)) && drawn_inside(d, g, frozen))
}
/// The reference that places a dimension's block as the renderer draws it: the block holds world
/// geometry, moved by the insertion point (DXF group 12, which an older AutoCAD sets for a moved
/// dimension; #2634).
@@ -1356,9 +1408,19 @@ fn prim_near(p: &Prim, probe: &Bounds2, aperture: f64) -> bool {
b.expand(aperture).intersects(probe)
}
/// The unit direction `v` has once `m` places it: zero only when the placed vector has no length
/// or is not finite. Its length is compared with zero, not with the drawing tolerance, so a
/// direction keeps pointing the same way however small or large the scale of `m` is.
pub(crate) fn placed_dir(v: Vec2, m: &Mat3) -> Vec2 {
let v = m.apply_vec(v);
let len = v.len();
if len > 0.0 && len.is_finite() { v / len } else { Vec2::ZERO }
}
/// `p` placed by the affine transform `m`, exactly: circles and arcs under a non-uniform scale
/// become ellipses and elliptical arcs.
fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
/// become ellipses and elliptical arcs. An xline or a ray keeps its direction at any scale
/// ([`placed_dir`]).
pub(crate) fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
let mirror = m.is_mirroring();
match p {
Prim::Seg(Segment::Line(l)) => Prim::Seg(Segment::Line(cadcraft_geom::Line::new(m.apply(l.a), m.apply(l.b)))),
@@ -1385,7 +1447,7 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
Prim::Spline(s)
}
Prim::Point(q) => Prim::Point(m.apply(*q)),
Prim::Infinite { base, dir, ray } => Prim::Infinite { base: m.apply(*base), dir: m.apply_vec(*dir).normalized(), ray: *ray },
Prim::Infinite { base, dir, ray } => Prim::Infinite { base: m.apply(*base), dir: placed_dir(*dir, m), ray: *ray },
Prim::Fill(f) => Prim::Fill(f.iter().map(|q| m.apply(*q)).collect()),
}
}
+118 -5
View File
@@ -7,7 +7,14 @@ use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_
mod table;
/// ACADVER: the program's release, as a text AutoCAD documents it and `atof` reads back as a
/// number. A drawing's `$ACADVER` header is its file version, which is what a save writes, so the
/// two are separate values: `get` gives this text, `list` too, and the header stays as read.
pub const ACADVER_TEXT: &str = "24.3s (CADCraft)";
const SESSION_VARS: &[&str] = &[
// The release text, with or without a drawing (the header's `$ACADVER` is the file version).
"ACADVER",
"AUDITCTL",
"ATTREQ",
"OSMODE",
@@ -48,6 +55,7 @@ const SESSION_VARS: &[&str] = &[
"HIGHLIGHT",
"SELECTIONEFFECT",
"SELECTIONPREVIEW",
"SELECTIONANNODISPLAY",
"PREVIEWEFFECT",
"PREVIEWFILTER",
"GRIPS",
@@ -81,10 +89,54 @@ const SESSION_VARS: &[&str] = &[
"SAVETIME",
"SAVEFILEPATH",
"ISAVEBAK",
"DIMASO",
"TEXTEVAL",
"POPUPS",
];
pub fn get(s: &Session, name: &str) -> Option<Value> {
/// The DIMASSOC mode DIMASO turned off, kept in the drawing's header so undo restores it.
/// `CADCRAFT_` names are not listed by SYSVARS and no file writes this one.
const DIMASO_MODE: &str = "CADCRAFT_DIMASO_MODE";
/// The header key above, under any number of `$`: no variable of that name exists.
fn is_internal(n: &str) -> bool {
n.trim_start_matches('$') == DIMASO_MODE
}
/// The names this session also answers with DXF's `$` in front: the header writes them that way
/// (`$DIMASO`, `$TEXTEVAL`, `$REGENMODE`, `$POPUPS`), so a routine may type either form.
const DOLLAR_VARS: &[&str] = &["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"];
/// [`set`] takes only a number for these: a program's or a routine's text is refused. A value
/// typed at the command line arrives as text and goes through [`typed_value`] first.
const NUMBER_ONLY: &[&str] = &["DIMASO", "TEXTEVAL", "REGENMODE"];
/// The value of `text` typed at a SETVAR prompt for `name`: typed digits are a number for the
/// [`NUMBER_ONLY`] variables. Anything else stays text.
pub(crate) fn typed_value(name: &str, text: String) -> Value {
if NUMBER_ONLY.contains(&bare_name(name).as_str())
&& let Ok(number) = text.trim().parse::<i64>()
{
return json!(number);
}
Value::String(text)
}
/// `name` trimmed and upper case, without the `$` those names take. Every other name keeps the
/// `$` it was typed with: `$ANGBASE` stays a name of its own (LISP converts radians only for the
/// plain name) and `$OSMODE` is not the session's OSMODE.
fn bare_name(name: &str) -> String {
let n = name.trim().to_ascii_uppercase();
// Every leading `$`, as the header drops them all when it stores a value.
let rest = n.trim_start_matches('$');
if rest.len() < n.len() && DOLLAR_VARS.contains(&rest) { rest.to_string() } else { n }
}
pub fn get(s: &Session, name: &str) -> Option<Value> {
let n = bare_name(name);
if is_internal(&n) {
return None;
}
let st = &s.settings;
let v = match n.as_str() {
"OSMODE" => json!(st.osmode),
@@ -134,6 +186,7 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
"HIGHLIGHT" => json!(i32::from(st.highlight)),
"SELECTIONEFFECT" => json!(st.selectioneffect),
"SELECTIONPREVIEW" => json!(st.selectionpreview),
"SELECTIONANNODISPLAY" => json!(i32::from(st.selectionannodisplay)),
"PREVIEWEFFECT" => json!(st.previeweffect),
"PREVIEWFILTER" => json!(st.previewfilter),
"GRIPS" => json!(st.grips),
@@ -177,7 +230,16 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
"SAVETIME" => json!(crate::autosave::savetime()),
"SAVEFILEPATH" => json!(crate::autosave::savefilepath()),
"ISAVEBAK" => json!(i32::from(crate::autosave::isavebak())),
"CMDNAMES" => json!(s.running.as_ref().map(|r| r.id.to_ascii_uppercase()).unwrap_or_default()),
// DIMASO is obsolete in AutoCAD and has no value of its own: it reports DIMASSOC.
"DIMASO" => json!(i32::from(matches!(dimassoc(s)?, 1 | 2))),
// Whether a prompt reads typed text as LISP (routines switch it around their prompts).
"TEXTEVAL" => json!(i32::from(st.texteval)),
// Dialogs are available (read-only; a batch session is still told 1, as AutoCAD does).
"POPUPS" => json!(1),
// The command a transparent one runs inside comes first, as AutoCAD gives it ("LINE'ZOOM").
// While a transparent command reads its input it isn't `running`, but the outer command
// is still suspended, and still active.
"CMDNAMES" => json!([&s.suspended, &s.running].into_iter().flatten().map(|r| r.id.to_ascii_uppercase()).collect::<Vec<_>>().join("'")),
"DWGNAME" => json!(s.state().map(|d| d.title.clone()).unwrap_or_default()),
"DBMOD" => json!(s.state().map(|d| i32::from(d.is_dirty())).unwrap_or(0)),
// The next handle the drawing gives out, in hex as `$HANDSEED` (the header keeps the
@@ -187,8 +249,12 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
// The drawing's folder with a trailing separator ("" while it has no file); DWGTITLED is 1 once it has one.
"DWGPREFIX" => json!(s.state().ok().and_then(|d| d.path.as_deref()).map(dwg_prefix).unwrap_or_default()),
"DWGTITLED" => json!(s.state().map(|d| i32::from(d.path.is_some())).unwrap_or(0)),
"CMDACTIVE" => json!(i32::from(s.running.is_some())),
// 1: a command is active; 2: a transparent one, inside it.
"CMDACTIVE" => json!(i32::from(s.running.is_some() || s.suspended.is_some()) + 2 * i32::from(s.suspended.is_some())),
"TILEMODE" => json!(i32::from(s.state().is_ok_and(|d| d.space.layout().is_none()))),
// The release number as AutoCAD reports it, so `(atof (getvar "ACADVER"))` is 24.3; the
// drawing's own `$ACADVER` (its file version) is left alone for the save version.
"ACADVER" => json!(ACADVER_TEXT),
"PLATFORM" => json!(std::env::consts::OS),
"BLOCKEDITOR" => json!(i32::from(s.state().is_ok_and(|d| d.block_edit.is_some()))),
// The template NEW/QNEW start from (a profile setting, like FONTALT; "" = none).
@@ -257,6 +323,11 @@ fn dwg_prefix(path: &str) -> String {
}
}
/// DIMASSOC's value (0 off, 1 or 2 associative), read where DIMASO reports it from.
fn dimassoc(s: &Session) -> Option<i64> {
table::get(s, "DIMASSOC")?.as_i64()
}
fn as_bool(v: &Value) -> Option<bool> {
v.as_bool().or_else(|| v.as_i64().map(|i| i != 0)).or_else(|| v.as_str().and_then(|s| s.trim().parse::<i64>().ok()).map(|i| i != 0))
}
@@ -277,6 +348,7 @@ fn as_pt(v: &Value) -> Option<cadcraft_geom::Vec2> {
/// Variables `get` reports from session or drawing state that `set` can't change.
const READ_ONLY: &[&str] = &[
"ACADVER",
"CMDNAMES",
"DWGNAME",
"DWGPREFIX",
@@ -304,10 +376,15 @@ const READ_ONLY: &[&str] = &[
"UCSXDIR",
"UCSYDIR",
"WORLDUCS",
// Dialogs: a session always has them, so the variable is fixed (not saved).
"POPUPS",
];
pub fn is_read_only(name: &str) -> bool {
READ_ONLY.iter().any(|r| r.eq_ignore_ascii_case(name.trim())) || table::is_read_only(&name.trim().to_ascii_uppercase())
// A header name's `$` is ignored: the header drops it when it stores a value, so `$ACADVER`
// would otherwise change ACADVER, and with it the version a save writes.
let n = name.trim().trim_start_matches('$').trim();
READ_ONLY.iter().any(|r| r.eq_ignore_ascii_case(n)) || table::is_read_only(&n.to_ascii_uppercase())
}
/// POLARADDANG as typed: up to ten angles in degrees separated by `;` (radians out); `None` when
@@ -325,11 +402,17 @@ pub fn format_angle_list(angles: &[f64]) -> String {
/// Set a system variable, refusing values out of its range and folders the automation roots can't hold.
pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
let n = name.trim().to_ascii_uppercase();
let n = bare_name(name);
if is_internal(&n) {
return Err(EngineError::BadParams { cmd: "setvar".into(), msg: format!("unknown variable `{n}`") });
}
if is_read_only(&n) {
return Err(EngineError::BadParams { cmd: "setvar".into(), msg: format!("{n} is read-only") });
}
let bad = || EngineError::BadParams { cmd: "setvar".into(), msg: format!("invalid value for {n}") };
if NUMBER_ONLY.contains(&n.as_str()) && !v.is_number() {
return Err(bad());
}
let st = &mut s.settings;
match n.as_str() {
"OSMODE" => {
@@ -401,6 +484,7 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
"HIGHLIGHT" => st.highlight = as_bool(v).ok_or_else(bad)?,
"SELECTIONEFFECT" => st.selectioneffect = small(v, 1).ok_or_else(bad)?,
"SELECTIONPREVIEW" => st.selectionpreview = small(v, 3).ok_or_else(bad)?,
"SELECTIONANNODISPLAY" => st.selectionannodisplay = small(v, 1).ok_or_else(bad)? != 0,
"PREVIEWEFFECT" => st.previeweffect = small(v, 2).ok_or_else(bad)?,
"PREVIEWFILTER" => st.previewfilter = small(v, 63).ok_or_else(bad)?,
"GRIPS" => st.grips = small(v, 2).ok_or_else(bad)?,
@@ -436,6 +520,35 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
}
"SAVEFILEPATH" => crate::autosave::set_savefilepath(v.as_str().ok_or_else(bad)?),
"ISAVEBAK" => crate::autosave::set_isavebak(as_bool(v).ok_or_else(bad)?),
// DIMASO has no value of its own: 0 turns DIMASSOC off (remembering the mode it had),
// 1 restores that mode (2 when none was seen), and 1 while it is on changes nothing. The
// mode it remembers is in the drawing's header ([`DIMASO_MODE`]), so each open drawing
// keeps its own and undo restores it with DIMASSOC; no file writes it.
"DIMASO" => {
let on = as_i(v).filter(|i| matches!(i, 0 | 1)).ok_or_else(bad)? == 1;
let mode = dimassoc(s).ok_or_else(bad)?;
// The drawing is touched only when DIMASSOC changes, so it is not marked modified
// and no undo step is left for a value it already has.
match (on, mode) {
(true, 1 | 2) | (false, 0) => {}
// Turned back on, from off or from a file's unknown mode: the mode it had.
(true, _) => {
let h = &mut s.doc_mut()?.header;
// Only a mode DIMASSOC takes: a file's value of anything else restores 2.
let restore = h.i64(DIMASO_MODE, 2);
h.set_i64("DIMASSOC", if matches!(restore, 1 | 2) { restore } else { 2 });
}
(false, _) => {
let h = &mut s.doc_mut()?.header;
if matches!(mode, 1 | 2) {
h.set_i64(DIMASO_MODE, mode);
}
h.set_i64("DIMASSOC", 0);
}
}
}
// Stored for routines that switch it around their prompts; no prompt reads it yet.
"TEXTEVAL" => st.texteval = small(v, 1).ok_or_else(bad)? == 1,
// A number is in degrees; text is an angle typed in AUNITS (SETVAR at the command line).
"ANGBASE" => {
let a = match v {
+2
View File
@@ -73,6 +73,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
("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)),
// 1 regenerates the drawing after a command that changes it (stored, nothing reads it yet).
("REGENMODE", Kind::Choice(&[0, 1]), Def::Int(1)),
("REVCLOUDARCLEN", Kind::Real { min: 0.0, strict: true }, Def::Units(0.5, 15.0)),
("SPLINESEGS", Kind::Int(-32768, 32767), Def::Int(8)),
("SPLKNOTS", Kind::Choice(&[0, 1, 2]), Def::Int(0)),
+27
View File
@@ -965,6 +965,33 @@ fn setvar_at_command_line() {
assert!(s.running.is_none());
}
/// #3273: GETVAR at the command line asks for a name and echoes its value, without changing it;
/// it said only that `name` was required.
#[test]
fn getvar_at_command_line() {
let mut s = Session::new();
let dimscale = sysvars::get(&s, "DIMSCALE").unwrap();
// One line, as typed in the issue.
s.cmdline("GETVAR DIMSCALE").unwrap();
assert!(s.running.is_none());
assert!(s.log.last().is_some_and(|l| l.starts_with("DIMSCALE = ")), "{:?}", s.log.last());
assert_eq!(sysvars::get(&s, "DIMSCALE").unwrap(), dimscale, "reading changes nothing");
// Step by step, in any case.
s.cmdline("getvar").unwrap();
assert!(s.running.is_some());
s.cmdline("lunits").unwrap();
assert!(s.running.is_none());
assert!(s.log.last().is_some_and(|l| l.starts_with("LUNITS = ")), "{:?}", s.log.last());
// An unknown name says so, and Enter ends it.
s.cmdline("GETVAR NOSUCHVAR").unwrap();
assert_eq!(s.log.last().map(String::as_str), Some("Unknown variable NOSUCHVAR. Type SETVAR ? to list variables."));
s.cmdline("getvar").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none());
// The command an agent runs is unchanged.
assert_eq!(s.execute("getvar", &json!({"name": "dimscale"})).unwrap(), json!({"name": "DIMSCALE", "value": dimscale}));
}
#[test]
fn setvar_keeps_header_types() {
let mut s = Session::new();
+659
View File
@@ -0,0 +1,659 @@
//! #3433: -PLOT and -PAGESETUP typed at the command line, in a script or from `(command …)` ask
//! for their options one at a time and run the `plot` and `pagesetup` commands with the answers,
//! so a script or a LISP routine can set a layout's paper and plot it without a dialog.
//!
//! In its own test binary, not `tests/it`, because it installs the real plotter: the io hooks
//! are process-wide and set once (`set_io` keeps the first value), so in `tests/it` they would
//! change what the other tests' saves and plots do, by test order.
use cadcraft_engine::cmd::file::{IoHooks, set_io};
use cadcraft_engine::cmd::plotters::{PlotterStore, set_plotter_store};
use cadcraft_engine::{Input, Session};
use serde_json::{Value, json};
#[path = "support/temp_dir.rs"]
mod temp_dir;
use temp_dir::TempDir;
/// ISO A4 in points, short side first.
const A4_PT: (f64, f64) = (595.28, 841.89);
/// ISO A3 in points, short side first.
const A3_PT: (f64, f64) = (841.89, 1190.55);
/// A session with the real plotter, the built-in devices only, and one line in model space.
fn session() -> Session {
set_plotter_store(PlotterStore::memory());
set_io(IoHooks {
read: |_, _| Err("no reader in this test".into()),
write: |_, _| Err("no writer in this test".into()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
let mut s = Session::new();
s.cmdline("line 0,0 100,50").unwrap();
s.cmdline("").unwrap();
s
}
/// A path in `dir` written with forward slashes, so it reads the same in a script line and in a
/// LISP string.
fn out(dir: &TempDir, name: &str) -> String {
dir.path_str(name).replace('\\', "/")
}
/// The page size of a plotted PDF in points, as (width, height).
fn media(path: &str) -> (f64, f64) {
let bytes = std::fs::read(path).unwrap_or_else(|e| panic!("{path}: {e}"));
assert!(bytes.starts_with(b"%PDF"), "{path} is a PDF");
let text = String::from_utf8_lossy(&bytes);
let at = text.find("/MediaBox").expect("the PDF names its page size");
let rest = &text[at..];
let (open, close) = (rest.find('[').expect("["), rest.find(']').expect("]"));
let n: Vec<f64> = rest[open + 1..close].split_whitespace().filter_map(|t| t.parse().ok()).collect();
assert_eq!(n.len(), 4, "a page box has four numbers: {n:?}");
(n[2] - n[0], n[3] - n[1])
}
/// Whether a page is the sheet `size` (short side first), turned to landscape or not.
fn is_sheet(page: (f64, f64), size: (f64, f64), landscape: bool) -> bool {
let want = if landscape { (size.1, size.0) } else { size };
(page.0 - want.0).abs() < 0.5 && (page.1 - want.1).abs() < 0.5
}
/// The stored page setup of a layout, as the `pagesetup` query reports it.
fn page(s: &mut Session, layout: &str) -> Value {
s.execute("pagesetup", &json!({ "layout": layout })).unwrap()["page"].clone()
}
/// The question on the command line now, as shown.
fn asked(s: &Session) -> String {
s.current_prompt().expect("a question is asked").display()
}
/// A script's long form on the Model tab plots a PDF on the paper and in the orientation its
/// answers name.
#[test]
fn the_long_form_on_model_plots_the_asked_paper_and_orientation() {
let mut s = session();
let dir = TempDir::new("dash-plot-model");
let pdf = out(&dir, "model.pdf");
s.script(&format!("-PLOT Y\nModel\nCADCraft PDF\nA3\nM L N E F C Y\n.\nY A\n{pdf}\nN Y\n")).unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
assert!(is_sheet(media(&pdf), A3_PT, true), "{:?}", media(&pdf));
// The other orientation and another paper, to show the answers decide and not a default.
let pdf = out(&dir, "model-portrait.pdf");
s.script(&format!("-PLOT Y\nModel\nCADCraft PDF\nA4\nM P N E F C Y\n.\nY A\n{pdf}\nN Y\n")).unwrap();
assert!(is_sheet(media(&pdf), A4_PT, false), "{:?}", media(&pdf));
}
/// The long form on a layout asks the layout's own questions (no shade plot; lineweight scaling,
/// paper space first and hiding instead) and plots that layout on the asked paper, without
/// touching its stored page setup when the answer to saving is No.
#[test]
fn the_long_form_on_a_layout_plots_the_asked_paper_and_keeps_the_page_setup() {
let mut s = session();
let dir = TempDir::new("dash-plot-layout");
let pdf = out(&dir, "layout.pdf");
let before = page(&mut s, "Layout1");
s.script(&format!("-PLOT Y\nLayout1\nCADCraft PDF\nA4\nM P N L 1=1 0,0 Y\n.\nY N N N\n{pdf}\nN Y\n")).unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
assert!(is_sheet(media(&pdf), A4_PT, false), "{:?}", media(&pdf));
assert_eq!(page(&mut s, "Layout1"), before, "saving answered No: the layout keeps its page setup");
}
/// The short form asks the layout, a page setup name, the device and the file, and plots the
/// layout with its stored page setup.
#[test]
fn the_short_form_plots_the_layout_as_its_page_setup_says() {
let mut s = session();
let dir = TempDir::new("dash-plot-short");
s.execute("pagesetup", &json!({ "layout": "Layout1", "paper": "A3", "landscape": true })).unwrap();
let pdf = out(&dir, "short.pdf");
s.cmdline("-PLOT").unwrap();
let mut seen = vec![asked(&s)];
for answer in ["N", "Layout1", "", "CADCraft PDF", &pdf, "", ""] {
s.cmdline(answer).unwrap();
seen.extend(s.current_prompt().map(|p| p.display()));
}
assert_eq!(seen.len(), 7, "seven questions: {seen:#?}");
let has = |i: usize, word: &str| seen[i].to_lowercase().contains(word);
assert!(
has(0, "detailed") && has(1, "layout") && has(2, "page setup") && has(3, "device") && has(4, "file") && has(5, "save") && has(6, "go ahead"),
"{seen:#?}"
);
assert!(s.current_prompt().is_none());
assert!(is_sheet(media(&pdf), A3_PT, true), "{:?}", media(&pdf));
}
/// An AutoLISP routine plots through `(command "_-PLOT" …)` and sets a layout's page setup
/// through `(command "_-PAGESETUP" …)`, with underscored keywords as routines write them.
#[test]
fn lisp_command_plots_and_sets_a_page_setup() {
let mut s = session();
let dir = TempDir::new("dash-plot-lisp");
let pdf = out(&dir, "lisp.pdf");
s.script(&format!(r#"(command "_-PLOT" "_Y" "Model" "CADCraft PDF" "A4" "_M" "_P" "_N" "_E" "_F" "_C" "_Y" "." "_Y" "_A" "{pdf}" "_N" "_Y")"#))
.unwrap();
assert!(s.current_prompt().is_none(), "the routine answered every question: {:?}", s.current_prompt());
assert!(is_sheet(media(&pdf), A4_PT, false), "{:?}", media(&pdf));
s.script(r#"(command "_-PAGESETUP" "Layout1" "CADCraft PDF" "A3" "_M" "_L" "_N" "_L" "_F" "0,0" "_Y" "monochrome.ctb" "_N" "_N" "_N" "_N")"#)
.unwrap();
assert!(s.current_prompt().is_none(), "the routine answered every question: {:?}", s.current_prompt());
let p = page(&mut s, "Layout1");
assert_eq!(p["device"], "CADCraft PDF");
assert!(p["paper"].as_str().unwrap().contains("A3"), "{p}");
assert_eq!(p["landscape"], true);
assert_eq!(p["paperMm"], true);
assert_eq!(p["scaleToFit"], true);
assert_eq!(p["plotStyleTable"], "monochrome.ctb");
assert_eq!(p["lineweights"], false);
}
/// -PAGESETUP from a script stores the answers on the layout, the `pagesetup` query reads them
/// back, the other layout is untouched, and the whole command is one undo step.
#[test]
fn pagesetup_script_changes_the_stored_page_setup() {
let mut s = session();
let before = page(&mut s, "Layout1");
let other = page(&mut s, "Layout2");
s.script("-PAGESETUP\nLayout1\nCADCraft PDF\nA3\nM P N L 1=2 0,0 Y\ngrayscale.ctb\nY N N N\n").unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
let p = page(&mut s, "Layout1");
assert_ne!(p, before);
assert_eq!(p["device"], "CADCraft PDF");
assert!(p["paper"].as_str().unwrap().contains("A3"), "{p}");
assert_eq!((&p["landscape"], &p["paperMm"], &p["scaleToFit"]), (&json!(false), &json!(true), &json!(false)));
assert!((p["scale"].as_f64().unwrap() - 0.5).abs() < 1e-9, "1=2 is half a paper unit per drawing unit: {p}");
assert_eq!(p["plotStyleTable"], "grayscale.ctb");
assert_eq!(page(&mut s, "Layout2"), other);
s.undo().unwrap();
assert_eq!(page(&mut s, "Layout1"), before, "one undo step takes the page setup back");
}
/// Enter at every question takes the default the question shows: on the Model tab the long form
/// asks its seventeen questions in order and plots as the `plot` command does with those
/// defaults; on a layout the defaults are its stored page setup.
#[test]
fn enter_takes_the_shown_default_at_each_question() {
let mut s = session();
let dir = TempDir::new("dash-plot-enter");
let pdf = out(&dir, "enter.pdf");
s.cmdline("-PLOT").unwrap();
s.cmdline("Y").unwrap();
let mut seen = vec![asked(&s)];
s.cmdline("").unwrap(); // the layout: the current tab
seen.push(asked(&s));
s.cmdline("CADCraft PDF").unwrap();
// Paper, units, orientation, upside down, area, scale, offset, plot styles, table,
// lineweights, shade plot: Enter at each.
for _ in 0..11 {
let p = s.current_prompt().expect("a question");
assert!(p.default.is_some(), "every question shows a default: {}", p.display());
seen.push(p.display());
s.cmdline("").unwrap();
}
let file = s.current_prompt().expect("the file question");
assert!(file.default.as_deref().is_some_and(|d| d.ends_with("-Model.pdf")), "{}", file.display());
seen.push(file.display());
s.cmdline(&pdf).unwrap();
seen.push(asked(&s));
s.cmdline("").unwrap(); // save: No
seen.push(asked(&s));
s.cmdline("").unwrap(); // proceed: Yes
assert!(s.current_prompt().is_none());
let order = [
"layout",
"device",
"paper size",
"paper units",
"orientation",
"upside down",
"plot area",
"plot scale",
"plot offset",
"plot styles",
"plot style table",
"lineweights",
"shade plot",
"file name",
"save",
"go ahead",
];
assert_eq!(seen.len(), order.len(), "{seen:#?}");
for (q, word) in seen.iter().zip(order) {
assert!(q.to_lowercase().contains(word), "`{q}` should ask for the {word}");
}
// The built-in device's default paper and orientation.
assert!(is_sheet(media(&pdf), A4_PT, true), "{:?}", media(&pdf));
// On a layout the defaults are its page setup: Enter everywhere plots it as stored.
s.execute("pagesetup", &json!({ "layout": "Layout2", "device": "CADCraft PDF", "paper": "A3", "landscape": false })).unwrap();
let stored = page(&mut s, "Layout2");
let pdf = out(&dir, "enter-layout.pdf");
s.cmdline("-PLOT").unwrap();
s.cmdline("Y").unwrap();
s.cmdline("Layout2").unwrap();
assert!(asked(&s).contains("<CADCraft PDF>"), "{}", asked(&s));
s.cmdline("").unwrap();
assert!(asked(&s).contains("A3"), "{}", asked(&s));
let mut layout_questions = Vec::new();
while !asked(&s).to_lowercase().contains("file name") {
layout_questions.push(asked(&s).to_lowercase());
s.cmdline("").unwrap();
}
assert!(layout_questions.iter().any(|q| q.contains("<layout>")), "the area defaults to the sheet: {layout_questions:#?}");
assert!(!layout_questions.iter().any(|q| q.contains("shade plot")), "no shade plot question on a layout: {layout_questions:#?}");
for word in ["scale the lineweights", "paper space first", "hide paper space"] {
assert!(layout_questions.iter().any(|q| q.contains(word)), "a layout is asked about {word}: {layout_questions:#?}");
}
s.cmdline(&pdf).unwrap();
s.cmdline("").unwrap();
s.cmdline("").unwrap();
assert!(is_sheet(media(&pdf), A3_PT, false), "{:?}", media(&pdf));
assert_eq!(page(&mut s, "Layout2"), stored);
}
/// A wrong answer is told and the same question is asked again; so is an answer the plotter
/// cannot honour, which is never accepted without effect.
#[test]
fn a_wrong_answer_asks_the_question_again() {
let mut s = session();
let dir = TempDir::new("dash-plot-wrong");
let pdf = out(&dir, "wrong.pdf");
s.cmdline("-PLOT").unwrap();
// Each pair: answers that must be refused at the question, then the answer that moves on.
let steps: [(&[&str], &str); 14] = [
(&["maybe"], "Y"),
(&["No such layout"], "Model"),
(&["No such device"], "CADCraft PDF"),
(&["No such paper"], "A4"),
(&["furlongs"], "M"),
(&["sideways"], "L"),
(&["Y"], "N"), // upside down
(&["everything"], "E"), // area
(&["abc", "0=1", "5"], "1=2"),
(&["left", "1;2"], "0,0"),
(&["perhaps"], "Y"), // plot styles
(&[], "."), // table
(&["perhaps"], "Y"), // lineweights
(&["H", "V", "R"], "A"), // shade plot
];
for (wrong, right) in steps {
let question = asked(&s);
for w in wrong {
let said = s.log.len();
s.cmdline(w).unwrap();
assert_eq!(asked(&s), question, "`{w}` is not an answer here");
assert!(s.log.len() > said, "`{w}` at `{question}` is told why it is refused");
}
s.cmdline(right).unwrap();
assert_ne!(asked(&s), question, "`{right}` answers `{question}`");
}
s.cmdline(&pdf).unwrap();
// Model space stores no page setup: saving is refused there, not silently dropped.
let question = asked(&s);
s.cmdline("Y").unwrap();
assert_eq!(asked(&s), question);
s.cmdline("N").unwrap();
s.cmdline("Y").unwrap();
assert!(s.current_prompt().is_none());
assert!(is_sheet(media(&pdf), A4_PT, true), "{:?}", media(&pdf));
}
/// Esc at any question ends the command with nothing plotted, nothing stored and no undo step.
#[test]
fn escape_cancels_and_changes_nothing() {
let mut s = session();
let dir = TempDir::new("dash-plot-esc");
let pdf = out(&dir, "never.pdf");
let before = page(&mut s, "Layout1");
let drawing = s.doc().unwrap().clone();
// -PAGESETUP, cancelled at its last question.
s.script("-PAGESETUP\nLayout1\nCADCraft PDF\nA3\nM P N L 1=2 0,0 Y\ngrayscale.ctb\nY N N\n").unwrap();
assert!(asked(&s).to_lowercase().contains("hide paper space"), "{}", asked(&s));
s.input(Input::Cancel).unwrap();
assert!(s.current_prompt().is_none());
assert_eq!(page(&mut s, "Layout1"), before);
// -PLOT with saving answered Yes, cancelled at "proceed".
s.script(&format!("-PLOT Y\nLayout1\nCADCraft PDF\nA3\nM P N L 1=2 0,0 Y\n.\nY N N N\n{pdf}\nY\n")).unwrap();
assert!(asked(&s).to_lowercase().contains("go ahead"), "{}", asked(&s));
s.input(Input::Cancel).unwrap();
assert!(s.current_prompt().is_none());
assert!(!std::path::Path::new(&pdf).exists(), "nothing was plotted");
assert_eq!(page(&mut s, "Layout1"), before);
assert_eq!(*s.doc().unwrap(), drawing, "the drawing is as it was");
s.undo().unwrap();
assert!(s.doc().unwrap().model.is_empty(), "undo takes back the line: neither command left an undo step");
}
/// The command ends without a plot where the observed behaviour ends it: no output device, a
/// plot style table that does not exist, and "proceed" answered No (which still saves the page
/// setup when saving was answered Yes).
#[test]
fn the_command_ends_without_a_plot_where_it_should() {
let mut s = session();
let dir = TempDir::new("dash-plot-ends");
// Enter at the device question on a tab without a device.
s.script("-PLOT Y\nModel\n\n").unwrap();
assert!(s.current_prompt().is_none(), "no device: the command ends: {:?}", s.current_prompt());
assert!(s.log.last().is_some_and(|l| l.contains("cannot plot")), "{:?}", s.log.last());
// An unknown plot style table, also when plot styles were answered No.
for styles in ["Y", "N"] {
s.script(&format!("-PLOT Y\nModel\nCADCraft PDF\nA4\nM P N E F C {styles}\nno-such-table.ctb\n")).unwrap();
assert!(s.current_prompt().is_none(), "an unknown table ends the command: {:?}", s.current_prompt());
assert!(s.log.last().is_some_and(|l| l.contains("no-such-table.ctb")), "{:?}", s.log.last());
}
// Proceed answered No: no file; the page setup is saved because saving was answered Yes.
let pdf = out(&dir, "declined.pdf");
let before = page(&mut s, "Layout1");
s.script(&format!("-PLOT Y\nLayout1\nCADCraft PDF\nA3\nM P N L F 0,0 Y\n.\nY N N N\n{pdf}\nY N\n")).unwrap();
assert!(s.current_prompt().is_none());
assert!(!std::path::Path::new(&pdf).exists(), "proceed answered No plots nothing");
let saved = page(&mut s, "Layout1");
assert_ne!(saved, before);
assert!(saved["paper"].as_str().unwrap().contains("A3") && saved["device"] == "CADCraft PDF", "{saved}");
// The next run on that layout offers the saved answers as its defaults.
s.script("-PLOT Y\nLayout1\n").unwrap();
assert!(asked(&s).contains("<CADCraft PDF>"), "{}", asked(&s));
s.cmdline("").unwrap();
assert!(asked(&s).contains("A3"), "{}", asked(&s));
s.input(Input::Cancel).unwrap();
}
/// The answers reach the `plot` command as the parameters they stand for: a typed plot writes
/// the same file as the JSON call with those parameters. The scale is given in the answered
/// paper units, the window by two corners, a named view as its rectangle.
#[test]
fn typed_answers_plot_as_the_same_json_parameters() {
let mut s = session();
let dir = TempDir::new("dash-plot-same");
let same = |s: &mut Session, name: &str, script: &str, params: Value| {
let typed = out(&dir, &format!("{name}-typed.pdf"));
let direct = out(&dir, &format!("{name}-json.pdf"));
s.script(&script.replace("{out}", &typed)).unwrap();
assert!(s.current_prompt().is_none(), "{name}: the command ended: {:?}", s.current_prompt());
let mut p = params;
p["path"] = json!(direct);
s.execute("plot", &p).unwrap();
assert_eq!(std::fs::read(&typed).unwrap(), std::fs::read(&direct).unwrap(), "{name}: the typed plot is the JSON plot");
};
// One inch on paper for two drawing units, on a sheet the plotter measures in millimetres.
same(
&mut s,
"inches",
"-PLOT Y\nModel\nCADCraft PDF\nANSI B\nI L N E 1=2 1,0.5 N\n.\nN A\n{out}\nN Y\n",
json!({ "layout": "Model", "device": "CADCraft PDF", "paper": "ANSI B", "landscape": true, "plotArea": "extents", "fit": false,
"scale": 12.7, "center": false, "offset": [25.4, 12.7], "plotStyleTable": "None", "lineweights": false }),
);
// A window by two corners, with a plot style table.
same(
&mut s,
"window",
"-PLOT Y\nModel\nCADCraft PDF\nA4\nM P N W 10,5 60,40 F C Y\nmonochrome.ctb\nY A\n{out}\nN Y\n",
json!({ "layout": "Model", "device": "CADCraft PDF", "paper": "A4", "landscape": false, "plotArea": "window",
"window": [[10, 5], [60, 40]], "fit": true, "center": true, "plotStyleTable": "monochrome.ctb", "lineweights": true }),
);
// A named model space view is its rectangle.
s.execute("view", &json!({ "option": "window", "name": "Detail", "p1": [10, 10], "p2": [50, 30] })).unwrap();
let v = s.doc().unwrap().views.iter().find(|v| v.name == "Detail").expect("the view was saved").clone();
let (lo, hi) = ((v.center.x - v.width / 2.0, v.center.y - v.height / 2.0), (v.center.x + v.width / 2.0, v.center.y + v.height / 2.0));
same(
&mut s,
"view",
"-PLOT Y\nModel\nCADCraft PDF\nA4\nM P N V\nDetail\nF C Y\n.\nY A\n{out}\nN Y\n",
json!({ "layout": "Model", "device": "CADCraft PDF", "paper": "A4", "landscape": false, "plotArea": "window",
"window": [[lo.0, lo.1], [hi.0, hi.1]], "fit": true, "center": true, "plotStyleTable": "None", "lineweights": true }),
);
}
/// A user device made from the built-in PDF device, whose paper `paper` has `margins` (mm).
fn device_with_margins(s: &mut Session, name: &str, paper: &str, margins: [f64; 4]) {
s.execute("plottermanager", &json!({ "action": "new", "name": name, "from": "CADCraft PDF", "output": "pdf" })).unwrap();
s.execute("plottermanager", &json!({ "action": "set", "name": name, "paper": { "name": paper, "margins": margins } })).unwrap();
}
/// The layout plotted as its stored page setup says, fitted to the printable area, so that the
/// stored margins show in the file.
fn plot_as_stored(s: &mut Session, layout: &str, path: &str) -> Vec<u8> {
s.execute("plot", &json!({ "layout": layout, "fit": true, "path": path })).unwrap();
std::fs::read(path).unwrap()
}
/// Enter at the paper question after a change of device keeps the paper's name but takes the new
/// device's margins for it, in the plot as in the saved page setup: the plot the user approved is
/// the plot the saved page setup gives.
#[test]
fn a_device_change_plots_with_the_margins_it_saves() {
let mut s = session();
let dir = TempDir::new("dash-plot-device-margins");
s.execute("pagesetup", &json!({ "layout": "Layout1", "device": "CADCraft PDF", "paper": "A3", "landscape": true })).unwrap();
let before = page(&mut s, "Layout1");
let paper = before["paper"].as_str().unwrap().to_string();
device_with_margins(&mut s, "Wide margins 3433", &paper, [30.0, 30.0, 30.0, 30.0]);
let typed = out(&dir, "typed.pdf");
s.script(&format!("-PLOT Y\nLayout1\nWide margins 3433\n\nM L N L F 0,0 Y\n.\nY N N N\n{typed}\nY Y\n")).unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
let saved = page(&mut s, "Layout1");
assert_eq!(saved["paper"], before["paper"], "Enter kept the paper");
assert_ne!(saved["marginsMm"], before["marginsMm"], "the saved page setup has the new device's margins");
let stored = plot_as_stored(&mut s, "Layout1", &out(&dir, "stored.pdf"));
assert!(std::fs::read(&typed).unwrap() == stored, "the typed plot is the plot its saved page setup gives");
}
/// Enter at the paper question on the layout's own device sends no paper, so the layout keeps
/// margins that are not the device's: the plot and the saved page setup both keep them.
#[test]
fn enter_at_the_paper_question_keeps_the_layouts_own_margins() {
let mut s = session();
let dir = TempDir::new("dash-plot-own-margins");
s.execute("pagesetup", &json!({ "layout": "Layout1", "device": "CADCraft PDF", "paper": "A3", "landscape": true, "margins": [12, 14, 16, 18] }))
.unwrap();
let before = page(&mut s, "Layout1");
let typed = out(&dir, "typed.pdf");
s.script(&format!("-PLOT Y\nLayout1\n\n\nM L N L F 0,0 Y\n.\nY N N N\n{typed}\nY Y\n")).unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
assert_eq!(page(&mut s, "Layout1")["marginsMm"], before["marginsMm"], "the layout keeps its own margins");
let stored = plot_as_stored(&mut s, "Layout1", &out(&dir, "stored.pdf"));
assert!(std::fs::read(&typed).unwrap() == stored, "the typed plot is the plot its saved page setup gives");
}
/// Turning the orientation of a layout that keeps its paper turns its margins with the sheet, in
/// the plot as in the saved page setup.
#[test]
fn a_turned_layout_plots_with_the_margins_it_saves() {
let mut s = session();
let dir = TempDir::new("dash-plot-turned");
s.execute("pagesetup", &json!({ "layout": "Layout2", "device": "CADCraft PDF", "paper": "A4", "landscape": false, "margins": [5, 10, 15, 20] }))
.unwrap();
let typed = out(&dir, "typed.pdf");
s.script(&format!("-PLOT Y\nLayout2\n\n\nM L N L F 0,0 Y\n.\nY N N N\n{typed}\nY Y\n")).unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
assert_eq!(page(&mut s, "Layout2")["landscape"], true);
let stored = plot_as_stored(&mut s, "Layout2", &out(&dir, "stored.pdf"));
assert!(std::fs::read(&typed).unwrap() == stored, "the typed plot is the plot its saved page setup gives");
}
/// A Model plot to an SVG device can only be centred (`plot` refuses an offset there): the offset
/// question says so, refuses an offset, and Enter plots. A PDF device keeps the offset 0,0.
#[test]
fn a_model_svg_plot_is_centred_at_the_offset_question() {
let mut s = session();
let dir = TempDir::new("dash-plot-svg");
let svg = out(&dir, "model.svg");
s.script("-PLOT Y\nModel\nCADCraft SVG\nA4\nM L N E F\n").unwrap();
let question = asked(&s);
assert!(question.to_lowercase().contains("offset") && question.contains("<Center>"), "{question}");
for offset in ["0,0", "5,5"] {
let said = s.log.len();
s.cmdline(offset).unwrap();
assert_eq!(asked(&s), question, "`{offset}` is not available for an SVG plot of model space");
assert!(s.log.len() > said, "`{offset}` is told why it is refused");
}
s.cmdline("").unwrap();
s.script(&format!("Y\n.\nY A\n{svg}\nN Y\n")).unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
assert!(std::fs::read(&svg).unwrap_or_else(|e| panic!("{svg}: {e}; {:?}", s.log.last())).starts_with(b"<svg"), "the SVG was plotted");
s.script("-PLOT Y\nModel\nCADCraft PDF\nA4\nM L N E F\n").unwrap();
assert!(asked(&s).contains("<0,0>"), "{}", asked(&s));
s.input(Input::Cancel).unwrap();
}
/// Enter at the paper units question stores the units the question showed: a metric drawing's
/// layout moved to an inch sheet shows Inches, and the scale typed there is saved in inches. A
/// layout that keeps its paper and its units is not given units of its own.
#[test]
fn enter_at_the_units_question_saves_the_units_it_shows() {
let mut s = session();
s.execute("setvar", &json!({ "name": "MEASUREMENT", "value": 1 })).unwrap();
s.script("-PAGESETUP\nLayout1\nCADCraft PDF\nANSI B\n").unwrap();
assert!(asked(&s).contains("<Inches>"), "{}", asked(&s));
s.cmdline("").unwrap();
s.script("L N L 1=2 0,0 Y\n.\nY N N N\n").unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
let p = page(&mut s, "Layout1");
assert!(p["paper"].as_str().unwrap().contains("ANSI B"), "{p}");
assert!((p["scale"].as_f64().unwrap() - 0.5).abs() < 1e-9, "{p}");
assert_eq!(p["paperMm"], false, "1=2 was answered in inches, so the saved scale is in inches: {p}");
let before = page(&mut s, "Layout2");
assert!(before.get("paperMm").is_none(), "a new layout follows the drawing's units: {before}");
s.script("-PAGESETUP\nLayout2\nCADCraft PDF\n\n").unwrap();
assert!(asked(&s).to_lowercase().contains("paper units"), "{}", asked(&s));
s.cmdline("").unwrap();
s.script("L N L F 0,0 Y\n.\nY N N N\n").unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
let after = page(&mut s, "Layout2");
assert_eq!(after["paper"], before["paper"]);
assert!(after.get("paperMm").is_none(), "the layout keeps following the drawing's units: {after}");
}
/// Set the plot area a layout's page setup stores, as a drawing file would have it.
fn store_plot_area(s: &mut Session, layout: &str, area: &str, window: [f64; 4]) {
let l = s.doc_mut().unwrap().layouts.iter_mut().find(|l| l.name == layout).expect("the layout");
l.page.plot_area = area.into();
l.page.plot_window = window;
}
/// -PLOT on a layout shows and takes the area the plot really covers: the sheet, also when the
/// page setup read from a file stores another area that no plot of a layout honours, or the
/// stored plot window when there is a real one. -PAGESETUP still shows and keeps what is stored.
#[test]
fn a_layout_is_offered_the_plot_area_it_really_plots() {
let mut s = session();
let dir = TempDir::new("dash-plot-layout-area");
s.execute("pagesetup", &json!({ "layout": "Layout1", "device": "CADCraft PDF", "paper": "A4", "landscape": false })).unwrap();
let sheet = out(&dir, "sheet.pdf");
s.execute("plot", &json!({ "layout": "Layout1", "fit": false, "scale": 1, "path": sheet })).unwrap();
// A stored area that changes nothing in a plot (and a window with no size) is the sheet.
for (area, window) in [("extents", [0.0; 4]), ("display", [0.0; 4]), ("limits", [0.0; 4]), ("window", [0.0; 4])] {
store_plot_area(&mut s, "Layout1", area, window);
s.script("-PLOT Y\nLayout1\n\n\nM P N\n").unwrap();
let question = asked(&s);
assert!(question.to_lowercase().contains("plot area") && question.contains("<Layout>"), "stored {area}: {question}");
for other in ["E", "D", "W", "V"] {
let said = s.log.len();
s.cmdline(other).unwrap();
assert_eq!(asked(&s), question, "stored {area}: `{other}` is not what a layout plots");
assert!(s.log.len() > said, "`{other}` is told why it is refused");
}
let pdf = out(&dir, &format!("{area}.pdf"));
s.script(&format!("L 1=1 0,0 Y\n.\nY N N N\n{pdf}\nN Y\n")).unwrap();
assert!(s.current_prompt().is_none(), "stored {area}: the command ended: {:?}", s.current_prompt());
assert!(std::fs::read(&pdf).unwrap() == std::fs::read(&sheet).unwrap(), "stored {area}: the sheet is what is plotted");
assert_eq!(page(&mut s, "Layout1")["plotArea"], area, "saving answered No: the stored area stays");
}
// A real stored window is what the plot covers: it is shown, and the sheet is refused.
store_plot_area(&mut s, "Layout1", "window", [0.0, 0.0, 100.0, 50.0]);
s.script("-PLOT Y\nLayout1\n\n\nM P N\n").unwrap();
let question = asked(&s);
assert!(question.contains("<Window>"), "{question}");
s.cmdline("L").unwrap();
assert_eq!(asked(&s), question, "the stored window is plotted, not the sheet");
s.input(Input::Cancel).unwrap();
// -PAGESETUP shows what the file stored and keeps it unless Layout is answered.
store_plot_area(&mut s, "Layout1", "extents", [0.0; 4]);
s.script("-PAGESETUP\nLayout1\n\n\nM P N\n").unwrap();
assert!(asked(&s).contains("<Extents>"), "{}", asked(&s));
s.cmdline("").unwrap();
s.script("1=1 0,0 Y\n.\nY N N N\n").unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
assert_eq!(page(&mut s, "Layout1")["plotArea"], "extents");
}
/// A file name whose type is not what the device writes is refused at the file question, which
/// is asked again; a name without a type still gets the device's.
#[test]
fn a_file_type_the_device_does_not_write_is_refused_at_the_file_question() {
let mut s = session();
let dir = TempDir::new("dash-plot-file-type");
s.script("-PLOT Y\nModel\nCADCraft PDF\nA4\nM L N E F C Y\n.\nY A\n").unwrap();
let question = asked(&s);
assert!(question.to_lowercase().contains("file name"), "{question}");
for wrong in ["sheet.svg", "sheet.PNG"] {
let said = s.log.len();
s.cmdline(&out(&dir, wrong)).unwrap();
assert_eq!(asked(&s), question, "`{wrong}` is not a file the PDF device writes");
assert!(s.log.len() > said, "`{wrong}` is told why it is refused");
}
s.cmdline(&out(&dir, "sheet")).unwrap();
assert!(asked(&s).to_lowercase().contains("save"), "{}", asked(&s));
s.script("N Y\n").unwrap();
assert!(s.current_prompt().is_none());
assert!(is_sheet(media(&out(&dir, "sheet.pdf")), A4_PT, true));
assert!(!std::path::Path::new(&out(&dir, "sheet.svg")).exists() && !std::path::Path::new(&out(&dir, "sheet.PNG")).exists());
// The short form asks the same question.
s.script("-PLOT N\nModel\n\nCADCraft PNG\n").unwrap();
let question = asked(&s);
s.cmdline(&out(&dir, "short.pdf")).unwrap();
assert_eq!(asked(&s), question, "the PNG device does not write a PDF");
s.input(Input::Cancel).unwrap();
}
/// Save answered Yes and the plot answered Yes: a plot that fails saves nothing, so the page
/// setup never holds answers whose plot the user did not get.
#[test]
fn a_failed_plot_saves_no_page_setup() {
let mut s = session();
let dir = TempDir::new("dash-plot-failed");
// A folder stands where the file should be written.
let taken = out(&dir, "taken.pdf");
std::fs::create_dir_all(&taken).unwrap();
let before = page(&mut s, "Layout1");
s.script(&format!("-PLOT Y\nLayout1\nCADCraft PDF\nA3\nM P N L F 0,0 Y\n.\nY N N N\n{taken}\nY Y\n")).unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
assert!(std::path::Path::new(&taken).is_dir(), "nothing was plotted over the folder");
assert_eq!(page(&mut s, "Layout1"), before, "the failed plot saved nothing");
assert!(!s.log.iter().any(|l| l.contains("saved")), "{:?}", s.log);
}
/// Drawing limits without an area cannot be plotted: Limits is refused at the plot area question
/// and not at the end of the command.
#[test]
fn limits_without_an_area_are_refused_at_the_area_question() {
let mut s = session();
s.execute("limits", &json!({ "min": [0, 0], "max": [0, 9] })).unwrap();
s.script("-PLOT Y\nModel\nCADCraft PDF\nA4\nM L N\n").unwrap();
let question = asked(&s);
assert!(question.to_lowercase().contains("plot area"), "{question}");
let said = s.log.len();
s.cmdline("L").unwrap();
assert_eq!(asked(&s), question, "limits without an area are not a plot area");
assert!(s.log.len() > said);
s.cmdline("E").unwrap();
assert_ne!(asked(&s), question);
s.input(Input::Cancel).unwrap();
}
+111
View File
@@ -0,0 +1,111 @@
//! ACADVER is the program's release as text, as AutoCAD documents it, so `(atof (getvar
//! "ACADVER"))` reads a number from it. It is read-only, and the drawing's `$ACADVER` stays the
//! file version a save writes, so a drawing read from a 2000 DXF saves as one.
use cadcraft_engine::Session;
use cadcraft_engine::lisp::value::Value;
use serde_json::json;
/// The release text `getvar` and `(getvar "ACADVER")` report.
const RELEASE: &str = "24.3s (CADCraft)";
/// A 2000 DXF (`$ACADVER` `AC1015`) holding one line.
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n\
0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n10.0\n21\n0.0\n31\n0.0\n\
0\nENDSEC\n0\nEOF\n";
/// A LISP expression's value, or its error message.
fn lisp(s: &mut Session, code: &str) -> Result<Value, String> {
match s.lisp_eval(code, false, true, Vec::new()) {
Ok(Some(Ok(v))) => Ok(v),
Ok(Some(Err(e))) => Err(e),
Ok(None) => Err("did not finish".into()),
Err(e) => Err(e.to_string()),
}
}
/// GETVAR's value.
fn getvar(s: &mut Session, name: &str) -> serde_json::Value {
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
}
/// The `$ACADVER` a DXF text declares.
fn file_version(text: &str) -> Option<String> {
let l: Vec<&str> = text.lines().map(str::trim).collect();
let at = l.windows(2).position(|w| w == ["9", "$ACADVER"])?;
l.get(at + 2).filter(|c| **c == "1").and_then(|_| l.get(at + 3)).map(|v| (*v).to_string())
}
#[test]
fn getvar_gives_the_release_text_and_atof_reads_the_number() {
let mut s = Session::new();
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
assert_eq!(getvar(&mut s, "acadver"), json!(RELEASE), "lower-case names work");
assert!(matches!(lisp(&mut s, "(getvar \"ACADVER\")"), Ok(Value::Str(t)) if &*t == RELEASE), "a LISP string");
assert!(matches!(lisp(&mut s, "(atof (getvar \"ACADVER\"))"), Ok(Value::Real(r)) if (r - 24.3).abs() < 1e-9), "(atof) reads the release number");
}
#[test]
fn setvar_refuses_acadver_and_changes_nothing() {
let mut s = Session::new();
let before = s.state().unwrap().doc.header.str("ACADVER", "");
let e = s.execute("setvar", &json!({ "name": "ACADVER", "value": "AC1027" })).unwrap_err().to_string();
assert!(e.contains("read-only"), "{e}");
assert!(lisp(&mut s, "(setvar \"ACADVER\" \"AC1027\")").is_err(), "AutoLISP's setvar too");
// Typed at the command line, SETVAR reports the variable as read-only at its name prompt.
s.cmdline("setvar acadver").unwrap();
assert!(s.log.iter().any(|l| l == &format!("ACADVER = {RELEASE} (read only)")), "{:?}", s.log);
// Neither the release text nor the drawing's file version moved.
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), before);
assert_eq!(before, "AC1032");
}
#[test]
fn a_2000_drawing_saves_as_2000() {
crate::refedit_xref::hooks();
let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("acadver-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("r2000.dxf");
let name = path.to_string_lossy().into_owned();
let mut s = Session::empty();
s.open_drawing(cadcraft_io::read_dxf(DXF.as_bytes()).unwrap(), "r2000.dxf", Some(name.clone()));
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1015", "read as 2000");
assert_eq!(cadcraft_io::save_version(&s.state().unwrap().doc), cadcraft_io::Version::R2000);
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE), "still the release text");
s.execute("qsave", &json!({})).unwrap();
let saved = std::fs::read_to_string(&path).unwrap();
assert_eq!(file_version(&saved).as_deref(), Some("AC1015"), "the file keeps its 2000 version");
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1015");
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
assert_eq!(cadcraft_io::read_dxf(saved.as_bytes()).unwrap().header.str("ACADVER", ""), "AC1015", "and reopens as 2000");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_dollar_name_cannot_change_the_file_version() {
let mut s = Session::new();
let e = s.execute("setvar", &json!({ "name": "$ACADVER", "value": "AC1027" })).unwrap_err().to_string();
assert!(e.contains("read-only"), "{e}");
assert!(lisp(&mut s, "(setvar \"$ACADVER\" \"AC1015\")").is_err(), "AutoLISP's setvar too");
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1032", "the save version did not move");
assert!(cadcraft_engine::sysvars::is_read_only("$acadver"), "SETVAR's prompt sees it as read-only too");
// Other `$` names still reach the header as before, in LISP's units.
assert!(lisp(&mut s, "(setvar \"$ANGBASE\" (/ pi 2))").is_ok());
assert!(matches!(lisp(&mut s, "(getvar \"$ANGBASE\")"), Ok(Value::Real(r)) if (r - std::f64::consts::FRAC_PI_2).abs() < 1e-9));
let r = s.execute("setvar", &json!({ "name": "$OSMODE", "value": 9 })).unwrap();
assert_eq!(r["value"], json!(9), "{r}");
}
#[test]
fn listings_show_the_release_text_without_a_drawing() {
let mut s = Session::empty();
let all = s.execute("sysvars", &json!({})).unwrap();
let text = all.to_string();
assert!(text.contains(RELEASE), "{text}");
let mut s = Session::new();
let all = s.execute("sysvars", &json!({})).unwrap().to_string();
assert!(all.contains(RELEASE) && !all.contains("\"AC1032\""), "{all}");
}
@@ -10,8 +10,7 @@ use cadcraft_engine::cmd::file::MAX_ALIASES;
use cadcraft_engine::cmd::resolve_alias;
use serde_json::json;
#[path = "support/temp_dir.rs"]
mod temp_dir;
use crate::temp_dir;
use temp_dir::TempDir;
+1 -1
View File
@@ -81,7 +81,7 @@ fn unsupported_scale_hides_unless_annoallvisible() {
let (mut s, h) = with_text();
setvar(&mut s, "CANNOSCALE", json!("1:20"));
// ANNOALLVISIBLE 1 (the default): shown, at the object's own scale.
assert_eq!(s.doc().unwrap().anno_draw(&entity(&s, h)), AnnoDraw::Scaled(1.0));
assert_eq!(s.doc().unwrap().anno_draw(&entity(&s, h)), AnnoDraw::Scaled { factor: 1.0, by: cadcraft_engine::geom::Vec2::ZERO });
assert!(drawn_height(s.doc().unwrap(), h).is_some());
s.execute("annovisible.current", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().header.i64("ANNOALLVISIBLE", 1), 0);
@@ -0,0 +1,221 @@
//! An annotative object can sit somewhere else at one of its scales: its grips move it at the
//! current annotation scale only (when it supports several), MOVE and ROTATE move every scale,
//! and ANNORESET puts every scale back where the current one is.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{AnnoDraw, Entity, EntityKind, Handle};
use cadcraft_engine::geom::Vec2;
use serde_json::{Value, json};
fn setvar(s: &mut Session, name: &str, value: Value) {
s.execute("setvar", &json!({ "name": name, "value": value })).unwrap();
}
fn handle(r: &Value) -> Handle {
r["handle"].as_str().or_else(|| r["handles"][0].as_str()).and_then(Handle::parse_hex).unwrap()
}
fn entity(s: &Session, h: Handle) -> Entity {
(**s.doc().unwrap().entity(h).unwrap()).clone()
}
/// Annotative text at the origin supporting 1:1 and 1:50, with 1:50 current.
fn two_scales() -> (Session, Handle) {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
let h = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap());
setvar(&mut s, "CANNOSCALE", json!("1:50"));
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:50" })).unwrap();
(s, h)
}
/// Where `h` shows at annotation scale `name`.
fn shown_at(s: &mut Session, h: Handle, name: &str) -> Vec2 {
setvar(s, "CANNOSCALE", json!(name));
let d = s.doc().unwrap();
match d.anno_shown(d.entity(h).unwrap()) {
EntityKind::Text(t) => t.insert.xy(),
EntityKind::MText(t) => t.insert.xy(),
EntityKind::MLeader(m) => m.landing.xy(),
EntityKind::Dimension(dm) => dm.text_mid.xy(),
k => panic!("{k:?}"),
}
}
fn near(a: Vec2, b: Vec2) -> bool {
a.dist(b) < 1e-9
}
#[test]
fn a_grip_moves_text_at_the_current_scale_only() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
// The grips show where the object is.
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(5.0, 5.0)));
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(5.0, 5.0)));
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::ZERO));
}
#[test]
fn grip_scale_keeps_the_displayed_annotation_pivot_and_its_elevation() {
let (mut s, h) = two_scales();
let (z, other_z) = (7.0, 2.0);
s.doc_mut().unwrap().header.set_f64("ELEVATION", other_z);
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
let EntityKind::Text(t) = &mut e.kind else { panic!("expected text") };
t.insert.z = z;
})
.unwrap();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
let pivot = s.grips_of(h).unwrap()[0];
assert!(near(pivot, Vec2::new(5.0, 5.0)));
let EntityKind::Text(before) = entity(&s, h).kind else { panic!("expected text") };
s.execute("grip.scale", &json!({ "handles": [h.hex()], "baseHandle": h.hex(), "index": 0, "factor": 2.0 })).unwrap();
let EntityKind::Text(after) = entity(&s, h).kind else { panic!("expected text") };
assert!(near(s.grips_of(h).unwrap()[0], pivot), "the displayed grip is stationary");
assert!((after.insert.z - z).abs() < 1e-9, "the selected grip's Z is stationary, not ELEVATION");
assert!((after.height - 2.0 * before.height).abs() < 1e-9, "the scale operation actually took effect");
}
#[test]
fn undo_takes_a_move_at_one_scale_back() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
assert_eq!(entity(&s, h).common.anno_moves.len(), 1);
s.execute("undo", &json!({})).unwrap();
assert!(entity(&s, h).common.anno_moves.is_empty());
}
#[test]
fn move_and_rotate_carry_every_scale() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
s.execute("move", &json!({ "handles": [h.hex()], "delta": [1, 0] })).unwrap();
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(6.0, 5.0)));
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(1.0, 0.0)));
s.execute("rotate", &json!({ "handles": [h.hex()], "base": [0, 0], "angle": 90 })).unwrap();
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(-5.0, 6.0)));
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(0.0, 1.0)));
}
#[test]
fn annoreset_puts_every_scale_at_the_current_one() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let r = s.execute("annoreset", &json!({ "handles": [h.hex()] })).unwrap();
assert_eq!(r["reset"], 1, "{r}");
assert!(entity(&s, h).common.anno_moves.is_empty());
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(5.0, 5.0)));
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(5.0, 5.0)));
}
#[test]
fn removing_a_scale_drops_its_position() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
s.execute("objectscale", &json!({ "handles": [h.hex()], "delete": "1:50" })).unwrap();
assert!(entity(&s, h).common.anno_moves.is_empty());
}
#[test]
fn an_object_with_one_scale_moves_everywhere() {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let h = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap());
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
let e = entity(&s, h);
assert!(e.common.anno_moves.is_empty());
let EntityKind::Text(t) = &e.kind else { panic!() };
assert!(near(t.insert.xy(), Vec2::new(5.0, 5.0)));
}
#[test]
fn a_multileader_moves_its_content_and_keeps_its_arrowhead() {
let mut s = Session::new();
s.execute("mleaderstyle", &json!({ "name": "Anno", "annotative": true })).unwrap();
let h = handle(&s.execute("mleader", &json!({ "points": [[0, 0], [5, 5]], "text": "A" })).unwrap());
setvar(&mut s, "CANNOSCALE", json!("1:50"));
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:50" })).unwrap();
let EntityKind::MLeader(m) = entity(&s, h).kind else { panic!() };
let landing = m.leaders.iter().map(Vec::len).sum::<usize>();
let to = m.landing.xy() + Vec2::new(2.0, 1.0);
s.execute("grip.move", &json!({ "handle": h.hex(), "index": landing, "to": [to.x, to.y] })).unwrap();
assert!(near(shown_at(&mut s, h, "1:50"), to));
assert!(near(shown_at(&mut s, h, "1:1"), m.landing.xy()));
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let d = s.doc().unwrap();
let EntityKind::MLeader(shown) = d.anno_shown(d.entity(h).unwrap()) else { panic!() };
assert!(near(shown.leaders[0][0].xy(), Vec2::ZERO), "the arrowhead stays");
}
#[test]
fn a_dimension_moves_its_text_at_one_scale() {
let mut s = Session::new();
s.execute("dimstyle", &json!({ "name": "Anno", "annotative": true, "current": true })).unwrap();
let h = handle(&s.execute("dimaligned", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 2] })).unwrap());
setvar(&mut s, "CANNOSCALE", json!("1:2"));
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:2" })).unwrap();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 3, "to": [20, 20] })).unwrap();
assert!(near(shown_at(&mut s, h, "1:2"), Vec2::new(20.0, 20.0)));
let e = entity(&s, h);
let EntityKind::Dimension(dm) = &e.kind else { panic!() };
assert!(!near(dm.text_mid.xy(), Vec2::new(20.0, 20.0)), "the shared text position stays");
assert_eq!(e.common.anno_moves.len(), 1);
}
#[test]
fn shown_draws_through_the_offset() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let d = s.doc().unwrap();
assert!(matches!(d.anno_draw(d.entity(h).unwrap()), AnnoDraw::Scaled { by, .. } if near(by, Vec2::new(5.0, 5.0))));
let b = cadcraft_engine::doc::entity_bounds(d, d.entity(h).unwrap(), 0);
assert!(b.min.x > 4.0 && b.min.y > 4.0, "{b:?}");
}
#[test]
fn hostile_offsets_never_panic() {
let (mut s, h) = two_scales();
for to in [json!([1e308, -1e308]), json!([f64::MAX, 0]), json!(["x", 1])] {
let _ = s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": to }));
}
s.doc_mut().unwrap().modify_entity(h, |e| e.common.move_at("1:50", Vec2::new(f64::NAN, 1.0))).unwrap();
let _ = s.execute("annoreset", &json!({ "handles": [h.hex()] }));
let _ = s.execute("rotate", &json!({ "handles": [h.hex()], "base": [0, 0], "angle": 1e300 }));
let d = s.doc().unwrap();
let _ = cadcraft_engine::render::build(d, &cadcraft_engine::doc::Space::Model, &Default::default());
let _ = bounds(d, h);
}
fn bounds(d: &cadcraft_engine::doc::Drawing, h: Handle) -> cadcraft_engine::geom::Bounds2 {
cadcraft_engine::doc::entity_bounds(d, d.entity(h).unwrap(), 0)
}
#[test]
fn in_a_viewport_grips_and_annoreset_use_the_viewport_s_scale() {
// The text moved at 1:50; CANNOSCALE is 1:1 while a 1:50 viewport is active (MSPACE): the
// grips show where the viewport draws it, a grip moves it at 1:50, ANNORESET takes 1:50's place.
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:1"));
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
let vp = s.execute("mview", &json!({ "p1": [0, 0], "p2": [200, 100] })).unwrap();
let vh = vp["viewports"][0].as_str().and_then(Handle::parse_hex).unwrap();
s.execute("viewport.set", &json!({ "handle": vh.hex(), "scale": "1:50", "center": [0, 0] })).unwrap();
s.execute("mspace", &json!({ "handle": vh.hex() })).unwrap();
assert!((s.anno_view().unwrap() - 50.0).abs() < 1e-9);
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(5.0, 5.0)), "{:?}", s.grips_of(h));
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [7, 7] })).unwrap();
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(7.0, 7.0)));
s.execute("annoreset", &json!({ "handles": [h.hex()] })).unwrap();
s.execute("pspace", &json!({})).unwrap();
s.execute("layout.set", &json!({ "name": "Model" })).unwrap();
// 1:1 was never moved by the grips, and now sits where 1:50 is.
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(7.0, 7.0)));
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(7.0, 7.0)));
}
+233
View File
@@ -0,0 +1,233 @@
//! DIMRADIUS, DIMDIAMETER and DIMJOGGED take a circle or arc inside a block reference, in nested
//! references too, as AutoCAD does (#1967). A pick on a block's line, or on a circle the reference
//! scales unevenly (drawn as an ellipse), is not a circle or arc.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{DimKind, Dimension, EntityKind};
use cadcraft_engine::geom::Vec2;
use serde_json::json;
/// A drawing with block "P": a circle of radius 5 and an arc of radius 3 from 0° to 90° at its
/// origin, and a line from (10, 0) to (20, 0).
fn session() -> Session {
let mut s = Session::new();
s.execute("circle", &json!({"center": [0, 0], "radius": 5})).unwrap();
s.execute("arc", &json!({"center": [0, 0], "radius": 3, "start": 0, "end": 90})).unwrap();
s.execute("line", &json!({"points": [[10, 0], [20, 0]]})).unwrap();
s.execute("selectall", &json!({})).unwrap();
s.execute("block", &json!({"name": "P", "base": [0, 0], "keep": "delete"})).unwrap();
s
}
fn dims(s: &Session) -> Vec<Dimension> {
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Dimension(d) = &e.kind { Some(d.clone()) } else { None }).collect()
}
/// `p` written for a typed point.
fn pt(p: Vec2) -> String {
format!("{},{}", p.x, p.y)
}
#[test]
fn radius_and_diameter_of_a_circle_or_arc_in_a_rotated_scaled_reference() {
let mut s = session();
s.execute("insert", &json!({"name": "P", "at": [40, 10], "rotation": 30, "scale": 2})).unwrap();
let c = Vec2::new(40.0, 10.0);
// The circle: radius 10 in the drawing, picked away from the arc and the line.
let on_circle = c + Vec2::from_angle(200f64.to_radians()) * 10.0;
s.script(&format!("dimradius {} {}\n", pt(on_circle), pt(c + Vec2::new(-15.0, -8.0)))).unwrap();
assert!(s.running.is_none());
let d = dims(&s);
assert_eq!(d.len(), 1, "a radius dimension of the nested circle");
assert!(matches!(d[0].kind, DimKind::Radius));
assert!(d[0].defpt.xy().dist(c) < 1e-9, "centred on the circle: {:?}", d[0].defpt);
assert!((d[0].p15.xy().dist(c) - 10.0).abs() < 1e-9, "radius {}", d[0].p15.xy().dist(c));
// The arc: the block's 0°–90° become 30°–120°, radius 6; its diameter is 12.
let on_arc = c + Vec2::from_angle(75f64.to_radians()) * 6.0;
s.script(&format!("dimdiameter {} {}\n", pt(on_arc), pt(c + Vec2::new(2.0, 20.0)))).unwrap();
let d = dims(&s);
assert_eq!(d.len(), 2, "a diameter dimension of the nested arc");
assert!(matches!(d[1].kind, DimKind::Diameter));
assert!((d[1].p15.xy().dist(d[1].defpt.xy()) - 12.0).abs() < 1e-9, "diameter {}", d[1].p15.xy().dist(d[1].defpt.xy()));
// DIMJOGGED takes it too: a jogged radius dimension of the nested circle.
s.script(&format!(
"dimjogged {} {} {} {}\n",
pt(on_circle),
pt(c + Vec2::new(-30.0, -20.0)),
pt(c + Vec2::new(-12.0, -9.0)),
pt(c + Vec2::new(-20.0, -12.0))
))
.unwrap();
let d = dims(&s);
assert_eq!(d.len(), 3, "a jogged dimension of the nested circle");
assert!(d[2].marks.jogged.is_some());
assert!((d[2].p15.xy().dist(c) - 10.0).abs() < 1e-9);
}
#[test]
fn a_circle_two_references_deep_is_taken() {
let mut s = session();
// Block Q holds P at (100, 0), half size; Q is inserted at (0, -50).
let p = s.execute("insert", &json!({"name": "P", "at": [100, 0], "scale": 0.5})).unwrap()["handle"].as_str().unwrap().to_string();
s.execute("block", &json!({"name": "Q", "base": [0, 0], "handles": [p], "keep": "delete"})).unwrap();
s.execute("insert", &json!({"name": "Q", "at": [0, -50]})).unwrap();
s.script("dimradius 100,-52.5 110,-60\n").unwrap();
let d = dims(&s);
assert_eq!(d.len(), 1);
assert!(d[0].defpt.xy().dist(Vec2::new(100.0, -50.0)) < 1e-9, "{:?}", d[0].defpt);
assert!((d[0].p15.xy().dist(Vec2::new(100.0, -50.0)) - 2.5).abs() < 1e-9);
}
/// A mirrored reference (scale -1 in X) still draws a circle: the dimension is centred on the
/// mirrored centre with the circle's radius, in drawing units. It is not associative: the
/// attachments name objects of the drawing, and the circle is inside the block.
#[test]
fn a_circle_in_a_mirrored_reference_is_taken_unassociated() {
let mut s = session();
s.execute("insert", &json!({"name": "P", "at": [-60, 0], "scale": [-1.5, 1.5]})).unwrap();
let c = Vec2::new(-60.0, 0.0);
// The circle has radius 7.5 here; picked on its left, away from the arc and the mirrored line.
s.script(&format!("dimradius {} {}\n", pt(c + Vec2::new(0.0, -7.5)), pt(c + Vec2::new(-5.0, -15.0)))).unwrap();
let d = dims(&s);
assert_eq!(d.len(), 1, "a radius dimension of the circle in the mirrored reference");
assert!(d[0].defpt.xy().dist(c) < 1e-9, "centred on the mirrored centre: {:?}", d[0].defpt);
assert!((d[0].p15.xy().dist(c) - 7.5).abs() < 1e-9, "radius {}", d[0].p15.xy().dist(c));
assert!(d[0].assoc.is_empty(), "{:?}", d[0].assoc);
}
#[test]
fn a_blocks_line_or_an_unevenly_scaled_circle_is_not_a_circle() {
let mut s = session();
// Twice as wide as tall: the circle is drawn as an ellipse.
s.execute("insert", &json!({"name": "P", "at": [0, 100], "scale": [2, 1]})).unwrap();
s.script("dimradius 10,100\n").unwrap();
assert!(s.log.iter().any(|l| l == "Object selected is not a circle or arc."), "{:?}", s.log);
s.cancel();
// The block's line, in an evenly scaled reference.
s.execute("insert", &json!({"name": "P", "at": [0, 200]})).unwrap();
s.script("dimdiameter 15,200\n").unwrap();
assert!(s.log.iter().filter(|l| *l == "Object selected is not a circle or arc.").count() == 2, "{:?}", s.log);
s.cancel();
assert!(dims(&s).is_empty(), "no dimension made");
}
/// A pick on a circle is not lost to an unevenly scaled circle nearby that comes first in the
/// block. That one is measured as the ellipse it is drawn as, not as a circle of its average
/// radius, which here passes through the very point picked.
#[test]
fn an_unevenly_scaled_circle_nearby_does_not_hide_a_circle() {
let mut s = session();
let avg = 50f64.sqrt(); // P's circle of radius 5 scaled 2 × 1: average radius 5·√2
let mut handle = |p: serde_json::Value| s.execute("insert", &p).unwrap()["handle"].as_str().unwrap().to_string();
let uneven = handle(json!({"name": "P", "at": [0, 0], "scale": [2, 1]}));
let even = handle(json!({"name": "P", "at": [avg + 5.0, 0]}));
s.execute("block", &json!({"name": "R", "base": [0, 0], "handles": [uneven, even], "keep": "delete"})).unwrap();
s.execute("insert", &json!({"name": "R", "at": [0, 300]})).unwrap();
s.script(&format!("dimradius {avg},300 {},310\n", avg + 5.0)).unwrap();
let d = dims(&s);
assert_eq!(d.len(), 1, "the even circle under the cursor is taken: {:?}", s.log.last());
let c = Vec2::new(avg + 5.0, 300.0);
assert!(d[0].defpt.xy().dist(c) < 1e-9, "{:?}", d[0].defpt);
assert!((d[0].p15.xy().dist(c) - 5.0).abs() < 1e-9);
}
/// A block of `make` (run in model space, then made into block "N"), inserted at the origin.
fn nested(make: impl FnOnce(&mut Session)) -> Session {
let mut s = Session::new();
make(&mut s);
s.execute("selectall", &json!({})).unwrap();
s.execute("block", &json!({"name": "N", "base": [0, 0], "keep": "delete"})).unwrap();
s.execute("insert", &json!({"name": "N", "at": [0, 0]})).unwrap();
s
}
/// A pick on what else a block draws is measured as any pick measures it: on a text's box or
/// inside a SOLID it is that object, not a circle passing a hair away; behind a ray's start it is
/// not the ray.
#[test]
fn text_solids_and_rays_in_a_block_are_measured_as_they_are_drawn() {
// Inside the box of a text, far from its insertion point.
let mut s = nested(|s| {
s.execute("text", &json!({"at": [0, 0], "text": "HELLO", "height": 2})).unwrap();
s.execute("circle", &json!({"center": [8.000001, 1], "radius": 5})).unwrap();
});
// The pick is refused: DIMRADIUS says so and still asks for an arc or circle, where taking the
// circle would have moved on to the dimension line's location.
let refused = |s: &Session| {
s.log.last().is_some_and(|l| l == "Object selected is not a circle or arc.") && s.prompt_text().contains("Select arc or circle")
};
s.script("dimradius 3,1\n").unwrap();
assert!(refused(&s), "the pick is on the text: {:?} / {}", s.log, s.prompt_text());
s.cancel();
assert!(dims(&s).is_empty(), "the pick is on the text");
// Inside a SOLID, far from its edges.
let mut s = nested(|s| {
s.execute("solid", &json!({"points": [[0, 0], [10, 0], [0, 10], [10, 10]]})).unwrap();
s.execute("circle", &json!({"center": [10.000001, 5], "radius": 5})).unwrap();
});
let kinds: Vec<&str> = s.doc().unwrap().block("N").unwrap().entities.iter().map(|e| e.kind.type_name()).collect();
assert!(kinds.contains(&"2D Solid"), "the block holds the SOLID: {kinds:?}");
s.script("dimradius 5,5\n").unwrap();
assert!(refused(&s), "the pick is on the SOLID: {:?} / {}", s.log, s.prompt_text());
s.cancel();
assert!(dims(&s).is_empty(), "the pick is on the SOLID");
// Behind the start of a ray: the circle passing there is the object picked.
let mut s = nested(|s| {
s.execute("ray", &json!({"base": [0, 0], "through": [1, 0]})).unwrap();
s.execute("circle", &json!({"center": [-5, 5.000001], "radius": 5})).unwrap();
});
s.script("dimradius -5,0 -12,-4\n").unwrap();
let d = dims(&s);
assert_eq!(d.len(), 1, "the circle behind the ray's start is taken: {:?}", s.log.last());
assert!((d[0].p15.xy().dist(d[0].defpt.xy()) - 5.0).abs() < 1e-9);
}
/// In a layout viewport, a circle on a layer frozen there is not drawn, so it can't be picked.
#[test]
fn a_circle_on_a_layer_frozen_in_the_viewport_is_not_taken() {
// Inside a layout viewport, the circle's layer frozen there or not.
let viewport = |freeze: bool| {
let mut s = nested(|s| {
s.execute("layer.new", &json!({"name": "HID", "current": true})).unwrap();
s.execute("circle", &json!({"center": [0, 0], "radius": 4})).unwrap();
s.execute("layer.current", &json!({"name": "0"})).unwrap();
s.execute("line", &json!({"points": [[-10, -10], [-9, -10]]})).unwrap();
});
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
let r = s.execute("mview", &json!({"p1": [20, 20], "p2": [220, 120]})).unwrap();
let vp = r["viewports"][0].as_str().unwrap().to_string();
s.execute("mspace", &json!({"handle": vp})).unwrap();
if freeze {
s.execute("vplayer", &json!({"handle": vp, "freeze": ["HID"]})).unwrap();
}
s.script("dimradius 4,0 6,3\n").unwrap();
s.cancel();
s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Dimension(_))).count()
};
assert_eq!(viewport(false), 1, "thawed, the circle is taken through the viewport");
assert_eq!(viewport(true), 0, "frozen in the viewport, it is not drawn there and not taken");
}
/// A circle with no size, as a file can hold, is refused rather than given a degenerate
/// dimension, whether it is picked directly or inside a block.
#[test]
fn a_zero_radius_circle_is_refused() {
let zero = || EntityKind::Circle(cadcraft_engine::doc::Circle { center: cadcraft_engine::geom::Vec3::new(50.0, 50.0, 0.0), radius: 0.0 });
let mut s = Session::new();
s.doc_mut().unwrap().add(&cadcraft_engine::doc::Space::Model, Default::default(), zero()).unwrap();
s.script("dimradius 50,50\n").unwrap();
assert_eq!(s.log.last().map(String::as_str), Some("Object selected is not a circle or arc."), "{:?}", s.log);
s.cancel();
let mut s = nested(|s| {
s.doc_mut().unwrap().add(&cadcraft_engine::doc::Space::Model, Default::default(), zero()).unwrap();
});
s.script("dimdiameter 50,50\n").unwrap();
assert_eq!(s.log.last().map(String::as_str), Some("Object selected is not a circle or arc."), "{:?}", s.log);
s.cancel();
assert!(dims(&s).is_empty());
}
+386
View File
@@ -0,0 +1,386 @@
//! Legacy system variables a LISP routine saves and restores around its work: DIMASO (obsolete in
//! AutoCAD, which reports and sets DIMASSOC through it), TEXTEVAL, REGENMODE (kept in the drawing
//! and its DXF header) and POPUPS (read-only). Before them `(getvar "DIMASO")` read nil, so
//! `(setq o (getvar "DIMASO")) … (setvar "DIMASO" o)` failed and the routine left the drawing's
//! associativity changed.
use cadcraft_engine::Session;
use cadcraft_engine::lisp::value::{Value as LispValue, to_text};
use serde_json::{Value, json};
fn getvar(s: &mut Session, name: &str) -> Value {
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
}
fn setvar(s: &mut Session, name: &str, value: Value) -> bool {
s.execute("setvar", &json!({ "name": name, "value": value })).is_ok()
}
/// The value of a LISP expression, or the error it left.
fn eval(s: &mut Session, src: &str) -> Result<LispValue, String> {
match s.lisp_eval(src, false, true, Vec::new()) {
Ok(Some(v)) => v,
Ok(None) => Err("no value".into()),
Err(e) => Err(e.to_string()),
}
}
/// `(getvar name)` as the integer a routine receives.
fn lisp_getvar(s: &mut Session, name: &str) -> i64 {
let v = eval(s, &format!("(getvar \"{name}\")")).unwrap_or_else(|e| panic!("{name}: {e}"));
let n = v.as_number().unwrap_or_else(|| panic!("{name} is not a number"));
assert_eq!(n.fract(), 0.0, "{name} is a whole number");
n as i64
}
/// `(setvar name value)` from LISP: whether it was accepted.
fn lisp_setvar(s: &mut Session, name: &str, value: &str) -> bool {
eval(s, &format!("(setvar \"{name}\" {value})")).is_ok()
}
/// The DXF pairs `(group code, value)` of a file, both trimmed.
fn pairs(text: &str) -> Vec<(i32, String)> {
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let mut out = Vec::new();
for chunk in lines.chunks(2) {
let [code, value] = chunk else { break };
let Ok(c) = code.parse::<i32>() else { continue };
out.push((c, (*value).to_string()));
}
out
}
/// The HEADER variable names a DXF text writes (the value after each group code 9).
fn header_names(text: &str) -> Vec<String> {
pairs(text).iter().filter(|(c, _)| *c == 9).map(|(_, v)| v.trim_start_matches('$').to_string()).collect()
}
/// The integer a header variable is written with, as `(group code, value)` after its name.
fn header_int(text: &str, name: &str) -> Option<(i32, String)> {
let ps = pairs(text);
let i = ps.iter().position(|(c, v)| *c == 9 && v.trim_start_matches('$') == name)?;
ps.get(i + 1).cloned()
}
#[test]
fn fresh_values_are_integers_a_routine_reads() {
let mut s = Session::new();
for (name, want) in [("DIMASO", 1), ("TEXTEVAL", 0), ("REGENMODE", 1), ("POPUPS", 1)] {
assert_eq!(getvar(&mut s, name), json!(want), "{name}");
assert_eq!(lisp_getvar(&mut s, name), want, "{name} through getvar");
let kind = eval(&mut s, &format!("(type (getvar \"{name}\"))")).unwrap();
assert_eq!(to_text(&kind, true), "INT", "{name} is an integer to LISP");
}
// The list a routine sees (`SETVAR ?`) carries them too.
let all = cadcraft_engine::sysvars::list(&s);
for name in ["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"] {
assert_eq!(all.get(name), Some(&getvar(&mut s, name)), "{name} listed");
}
}
#[test]
fn a_routine_saving_and_restoring_each_one_leaves_it_as_it_was() {
let mut s = Session::new();
for (name, changed) in [("DIMASO", "0"), ("TEXTEVAL", "1"), ("REGENMODE", "0")] {
let before = lisp_getvar(&mut s, name);
// (setq o (getvar X)) … (setvar X o) must give back exactly what it read.
assert!(eval(&mut s, &format!("(setq o (getvar \"{name}\"))")).is_ok(), "{name} readable");
assert!(lisp_setvar(&mut s, name, changed), "{name} takes {changed}");
assert_ne!(lisp_getvar(&mut s, name), before, "{name} changed by {changed}");
assert!(eval(&mut s, &format!("(setvar \"{name}\" o)")).is_ok(), "{name} restored");
assert_eq!(lisp_getvar(&mut s, name), before, "{name} back to {before}");
}
// REGENMODE is the drawing's, kept in its header; TEXTEVAL only the session's.
assert_eq!(s.doc().unwrap().header.i64("REGENMODE", 1), 1);
}
#[test]
fn dimaso_restores_the_dimassoc_mode_it_turned_off() {
// The routine's save/restore through DIMASO, for each associative mode.
for mode in [1, 2] {
let mut s = Session::new();
assert!(setvar(&mut s, "DIMASSOC", json!(mode)));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1), "DIMASO follows DIMASSOC {mode}");
let o = eval(&mut s, "(getvar \"DIMASSOC\")").unwrap().as_number().unwrap();
assert!(lisp_setvar(&mut s, "DIMASO", "0"));
assert_eq!(getvar(&mut s, "DIMASO"), json!(0));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "DIMASO 0 turns associativity off");
assert!(lisp_setvar(&mut s, "DIMASO", "1"));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
assert_eq!(eval(&mut s, "(getvar \"DIMASSOC\")").unwrap().as_number(), Some(o), "DIMASO 1 puts back the DIMASSOC {mode} the routine read");
}
// Set directly, without ever switching it off first, DIMASO 1 leaves the mode alone.
let mut s = Session::new();
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1));
// No non-zero mode was seen: turning associativity back on gives AutoCAD's 2.
let mut s = Session::new();
assert!(setvar(&mut s, "DIMASSOC", json!(0)));
assert!(setvar(&mut s, "DIMASO", json!(0)));
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2), "none was seen: the default 2");
// A drawing whose saved DIMASSOC is no mode DIMASO can restore (a hostile file) gives 2.
let mut s = Session::new();
s.doc_mut().unwrap().header.set_i64("DIMASSOC", 5);
assert!(setvar(&mut s, "DIMASO", json!(0)));
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2));
// Such a mode is not associative, and DIMASO 1 turns associativity on from it too.
s.doc_mut().unwrap().header.set_i64("DIMASSOC", 5);
assert_eq!(getvar(&mut s, "DIMASO"), json!(0));
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2));
}
#[test]
fn typed_setvar_still_takes_digits() {
for (name, digits) in [("DIMASO", "0"), ("TEXTEVAL", "1"), ("REGENMODE", "0")] {
let want = json!(digits.parse::<i64>().unwrap());
let dollar = format!("${name}");
// SETVAR with the name, the bare name, and the `$` form, as typed at the command line.
for lines in [vec!["setvar", name, digits], vec![name, digits], vec!["setvar", dollar.as_str(), digits]] {
let mut s = Session::new();
for line in &lines {
s.cmdline(line).unwrap();
}
assert_eq!(getvar(&mut s, name), want, "typed {lines:?}");
}
// A routine that types the command passes its answers the same way.
let mut s = Session::new();
eval(&mut s, &format!("(command \"SETVAR\" \"{name}\" \"{digits}\")")).unwrap();
assert_eq!(getvar(&mut s, name), want, "(command \"SETVAR\" {name})");
// Typed words are still refused.
let mut s = Session::new();
let before = getvar(&mut s, name);
for line in ["setvar", name, "two"] {
s.cmdline(line).unwrap();
}
assert_eq!(getvar(&mut s, name), before, "typed word refused for {name}");
}
}
#[test]
fn a_new_drawing_writes_regenmode() {
let mut s = Session::new();
// The first drawing, then a new metric and a new imperial one.
for metric in [None, Some(true), Some(false)] {
if let Some(metric) = metric {
s.new_drawing(metric);
}
let text = cadcraft_io::write_dxf(s.doc().unwrap());
assert_eq!(header_int(&text, "REGENMODE"), Some((70, "1".to_string())), "new drawing, metric {metric:?}");
}
}
#[test]
fn hostile_values_are_refused_and_change_nothing() {
let mut s = Session::new();
for (name, v) in [
("REGENMODE", json!(2)),
("REGENMODE", json!(-1)),
("REGENMODE", json!(1.5)),
("REGENMODE", json!("two")),
("REGENMODE", Value::Null),
("TEXTEVAL", json!(-1)),
("TEXTEVAL", json!(2)),
("TEXTEVAL", json!("two")),
("TEXTEVAL", Value::Null),
("DIMASO", json!(3)),
("DIMASO", json!(-1)),
("DIMASO", json!(0.5)),
("DIMASO", json!("two")),
("DIMASO", Value::Null),
// Text a program or a routine passes is refused even when it spells a number.
("REGENMODE", json!("0")),
("TEXTEVAL", json!("1")),
("DIMASO", json!("0")),
("TEXTEVAL", json!(true)),
] {
let before = getvar(&mut s, name);
assert!(!setvar(&mut s, name, v.clone()), "{name} = {v} refused");
assert_eq!(getvar(&mut s, name), before, "{name} unchanged by {v}");
}
// The drawing's associativity is untouched by a refused DIMASO.
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(!setvar(&mut s, "DIMASO", json!(3)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1));
// The same through LISP, where nil and a NaN real arrive as values a variable can't take.
assert!(!lisp_setvar(&mut s, "REGENMODE", "nil"), "nil refused");
assert!(!lisp_setvar(&mut s, "DIMASO", "3"), "DIMASO 3 refused");
assert!(!lisp_setvar(&mut s, "DIMASO", "\"two\""), "DIMASO text refused");
for (name, v) in [("DIMASO", "\"0\""), ("TEXTEVAL", "\"1\""), ("REGENMODE", "\"0\"")] {
assert!(!lisp_setvar(&mut s, name, v), "{name} text {v} refused");
}
assert!(!lisp_setvar(&mut s, "TEXTEVAL", "-1"), "TEXTEVAL -1 refused");
// (- (exp 1000) (exp 1000)) is NaN: not a number JSON can hold, so it is refused as one.
assert!(!lisp_setvar(&mut s, "TEXTEVAL", "(- (exp 1000) (exp 1000))"), "NaN refused");
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(0));
}
#[test]
fn popups_is_read_only() {
let mut s = Session::new();
assert!(cadcraft_engine::sysvars::is_read_only("popups"));
for v in [json!(1), json!(0), json!("1")] {
let e = s.execute("setvar", &json!({ "name": "POPUPS", "value": v })).unwrap_err().to_string();
assert!(e.contains("read-only"), "{v}: {e}");
}
assert!(!lisp_setvar(&mut s, "POPUPS", "0"));
assert_eq!(getvar(&mut s, "POPUPS"), json!(1));
}
#[test]
fn regenmode_is_saved_in_the_dxf_header_and_read_back() {
let mut s = Session::new();
assert!(setvar(&mut s, "REGENMODE", json!(0)));
let text = cadcraft_io::write_dxf(s.doc().unwrap());
assert!(header_names(&text).contains(&"REGENMODE".to_string()), "$REGENMODE is in the header (has {:?})", header_names(&text));
assert_eq!(header_int(&text, "REGENMODE"), Some((70, "0".to_string())), "$REGENMODE is group 70, 0");
// A reopened drawing has the value it was saved with, and saves it back.
let mut back = Session::new();
back.open_drawing(cadcraft_io::read_dxf(text.as_bytes()).unwrap(), "regenmode.dxf", None);
assert_eq!(getvar(&mut back, "REGENMODE"), json!(0));
let again = cadcraft_io::write_dxf(back.doc().unwrap());
assert_eq!(header_int(&again, "REGENMODE"), Some((70, "0".to_string())));
}
#[test]
fn texteval_dimaso_and_popups_are_not_saved() {
let mut s = Session::new();
assert!(setvar(&mut s, "TEXTEVAL", json!(1)));
let text = cadcraft_io::write_dxf(s.doc().unwrap());
let names = header_names(&text);
for name in ["TEXTEVAL", "DIMASO", "POPUPS"] {
assert!(!names.contains(&name.to_string()), "{name} is not a header variable (has {names:?})");
}
// TEXTEVAL is the session's: a drawing opened in this session does not bring its own value.
s.open_drawing(cadcraft_io::read_dxf(text.as_bytes()).unwrap(), "no_legacy_vars.dxf", None);
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(1), "opening a drawing leaves the session's value");
}
#[test]
fn dimaso_remembers_the_mode_of_each_open_drawing() {
// The mode DIMASO turns off is the drawing's, not the session's: two open drawings switched
// between each put back the DIMASSOC mode they had.
let mut s = Session::new();
let first = s.active;
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(setvar(&mut s, "DIMASO", json!(0)));
let second = s.new_drawing(true);
assert_eq!(second, first + 1);
assert!(setvar(&mut s, "DIMASSOC", json!(2)));
assert!(setvar(&mut s, "DIMASO", json!(0)));
s.execute("document.switch", &json!({ "index": first })).unwrap();
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "the first drawing restores its own mode");
s.execute("document.switch", &json!({ "index": second })).unwrap();
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2), "the second drawing restores its own mode");
}
#[test]
fn the_dollar_forms_are_the_same_variables() {
// The DXF header writes these names with a `$` ($DIMASO, $TEXTEVAL, $REGENMODE, $POPUPS), so
// the command line takes them that way too, in any case and with spaces around them.
let mut s = Session::new();
for name in ["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"] {
let plain = getvar(&mut s, name);
let dollar = format!("${name}");
assert_eq!(getvar(&mut s, &dollar), plain, "{dollar} reads like {name}");
let typed = format!(" ${} ", name.to_ascii_lowercase());
assert_eq!(getvar(&mut s, &typed), plain, "{typed:?} reads like {name}");
assert_eq!(cadcraft_engine::sysvars::is_read_only(&dollar), cadcraft_engine::sysvars::is_read_only(name), "{dollar} read-only as {name}");
}
// DIMASO through its DXF name still turns DIMASSOC off and puts its mode back.
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(setvar(&mut s, "$DIMASO", json!(0)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "$DIMASO 0 turns associativity off");
assert!(setvar(&mut s, " $dimaso ", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "$DIMASO 1 puts the mode back");
// TEXTEVAL: set under one name, read under the other.
assert!(setvar(&mut s, "$TEXTEVAL", json!(1)));
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(1), "$TEXTEVAL set TEXTEVAL");
assert!(setvar(&mut s, "TEXTEVAL", json!(0)));
assert_eq!(getvar(&mut s, "$TEXTEVAL"), json!(0));
// REGENMODE takes only the values its plain name takes, and stores the ones it takes.
assert!(!setvar(&mut s, "$REGENMODE", json!(2)), "$REGENMODE 2 is out of range");
assert_eq!(getvar(&mut s, "REGENMODE"), json!(1), "a refused $REGENMODE changed nothing");
assert!(!setvar(&mut s, "$REGENMODE", json!(-1)), "$REGENMODE -1 is out of range");
assert!(setvar(&mut s, "$REGENMODE", json!(0)));
assert_eq!(getvar(&mut s, "$REGENMODE"), json!(0));
assert_eq!(getvar(&mut s, "REGENMODE"), json!(0));
assert_eq!(s.doc().unwrap().header.i64("REGENMODE", 1), 0, "$REGENMODE stored the drawing's value");
// POPUPS is read-only under its DXF name too.
for v in [json!(0), json!("1")] {
let e = s.execute("setvar", &json!({ "name": "$POPUPS", "value": v })).unwrap_err().to_string();
assert!(e.contains("read-only"), "$POPUPS {v}: {e}");
}
assert!(!lisp_setvar(&mut s, "$POPUPS", "0"));
assert_eq!(getvar(&mut s, "$POPUPS"), json!(1));
}
#[test]
fn other_dollar_names_keep_their_own_handling() {
// Only those four take a `$`: LISP's angle variables convert radians for the plain name, and
// `$OSMODE` stays a name of its own rather than becoming the session's OSMODE.
let mut s = Session::new();
assert!(eval(&mut s, "(setvar \"$ANGBASE\" (/ pi 2))").is_ok());
let base = eval(&mut s, "(getvar \"$ANGBASE\")").unwrap().as_number().unwrap_or(f64::NAN);
assert!((base - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "(getvar \"$ANGBASE\") gives pi/2, not {base}");
let osmode = eval(&mut s, "(setvar \"$OSMODE\" 9)").unwrap();
assert_eq!(to_text(&osmode, true), "9", "(setvar \"$OSMODE\" 9) returns 9");
assert_eq!(getvar(&mut s, "OSMODE"), json!(4133), "$OSMODE is not the session's OSMODE");
assert_eq!(getvar(&mut s, "$OSMODE"), json!(9), "$OSMODE still reads back what it was set to");
}
#[test]
fn undo_puts_back_the_mode_dimaso_remembers() {
// The mode DIMASO remembers goes back with DIMASSOC when the changes are undone.
let mut s = Session::new();
for (name, v) in [("DIMASSOC", 1), ("DIMASO", 0), ("DIMASSOC", 2), ("DIMASO", 0)] {
assert!(setvar(&mut s, name, json!(v)), "{name} {v}");
}
s.cmdline("u").unwrap();
s.cmdline("u").unwrap();
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "back to after the first DIMASO 0");
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "the mode remembered then, not the later 2");
}
#[test]
fn repeated_dollars_are_the_same_variables() {
let mut s = Session::new();
assert!(!lisp_setvar(&mut s, "$$REGENMODE", "2"), "out of range under any number of $");
assert_eq!(getvar(&mut s, "REGENMODE"), json!(1), "a refused $$REGENMODE changed nothing");
assert!(!setvar(&mut s, "$$$POPUPS", json!(0)), "read-only under any number of $");
assert!(cadcraft_engine::sysvars::is_read_only("$$POPUPS"));
}
#[test]
fn dimaso_on_while_already_on_leaves_the_drawing_unmodified() {
let mut s = Session::new();
assert_eq!(getvar(&mut s, "DBMOD"), json!(0), "a fresh drawing");
assert!(setvar(&mut s, "DIMASO", json!(1)), "already on");
assert_eq!(getvar(&mut s, "DBMOD"), json!(0), "nothing changed, so not modified");
}
#[test]
fn the_remembered_mode_is_not_a_variable_and_is_not_reported_lost() {
let mut s = Session::new();
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(setvar(&mut s, "DIMASO", json!(0)));
for name in ["CADCRAFT_DIMASO_MODE", "$CADCRAFT_DIMASO_MODE", "cadcraft_dimaso_mode"] {
assert!(s.execute("getvar", &json!({ "name": name })).is_err(), "{name} is not a variable");
assert!(!setvar(&mut s, name, json!(2)), "{name} cannot be set");
}
assert!(eval(&mut s, "(getvar \"CADCRAFT_DIMASO_MODE\")").map_or(true, |v| to_text(&v, false) == "nil"));
// Saved and read back, the drawing has lost nothing a save keeps.
let before = s.doc().unwrap().clone();
let after = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&before).as_bytes()).unwrap();
let cmp = cadcraft_io::roundtrip::compare(&before, &after, &cadcraft_io::roundtrip::Options::default());
assert!(!cmp.differences.iter().any(|d| d.place.contains("DIMASO")), "{:?}", cmp.differences.iter().map(|d| &d.place).collect::<Vec<_>>());
}
@@ -6,8 +6,7 @@ use cadcraft_engine::Session;
use cadcraft_engine::doc::{EntityKind, Hatch};
use serde_json::json;
#[path = "support/temp_dir.rs"]
mod temp_dir;
use crate::temp_dir;
use temp_dir::TempDir;
+1 -1
View File
@@ -23,7 +23,7 @@ fn groups(d: &cadcraft_engine::doc::Drawing, e: &Entity) -> (String, Vec<(i32, V
.into_iter()
.map(|t| {
let v = match t.value {
craft_dxf::Value::Str(s) | craft_dxf::Value::Hex(s) => json!(s),
craft_dxf::Value::Str(s) | craft_dxf::Value::Hex(s) | craft_dxf::Value::Invalid(s) => json!(s),
craft_dxf::Value::Real(r) => json!(r),
craft_dxf::Value::Int(i) => json!(i),
craft_dxf::Value::Bool(b) => json!(i32::from(b)),
+34
View File
@@ -1,10 +1,13 @@
#[path = "../support/temp_dir.rs"]
mod temp_dir;
mod acadver;
mod aliases;
mod angle_prompts;
mod angle_settings;
mod annotate_options;
mod annotative;
mod annotative_positions;
mod arc_ctrl_direction;
mod array_commands;
mod array_counts;
@@ -12,6 +15,7 @@ mod array_key_point;
mod array_live;
mod assoc_array;
mod attdef_command;
mod attdef_justify_style;
mod attdisp_attsync;
mod attedit_prompts;
mod attrib_modes;
@@ -20,6 +24,7 @@ mod attrib_props;
mod attribute_tag_matching;
mod attribute_tools;
mod attribute_value_baseline;
mod base64_compat;
mod block_description;
mod block_keep;
mod block_redefine;
@@ -31,6 +36,7 @@ mod break_keeps_z;
mod break_trim_keep_handle;
mod break_trim_polyline_rules;
mod breakatpoint_command_line;
mod bsaveas_source;
mod burst;
mod change_command;
mod chprop_command;
@@ -48,18 +54,23 @@ mod dim_baseline_spacing;
mod dim_block_text_layer_pick;
mod dim_chain;
mod dim_commands;
mod dim_diameter_sign;
mod dim_explode_text;
mod dim_nested_circle;
mod dim_properties;
mod dim_radial_inside;
mod dim_radial_outside;
mod dim_style_menu;
mod dim_text_frame;
mod dim_vars;
mod dimassoc_mode;
mod dimassoc_saved;
mod dimstyle_cli;
mod dimtedit_prompts;
mod drafting_spacing;
mod draw_prompts;
mod draworder;
mod dview;
mod dyn_input;
mod dynamic_block_data;
mod dynamic_grips;
@@ -71,6 +82,7 @@ mod fillet_chamfer;
mod fix_holds_grips;
mod followups_626;
mod greek_keyboard;
mod greek_keyboard_aliases;
mod grip_dim_input;
mod grip_options;
mod grip_selection;
@@ -98,24 +110,30 @@ mod json_param_validation;
mod kept_dimension_snaps;
mod layer_cmdline;
mod layer_merge_delete;
mod layer_name_control_chars;
mod layer_state_cmdline;
mod layoff_repeat;
mod layout_prompts;
mod leader_command;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod leader_text_scale;
mod legacy_sysvars;
mod lin_pat_files;
mod lisp_answer_by_frames;
mod lisp_corpus;
mod lisp_findfile;
mod lisp_getangle_inputs;
mod lisp_textbox;
mod lisp_undo_in_routine;
mod loops;
mod malformed_handles;
mod matchprop;
mod measure_distance_snapping;
mod measureinit;
mod metric_linetypes;
mod minsert;
mod mirror_degenerate_line;
mod mirror_hatch_direction;
mod mleader_content;
mod mleader_remember;
mod mleader_text_edit;
@@ -133,6 +151,8 @@ mod non_finite_edits;
mod offset_closed_spline;
mod offset_ellipse_side;
mod offset_move;
mod offset_preselection;
mod ole_frame_transform;
mod oops_command;
mod options_profile;
mod osnap_opened_drawings;
@@ -155,6 +175,7 @@ mod properties_set_locked;
mod properties_set_text_dims;
mod props_bad_lineweight;
mod props_insert_scale_attribs;
mod purge_arrow_blocks;
mod purge_kept_dimension_blocks;
mod purge_mlinestyles;
mod purge_prompts;
@@ -171,14 +192,18 @@ mod refedit;
mod refedit_xref;
mod region;
mod rename_cmdline;
mod rename_keeps_extras;
mod revcloud_recognised;
mod rotate_reference;
mod rotation_grip_input;
#[cfg(not(target_arch = "wasm32"))]
mod save_changed_on_disk;
mod scale_offset_z;
mod scale_zero_factor;
mod select_keywords;
mod select_similar;
mod select_underscore_keywords;
mod selection_anno_display;
mod selection_cycling;
mod selection_modes;
mod setvar_cecolor;
@@ -201,7 +226,9 @@ mod spline_degree;
mod spline_options;
mod stretch;
mod stretch_select;
mod stretch_window_ortho;
mod table_formulas;
mod table_malformed_handle;
mod table_styles;
mod temp_tracking;
mod text_commands;
@@ -212,18 +239,25 @@ mod transparent;
mod trim_closed_polyline;
mod trim_cut_at_the_pick;
mod trim_cut_where_an_arc_span_starts;
mod trim_extend_block_edges;
mod trim_extend_json_pick;
mod trim_extend_options;
mod trim_highlight;
mod trim_keeps_z_and_width;
mod ucs;
mod ucs_drafting;
mod undo_count;
mod undo_layout_tab;
mod units_bearing;
mod usage;
mod view_twist;
mod viewport_clip;
mod viewport_frozen_block_parts;
mod viewport_frozen_selection;
mod viewport_ucs_copy;
mod vplayer_prompts;
mod vports;
mod wblock_pick;
mod window_rotated_text;
mod wipeout_grips;
mod xclip;
+3 -1
View File
@@ -11,7 +11,9 @@ use cadcraft_engine::doc::{Block, Circle, Drawing, Entity, EntityKind, Handle, I
use cadcraft_engine::{Input, Session};
use serde_json::{Value, json};
fn hooks() {
/// The real file formats, for every test in this binary that opens or saves files (the hooks are
/// process-wide and the first ones set stay).
pub(crate) fn hooks() {
set_io(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()),
@@ -23,7 +23,7 @@ fn session() -> Session {
let layer = "0 TABLE\n2 LAYER\n5 2\n330 0\n100 AcDbSymbolTable\n70 1\n\
0 LAYER\n5 10\n330 2\n100 AcDbSymbolTableRecord\n100 AcDbLayerTableRecord\n2 Walls\n70 0\n62 3\n6 Continuous\n\
1001 ACME_TAGS\n1000 W-01\n1070 7\n0 ENDTAB\n";
let src = include_str!("../../io/tests/data/dynblock_door.txt").replace("\r\n", "\n").replacen(
let src = include_str!("../../../io/tests/data/dynblock_door.txt").replace("\r\n", "\n").replacen(
"0 TABLE\n2 BLOCK_RECORD\n",
&format!("{layer}0 TABLE\n2 BLOCK_RECORD\n"),
1,
@@ -0,0 +1,143 @@
//! A save over the drawing's own file refuses when another program changed the file after it was
//! opened or last saved here (CADCraft keeps no file open, so nothing else would stop it), and
//! `overwrite: true` replaces it anyway. The hooks are the same `cadcraft_io` ones the other
//! modules of this harness install.
use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, set_io};
use serde_json::json;
fn hooks() {
set_io(IoHooks {
read: |b, n| cadcraft_io::read(b, n).map_err(|e| e.to_string()),
write: |d, n| cadcraft_io::write(d, n).map_err(|e| e.to_string()),
plot: None,
});
}
fn folder(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("cadcraft-disk-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn add_circle(s: &mut Session, x: f64) {
s.execute("circle", &json!({ "center": [x, 0], "radius": 1 })).unwrap();
}
#[test]
fn qsave_refuses_a_file_someone_else_saved_and_overwrite_replaces_it() {
hooks();
let dir = folder("qsave");
let file = dir.join("plan.dxf");
let path = file.to_string_lossy().to_string();
let mut s = Session::new();
add_circle(&mut s, 0.0);
s.execute("saveas", &json!({ "path": path })).unwrap();
// Untouched on disk: saves go through, each compared with what the one before wrote.
add_circle(&mut s, 5.0);
s.execute("qsave", &json!({})).unwrap();
add_circle(&mut s, 10.0);
s.execute("qsave", &json!({})).unwrap();
// Another program saves the same file, here with the same length.
let mut theirs = std::fs::read(&file).unwrap();
let last = theirs.len() - 1;
theirs[last] ^= 0x20;
std::fs::write(&file, &theirs).unwrap();
add_circle(&mut s, 15.0);
let e = s.execute("qsave", &json!({})).unwrap_err().to_string();
assert!(e.contains("changed on disk"), "{e}");
assert_eq!(std::fs::read(&file).unwrap(), theirs, "their work stays");
assert!(s.state().unwrap().is_dirty(), "the drawing still has its unsaved changes");
assert!(s.execute("saveas", &json!({ "path": path })).is_err(), "SAVEAS onto its own file checks too");
let spelled = dir.join(".").join("plan.dxf").to_string_lossy().to_string();
assert!(s.execute("saveas", &json!({ "path": spelled })).is_err(), "the same file under another spelling");
// A copy under another name is always possible, and leaves their file alone.
let copy = dir.join("plan-mine.dxf").to_string_lossy().to_string();
s.execute("saveas", &json!({ "path": copy })).unwrap();
assert_eq!(std::fs::read(&file).unwrap(), theirs);
s.execute("qsave", &json!({})).unwrap();
// Back onto the original with overwrite: replaced on purpose.
s.execute("saveas", &json!({ "path": path, "overwrite": true })).unwrap();
assert_ne!(std::fs::read(&file).unwrap(), theirs);
assert!(s.execute("qsave", &json!({ "overwrite": "yes" })).is_err(), "overwrite must be a bool");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_file_opened_and_changed_elsewhere_is_not_saved_over() {
hooks();
let dir = folder("open");
let file = dir.join("plan.dxf");
let path = file.to_string_lossy().to_string();
let mut first = Session::new();
add_circle(&mut first, 0.0);
first.execute("saveas", &json!({ "path": path })).unwrap();
// Two sessions open the same file; the first saves, then the second tries to.
let mut second = Session::new();
second.execute("open", &json!({ "path": path })).unwrap();
first.execute("open", &json!({ "path": path })).unwrap();
add_circle(&mut first, 5.0);
first.execute("qsave", &json!({})).unwrap();
let saved_by_first = std::fs::read(&file).unwrap();
add_circle(&mut second, 10.0);
let e = second.execute("qsave", &json!({})).unwrap_err().to_string();
assert!(e.contains("changed on disk"), "{e}");
assert_eq!(std::fs::read(&file).unwrap(), saved_by_first, "the first session's save stays");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_deleted_file_or_a_drawing_never_saved_has_nothing_to_check() {
hooks();
let dir = folder("gone");
let file = dir.join("plan.dxf");
let path = file.to_string_lossy().to_string();
let mut s = Session::new();
add_circle(&mut s, 0.0);
s.execute("saveas", &json!({ "path": path })).unwrap();
std::fs::remove_file(&file).unwrap();
add_circle(&mut s, 5.0);
s.execute("qsave", &json!({})).unwrap();
assert!(file.exists());
// A drawing that never came from this file has nothing to compare: SAVEAS over it behaves as before.
let mut fresh = Session::new();
add_circle(&mut fresh, 0.0);
fresh.execute("saveas", &json!({ "path": path })).unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// With automation roots in force, a save outside the write root is refused by the roots before
/// the file there is compared: the answer says nothing about a file the agent may not reach.
#[test]
fn outside_the_write_root_the_roots_refuse_before_the_file_is_compared() {
hooks();
let dir = folder("roots");
let inside = dir.join("in");
let outside = dir.join("out");
std::fs::create_dir_all(&inside).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let file = outside.join("plan.dxf");
let path = file.to_string_lossy().to_string();
let mut s = Session::new();
add_circle(&mut s, 0.0);
s.execute("saveas", &json!({ "path": path })).unwrap();
let mut theirs = std::fs::read(&file).unwrap();
let last = theirs.len() - 1;
theirs[last] ^= 0x20;
std::fs::write(&file, &theirs).unwrap();
add_circle(&mut s, 5.0);
let roots = cadcraft_engine::file_access::AutomationRoots::new(Some(&inside), Some(&inside)).unwrap();
let e = cadcraft_engine::file_access::confine(roots.as_ref(), || s.execute("qsave", &json!({}))).unwrap_err().to_string();
assert!(e.contains("automation path rejected") && !e.contains("changed on disk"), "{e}");
assert_eq!(std::fs::read(&file).unwrap(), theirs);
let _ = std::fs::remove_dir_all(&dir);
}
@@ -0,0 +1,141 @@
//! A selected annotative object also shows at its other scales, faded (SELECTIONANNODISPLAY):
//! each at that scale's size and position. Grips stay on the current scale's representation.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{AnnoScale, Entity, EntityKind, Handle};
use cadcraft_engine::geom::Vec2;
use serde_json::{Value, json};
fn setvar(s: &mut Session, name: &str, value: Value) {
s.execute("setvar", &json!({ "name": name, "value": value })).unwrap();
}
fn getvar(s: &mut Session, name: &str) -> Value {
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
}
fn handle(r: &Value) -> Handle {
r["handle"].as_str().or_else(|| r["handles"][0].as_str()).and_then(Handle::parse_hex).unwrap()
}
fn entity(s: &Session, h: Handle) -> Entity {
(**s.doc().unwrap().entity(h).unwrap()).clone()
}
fn near(a: Vec2, b: Vec2) -> bool {
a.dist(b) < 1e-9
}
/// An annotative multileader supporting 1:1 and 1:10, its landing moved (2, 1) at 1:10, with
/// 1:1 current again. Returns it as it shows at 1:10.
fn moved_at_one_to_ten() -> (Session, Handle, Entity) {
let mut s = Session::new();
s.execute("mleaderstyle", &json!({ "name": "Anno", "annotative": true })).unwrap();
let h = handle(&s.execute("mleader", &json!({ "points": [[0, 0], [5, 5]], "text": "A" })).unwrap());
setvar(&mut s, "CANNOSCALE", json!("1:10"));
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:10" })).unwrap();
let EntityKind::MLeader(m) = entity(&s, h).kind else { panic!() };
let landing = m.leaders.iter().map(Vec::len).sum::<usize>();
let to = m.landing.xy() + Vec2::new(2.0, 1.0);
s.execute("grip.move", &json!({ "handle": h.hex(), "index": landing, "to": [to.x, to.y] })).unwrap();
let d = s.doc().unwrap();
let e = d.entity(h).unwrap();
let at_ten = Entity { kind: d.anno_shown(e), ..(**e).clone() };
setvar(&mut s, "CANNOSCALE", json!("1:1"));
(s, h, at_ten)
}
#[test]
fn a_selected_multileader_shows_its_other_scale_where_it_was_moved() {
let (mut s, h, at_ten) = moved_at_one_to_ten();
assert_eq!(getvar(&mut s, "SELECTIONANNODISPLAY"), json!(1), "on by default");
assert!(s.selection_anno_others().is_empty(), "nothing selected");
s.set_selection(vec![h]);
let others = s.selection_anno_others();
assert_eq!(others.len(), 1, "one other scale");
let (EntityKind::MLeader(other), EntityKind::MLeader(ten)) = (&others[0].kind, &at_ten.kind) else { panic!() };
assert!(near(other.landing.xy(), ten.landing.xy()), "at 1:10's position");
assert_eq!(other, ten, "at 1:10's size too");
assert!(others[0].common.anno_scales.is_empty(), "drawn as it is");
// The grips stay on the 1:1 representation.
let EntityKind::MLeader(m) = entity(&s, h).kind else { panic!() };
let grips = s.grips_of(h).unwrap();
assert!(grips.iter().any(|g| near(*g, m.landing.xy())));
assert!(!grips.iter().any(|g| near(*g, ten.landing.xy())));
// At 1:10 the other one is 1:1's, where it was.
setvar(&mut s, "CANNOSCALE", json!("1:10"));
let others = s.selection_anno_others();
let [EntityKind::MLeader(one)] = others.iter().map(|e| &e.kind).collect::<Vec<_>>()[..] else { panic!() };
assert!(near(one.landing.xy(), m.landing.xy()));
}
#[test]
fn selectionannodisplay_0_shows_no_other_scale() {
let (mut s, h, _) = moved_at_one_to_ten();
s.set_selection(vec![h]);
s.execute("setvar", &json!({ "name": "SELECTIONANNODISPLAY", "value": 2 })).unwrap_err();
s.execute("setvar", &json!({ "name": "SELECTIONANNODISPLAY", "value": "x" })).unwrap_err();
assert_eq!(getvar(&mut s, "SELECTIONANNODISPLAY"), json!(1), "a refused value changes nothing");
setvar(&mut s, "SELECTIONANNODISPLAY", json!(0));
assert!(s.selection_anno_others().is_empty());
s.cmdline("SELECTIONANNODISPLAY 1").unwrap();
assert_eq!(s.selection_anno_others().len(), 1, "typed at the command line");
}
#[test]
fn a_single_scale_or_plain_object_shows_nothing_more() {
let mut s = Session::new();
s.execute("mleaderstyle", &json!({ "name": "Anno", "annotative": true })).unwrap();
let one = handle(&s.execute("mleader", &json!({ "points": [[0, 0], [5, 5]], "text": "A" })).unwrap());
let line = handle(&s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap());
s.set_selection(vec![one, line]);
assert_eq!(entity(&s, one).common.anno_scales.len(), 1);
assert!(s.selection_anno_others().is_empty());
}
#[test]
fn hostile_scales_give_bounded_representations() {
let (s, h, _) = moved_at_one_to_ten();
let mut e = entity(&s, h);
// Invalid ratios are skipped; the same ratio under many names comes once; the list is capped.
e.common.anno_scales.push(AnnoScale::new("nan", f64::NAN, 1.0));
e.common.anno_scales.push(AnnoScale::new("zero", 0.0, 1.0));
e.common.anno_scales.push(AnnoScale::new("inf", 1.0, f64::INFINITY));
e.common.anno_scales.push(AnnoScale::new("huge", 1e-308, 1e308));
for i in 0..5000 {
e.common.anno_scales.push(AnnoScale::new(&format!("dup{i}"), 1.0, 10.0));
}
let mut unlimited = usize::MAX;
for view in [1.0, 10.0, f64::NAN, -1.0, 0.0, f64::INFINITY] {
let others = cadcraft_engine::doc::anno_others(&e, view, true, &mut unlimited);
assert!(others.len() <= 2, "{view}: {}", others.len());
}
assert!(cadcraft_engine::doc::anno_others(&e, 3.0, false, &mut unlimited).is_empty(), "not shown in that view");
}
#[test]
fn a_selection_shares_one_budget_of_faded_representations() {
let (mut s, h, _) = moved_at_one_to_ten();
// An object supporting many distinct scales: each gives a representation.
let mut e = entity(&s, h);
for i in 2..300 {
e.common.anno_scales.push(AnnoScale::new(&format!("1:{i}"), 1.0, f64::from(i)));
}
let mut unlimited = usize::MAX;
let many = cadcraft_engine::doc::anno_others(&e, 1.0, true, &mut unlimited).len();
assert!(many > 200, "{many}");
// A small budget stops it, used up, and the next object gets none.
let mut budget = 5;
assert_eq!(cadcraft_engine::doc::anno_others(&e, 1.0, true, &mut budget).len(), 5);
assert_eq!(budget, 0);
assert!(cadcraft_engine::doc::anno_others(&e, 1.0, true, &mut budget).is_empty());
// Ten such objects selected: the selection's representations stay within the shared budget,
// fewer than the objects would make one by one.
let mut hs = Vec::new();
for _ in 0..10 {
hs.push(s.doc_mut().unwrap().add(&cadcraft_engine::doc::Space::Model, e.common.clone(), e.kind.clone()).unwrap());
}
s.set_selection(hs.clone());
let shown = s.selection_anno_others().len();
assert!(shown <= cadcraft_engine::MAX_ANNO_FADED && shown < many * hs.len(), "{shown}");
}
+24
View File
@@ -47,3 +47,27 @@ fn transparent_zoom_resumes_the_running_command() {
assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("line"));
assert!(s.suspended.is_none());
}
/// #3273 review: GETVAR typed transparently inside LINE reads the command state LINE is in, and
/// LINE then carries on.
#[test]
fn transparent_getvar_sees_the_command_it_runs_inside() {
let mut s = Session::new();
s.cmdline("LINE 0,0").unwrap();
s.cmdline("'GETVAR CMDNAMES").unwrap();
// The value, then LINE resuming.
let tail = |s: &Session| s.log[s.log.len().saturating_sub(2)..].to_vec();
assert_eq!(tail(&s), ["CMDNAMES = LINE", "Resuming LINE command."]);
s.cmdline("'GETVAR CMDACTIVE").unwrap();
assert_eq!(tail(&s), ["CMDACTIVE = 3", "Resuming LINE command."], "a command, and a transparent one in it");
// A transparent command still prompting is named after the one it runs inside.
s.cmdline("'PAN").unwrap();
assert_eq!(cadcraft_engine::sysvars::get(&s, "CMDNAMES"), Some(serde_json::json!("LINE'PAN")));
s.cmdline("").unwrap();
assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("line"), "{}", s.prompt_text());
s.cmdline("10,0").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none());
assert_eq!(lines(&s), 1);
assert_eq!(cadcraft_engine::sysvars::get(&s, "CMDACTIVE"), Some(serde_json::json!(0)));
}
@@ -0,0 +1,594 @@
//! #3569: TRIM and EXTEND take what a block reference draws as cutting and boundary edges: the
//! objects inside it, placed by the reference (insertion point, scale, rotation), nested
//! references too, and only the objects that are drawn.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Block, Entity, EntityKind, Handle, Line};
use cadcraft_engine::geom::{Vec2, Vec3};
use serde_json::{Value, json};
/// The object a command made: its `handle`, or the first of its `handles`.
fn made(v: &Value) -> Handle {
let hex = v["handle"].as_str().or_else(|| v["handles"][0].as_str()).unwrap_or_else(|| panic!("{v}"));
Handle::parse_hex(hex).unwrap()
}
/// Draws a line from `a` to `b`.
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle {
made(&s.execute("line", &json!({ "points": [a, b] })).unwrap())
}
/// Makes block `name` (base point at the origin) of the objects `parts`, which leave the drawing.
fn block(s: &mut Session, name: &str, parts: &[Handle]) {
let handles: Vec<String> = parts.iter().map(|h| h.hex()).collect();
s.execute("block", &json!({ "name": name, "base": [0, 0], "handles": handles, "keep": "delete" })).unwrap();
}
/// Inserts block `name` at `at`, scaled by `scale` along its axes and turned by `rotation` degrees.
fn reference(s: &mut Session, name: &str, at: [f64; 2], scale: [f64; 2], rotation: f64) -> Handle {
made(&s.execute("insert", &json!({ "name": name, "at": at, "scale": scale, "rotation": rotation })).unwrap())
}
/// Puts `h` on layer `name`.
fn on_layer(s: &mut Session, h: Handle, name: &str) {
s.execute("properties.set", &json!({ "handles": [h.hex()], "layer": name })).unwrap();
}
/// The ends of line `h`.
fn ends(s: &Session, h: Handle) -> (Vec2, Vec2) {
match &s.doc().unwrap().entity(h).unwrap().kind {
EntityKind::Line(l) => (l.a.xy(), l.b.xy()),
k => panic!("{h:?} is not a line: {k:?}"),
}
}
/// Asserts that line `h` runs from `a` to `b`.
fn assert_ends(s: &Session, h: Handle, a: [f64; 2], b: [f64; 2]) {
let (p, q) = ends(s, h);
assert!(p.near(Vec2::new(a[0], a[1]), 1e-9) && q.near(Vec2::new(b[0], b[1]), 1e-9), "{p:?} to {q:?}, expected {a:?} to {b:?}");
}
/// A drawing with block "B" holding the vertical line x = 50, referenced once at (20, 5), which
/// draws it at x = 70 across the X axis. Returns the reference.
fn one_reference() -> (Session, Handle) {
let mut s = Session::new();
let part = line(&mut s, [50.0, -10.0], [50.0, 10.0]);
block(&mut s, "B", &[part]);
let r = reference(&mut s, "B", [20.0, 5.0], [1.0, 1.0], 0.0);
(s, r)
}
/// TRIM with a block reference as its only cutting edge cuts at the line the reference draws.
#[test]
fn trim_cuts_at_a_line_a_reference_draws() {
let (mut s, r) = one_reference();
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [90, 0], "edges": [r.hex()] })).unwrap();
assert_ends(&s, l, [0.0, 0.0], [70.0, 0.0]);
}
/// With no edges named every object is an edge, and a block reference is one of them.
#[test]
fn trim_with_every_object_an_edge_counts_references() {
let (mut s, _) = one_reference();
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [90, 0] })).unwrap();
assert_ends(&s, l, [0.0, 0.0], [70.0, 0.0]);
}
/// EXTEND reaches the line a block reference draws, with the reference named as the boundary
/// and with every object a boundary.
#[test]
fn extend_reaches_a_line_a_reference_draws() {
for edges in [true, false] {
let (mut s, r) = one_reference();
let l = line(&mut s, [0.0, 0.0], [30.0, 0.0]);
let mut p = json!({ "handle": l.hex(), "pick": [29, 0] });
if edges {
p["edges"] = json!([r.hex()]);
}
s.execute("extend", &p).unwrap();
assert_ends(&s, l, [0.0, 0.0], [70.0, 0.0]);
}
}
/// A line two references deep is an edge where both references put it: their offsets and
/// scales compose.
#[test]
fn a_nested_reference_is_placed_by_every_reference_above_it() {
let mut s = Session::new();
let part = line(&mut s, [50.0, -10.0], [50.0, 10.0]);
block(&mut s, "INNER", &[part]);
let inner = reference(&mut s, "INNER", [10.0, 0.0], [1.0, 1.0], 0.0);
block(&mut s, "OUTER", &[inner]);
// The line is at x = 50 in INNER, 60 in OUTER and, OUTER being twice as large along X, 125 here.
let r = reference(&mut s, "OUTER", [5.0, 0.0], [2.0, 1.0], 0.0);
let l = line(&mut s, [0.0, 0.0], [200.0, 0.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [190, 0], "edges": [r.hex()] })).unwrap();
assert_ends(&s, l, [0.0, 0.0], [125.0, 0.0]);
}
/// Rotation, uneven scale and mirroring together still put the edge where the reference draws
/// it, and a line the edge does not reach is not cut.
#[test]
fn a_turned_stretched_and_mirrored_reference_cuts_where_it_draws() {
let mut s = Session::new();
// x = 10 for y in -10..2. Scaled by (3, -2): x = 30 for y in -4..20. Turned a quarter turn:
// y = 30 for x in -20..4. Moved to (40, 0): y = 30 for x in 20..44.
let part = line(&mut s, [10.0, -10.0], [10.0, 2.0]);
block(&mut s, "B", &[part]);
let r = reference(&mut s, "B", [40.0, 0.0], [3.0, -2.0], 90.0);
// x = 25 is crossed only by the mirrored line: unmirrored it would span x in 36..60.
let l = line(&mut s, [25.0, 0.0], [25.0, 100.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [25, 90], "edges": [r.hex()] })).unwrap();
assert_ends(&s, l, [25.0, 0.0], [25.0, 30.0]);
// An object the line does not reach is not cut by its extension.
let past = line(&mut s, [50.0, 0.0], [50.0, 100.0]);
assert!(s.execute("trim", &json!({ "handle": past.hex(), "pick": [50, 90], "edges": [r.hex()] })).is_err());
assert_ends(&s, past, [50.0, 0.0], [50.0, 100.0]);
}
/// A turned reference, and a turned one with different X and Y scales, cut where they draw the
/// line, for TRIM and for EXTEND, also one level deeper.
#[test]
fn a_turned_and_unevenly_scaled_reference_cuts_where_it_draws() {
// The line x = 10 of the block, scaled along X and turned 30 degrees about the insertion
// point, crosses the horizontal through that point at 10 * scale / cos 30.
let cos30 = 30.0_f64.to_radians().cos();
for (scale, nested) in [([1.0, 1.0], false), ([1.5, 2.0], false), ([1.5, 2.0], true)] {
let mut s = Session::new();
let part = line(&mut s, [10.0, -10.0], [10.0, 10.0]);
block(&mut s, "B", &[part]);
if nested {
let inner = reference(&mut s, "B", [0.0, 0.0], [1.0, 1.0], 0.0);
block(&mut s, "OUTER", &[inner]);
}
let r = reference(&mut s, if nested { "OUTER" } else { "B" }, [0.0, 3.0], scale, 30.0);
let l = line(&mut s, [0.0, 3.0], [40.0, 3.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [39, 3], "edges": [r.hex()] })).unwrap();
assert_ends(&s, l, [0.0, 3.0], [10.0 * scale[0] / cos30, 3.0]);
let short = line(&mut s, [0.0, 3.0], [5.0, 3.0]);
s.execute("extend", &json!({ "handle": short.hex(), "pick": [4, 3], "edges": [r.hex()] })).unwrap();
assert_ends(&s, short, [0.0, 3.0], [10.0 * scale[0] / cos30, 3.0]);
}
}
/// A reference with X scale -1 cuts on the mirrored side of its insertion point.
#[test]
fn a_mirrored_reference_cuts_on_its_mirrored_side() {
let mut s = Session::new();
let part = line(&mut s, [10.0, -10.0], [10.0, 10.0]);
block(&mut s, "B", &[part]);
let r = reference(&mut s, "B", [0.0, 3.0], [-1.0, 1.0], 0.0);
// The only edge is at x = -10: nothing cuts the line at x = 10.
let l = line(&mut s, [-40.0, 3.0], [40.0, 3.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [39, 3], "edges": [r.hex()] })).unwrap();
assert_ends(&s, l, [-40.0, 3.0], [-10.0, 3.0]);
}
/// A circle in a reference with different X and Y scales cuts as the ellipse it is drawn as.
#[test]
fn a_circle_in_an_unevenly_scaled_reference_cuts_as_the_ellipse_it_draws() {
let mut s = Session::new();
let part = made(&s.execute("circle", &json!({ "center": [10, 0], "radius": 5 })).unwrap());
block(&mut s, "B", &[part]);
// Twice as wide along X: the circle is drawn as an ellipse about (10, 3) from x = 0 to 20.
let r = reference(&mut s, "B", [-10.0, 3.0], [2.0, 1.0], 0.0);
let l = line(&mut s, [-20.0, 3.0], [40.0, 3.0]);
let v = s.execute("trim", &json!({ "handle": l.hex(), "pick": [10, 3], "edges": [r.hex()] })).unwrap();
let pieces: Vec<Handle> = v["handles"].as_array().unwrap().iter().map(|h| Handle::parse_hex(h.as_str().unwrap()).unwrap()).collect();
let mut cuts: Vec<f64> = pieces.iter().map(|h| ends(&s, *h)).map(|(a, b)| if a.x.abs() < b.x.abs() { a.x } else { b.x }).collect();
cuts.sort_by(f64::total_cmp);
let [left, right] = cuts.as_slice() else { panic!("{cuts:?}") };
assert!(left.abs() < 0.01 && (right - 20.0).abs() < 0.01, "{cuts:?}");
}
/// A polyline with a width inside a reference is an edge at its centre line, not at its sides.
#[test]
fn a_wide_polyline_in_a_reference_cuts_at_its_centre_line() {
let mut s = Session::new();
let part = made(&s.execute("pline", &json!({ "vertices": [[10, -10], [10, 10]], "width": 2 })).unwrap());
block(&mut s, "B", &[part]);
let r = reference(&mut s, "B", [20.0, 5.0], [1.0, 1.0], 0.0);
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [90, 0], "edges": [r.hex()] })).unwrap();
assert_ends(&s, l, [0.0, 0.0], [30.0, 0.0]);
}
/// A line in a reference that stops short of the object is no edge by default; with edges that
/// run on (EDGEMODE 1) it is one.
#[test]
fn a_part_that_stops_short_is_an_edge_only_when_edges_run_on() {
let mut s = Session::new();
// Drawn from y = 4 up: its extension, not the line, crosses the X axis at x = 10.
let part = line(&mut s, [10.0, 4.0], [10.0, 12.0]);
block(&mut s, "B", &[part]);
let r = reference(&mut s, "B", [0.0, 0.0], [1.0, 1.0], 0.0);
let l = line(&mut s, [0.0, 0.0], [40.0, 0.0]);
let short = line(&mut s, [0.0, -2.0], [5.0, -2.0]);
for edges in [json!([r.hex()]), Value::Null] {
assert!(s.execute("trim", &json!({ "handle": l.hex(), "pick": [39, 0], "edges": edges })).is_err());
assert!(s.execute("extend", &json!({ "handle": short.hex(), "pick": [4, -2], "edges": edges })).is_err());
}
assert_ends(&s, l, [0.0, 0.0], [40.0, 0.0]);
assert_ends(&s, short, [0.0, -2.0], [5.0, -2.0]);
// With edges that run on, it is one, as the same line outside a block is.
s.execute("trim", &json!({ "handle": l.hex(), "pick": [39, 0], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends(&s, l, [0.0, 0.0], [10.0, 0.0]);
s.execute("extend", &json!({ "handle": short.hex(), "pick": [4, -2], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends(&s, short, [0.0, -2.0], [10.0, -2.0]);
}
/// A dimension inside a reference gives no edge, as a dimension outside a block gives none.
#[test]
fn a_dimension_in_a_reference_is_no_more_an_edge_than_outside_one() {
let mut s = Session::new();
let dim = made(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [50, 0], "at": [25, 20] })).unwrap());
// The dimension draws through a block of its own, here one line along y = 20.
let d = s.doc_mut().unwrap();
let mut drawn = Block::new("*D1");
drawn.entities.push(Entity::new(d.new_handle(), EntityKind::Line(Line { a: Vec3::new(0.0, 20.0, 0.0), b: Vec3::new(50.0, 20.0, 0.0) })));
d.blocks.insert("*D1".into(), std::sync::Arc::new(drawn));
d.modify_entity(dim, |e| {
if let EntityKind::Dimension(dm) = &mut e.kind {
dm.block = Some("*D1".into());
}
})
.unwrap();
// Outside a block the dimension cuts nothing, and so it cuts nothing inside a reference.
let l = line(&mut s, [25.0, -10.0], [25.0, 100.0]);
assert!(s.execute("trim", &json!({ "handle": l.hex(), "pick": [25, 90], "edges": [dim.hex()] })).is_err());
block(&mut s, "B", &[dim]);
let r = reference(&mut s, "B", [0.0, 0.0], [1.0, 1.0], 0.0);
assert!(s.execute("trim", &json!({ "handle": l.hex(), "pick": [25, 90], "edges": [r.hex()] })).is_err());
assert_ends(&s, l, [25.0, -10.0], [25.0, 100.0]);
}
/// Parts on a frozen layer, on a layer that is off, and hidden parts are not edges; the drawn
/// part beside them is.
#[test]
fn parts_that_are_not_drawn_are_not_edges() {
let mut s = Session::new();
let frozen = line(&mut s, [30.0, -10.0], [30.0, 10.0]);
on_layer(&mut s, frozen, "FROZEN");
let off = line(&mut s, [40.0, -10.0], [40.0, 10.0]);
on_layer(&mut s, off, "OFF");
let hidden = line(&mut s, [50.0, -10.0], [50.0, 10.0]);
s.doc_mut().unwrap().modify_entity(hidden, |e| e.common.visible = false).unwrap();
let drawn = line(&mut s, [60.0, -10.0], [60.0, 10.0]);
block(&mut s, "B", &[frozen, off, hidden, drawn]);
let d = s.doc_mut().unwrap();
d.layer_mut("FROZEN").unwrap().frozen = true;
d.layer_mut("OFF").unwrap().on = false;
let r = reference(&mut s, "B", [0.0, 0.0], [1.0, 1.0], 0.0);
// Picked at its start, the line loses the stretch up to the first edge: the only drawn part.
for edges in [true, false] {
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
let mut p = json!({ "handle": l.hex(), "pick": [1, 0] });
if edges {
p["edges"] = json!([r.hex()]);
}
s.execute("trim", &p).unwrap();
assert_ends(&s, l, [60.0, 0.0], [100.0, 0.0]);
s.execute("erase", &json!({ "handles": [l.hex()] })).unwrap();
}
}
/// A part on layer 0 follows its reference's layer: the reference on a frozen layer is no edge.
#[test]
fn a_reference_on_a_frozen_layer_is_no_edge() {
let mut s = Session::new();
// The part is on layer 0, so it is drawn on each reference's layer.
let part = line(&mut s, [0.0, -10.0], [0.0, 10.0]);
block(&mut s, "B", &[part]);
let frozen = reference(&mut s, "B", [30.0, 0.0], [1.0, 1.0], 0.0);
on_layer(&mut s, frozen, "FROZEN");
s.doc_mut().unwrap().layer_mut("FROZEN").unwrap().frozen = true;
reference(&mut s, "B", [60.0, 0.0], [1.0, 1.0], 0.0);
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [1, 0] })).unwrap();
assert_ends(&s, l, [60.0, 0.0], [100.0, 0.0]);
}
/// The highlight under the cursor in the running command shows the cut at the reference's line.
#[test]
fn the_rollover_highlight_shows_the_cut_at_a_reference() {
let (mut s, _) = one_reference();
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.zoom_extents().unwrap();
s.start("trim").unwrap();
// Quick mode: every object is an edge. The piece past the reference's line is what goes.
let part = s.highlight(l, Vec2::new(90.0, 0.0)).expect("a part of the line is highlighted");
let outline: Vec<Vec2> = part.iter().flat_map(|e| cadcraft_engine::select::hit_polylines(s.doc().unwrap(), e, 1e-4)).flatten().collect();
let by_x = |a: &Vec2, b: &Vec2| a.x.total_cmp(&b.x);
let (near, far) = (outline.iter().copied().min_by(by_x).unwrap(), outline.iter().copied().max_by(by_x).unwrap());
assert!(near.near(Vec2::new(70.0, 0.0), 1e-6) && far.near(Vec2::new(100.0, 0.0), 1e-6), "{near:?} to {far:?}");
}
/// Asserts that line `h` runs from `a` to `b`, within `tol`: for cuts far from the edge that makes
/// them, where the last digits of the crossing are not exact.
fn assert_ends_within(s: &Session, h: Handle, a: [f64; 2], b: [f64; 2], tol: f64) {
let (p, q) = ends(s, h);
assert!(p.near(Vec2::new(a[0], a[1]), tol) && q.near(Vec2::new(b[0], b[1]), tol), "{p:?} to {q:?}, expected {a:?} to {b:?}");
}
/// With edges that run on, a line in a reference a thousand times smaller than its block still
/// runs on as far as the same line outside a block: it cuts, and is a boundary for, an object
/// half a million units away. Also through two references that make it that small together.
#[test]
fn a_run_on_edge_in_a_small_reference_reaches_as_far_as_outside_a_block() {
for nested in [false, true] {
let mut s = Session::new();
let part = line(&mut s, [10.0, 4.0], [10.0, 12.0]);
block(&mut s, "B", &[part]);
// Drawn at x = 0.01 either way, from y = 0.004 to 0.012.
let r = if nested {
let inner = reference(&mut s, "B", [0.0, 0.0], [0.01, 0.01], 0.0);
block(&mut s, "OUTER", &[inner]);
reference(&mut s, "OUTER", [0.0, 0.0], [0.1, 0.1], 0.0)
} else {
reference(&mut s, "B", [0.0, 0.0], [0.001, 0.001], 0.0)
};
let l = line(&mut s, [-1.0, -5e5], [1.0, -5e5]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [0.9, -5e5], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends_within(&s, l, [-1.0, -5e5], [0.01, -5e5], 1e-6);
let short = line(&mut s, [-1.0, -6e5], [-0.5, -6e5]);
s.execute("extend", &json!({ "handle": short.hex(), "pick": [-0.6, -6e5], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends_within(&s, short, [-1.0, -6e5], [0.01, -6e5], 1e-6);
}
}
/// The run-on of a line in a small reference follows the line as the reference draws it: turned,
/// mirrored and scaled differently along X and Y, where its direction is not the block's.
#[test]
fn a_run_on_edge_in_a_small_uneven_reference_runs_along_the_drawn_line() {
// x = 10 for y in 4..12. Scaled by (0.001, -0.002) and turned a quarter turn: y = 0.01 for
// x in 0.008..0.024.
let mut s = Session::new();
let part = line(&mut s, [10.0, 4.0], [10.0, 12.0]);
block(&mut s, "B", &[part]);
let r = reference(&mut s, "B", [0.0, 0.0], [0.001, -0.002], 90.0);
let l = line(&mut s, [5e5, -1.0], [5e5, 1.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [5e5, 0.9], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends_within(&s, l, [5e5, -1.0], [5e5, 0.01], 1e-6);
// A slanted line, twice as tall as wide once drawn: it passes y = 1e6 at x = 5e5.
let mut s = Session::new();
let part = line(&mut s, [0.0, 0.0], [10.0, 10.0]);
block(&mut s, "S", &[part]);
let r = reference(&mut s, "S", [0.0, 0.0], [0.001, 0.002], 0.0);
let l = line(&mut s, [5e5 - 1.0, 1e6], [5e5 + 1.0, 1e6]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [5e5 + 0.9, 1e6], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends_within(&s, l, [5e5 - 1.0, 1e6], [5e5, 1e6], 1e-3);
}
/// The end segments of an open polyline in a small reference run on as far as outside a block.
#[test]
fn a_run_on_polyline_end_in_a_small_reference_reaches_as_far_as_outside_a_block() {
let mut s = Session::new();
let part = made(&s.execute("pline", &json!({ "vertices": [[10, 4], [10, 12], [20, 12]] })).unwrap());
block(&mut s, "B", &[part]);
let r = reference(&mut s, "B", [0.0, 0.0], [0.001, 0.001], 0.0);
// The first segment runs on down x = 0.01, the last one along y = 0.012.
let below = line(&mut s, [-1.0, -5e5], [1.0, -5e5]);
s.execute("trim", &json!({ "handle": below.hex(), "pick": [0.9, -5e5], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends_within(&s, below, [-1.0, -5e5], [0.01, -5e5], 1e-6);
let beside = line(&mut s, [5e5, -1.0], [5e5, 1.0]);
s.execute("trim", &json!({ "handle": beside.hex(), "pick": [5e5, 0.9], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends_within(&s, beside, [5e5, -1.0], [5e5, 0.012], 1e-6);
}
/// In a reference a million times larger than its block a line runs on no farther than the same
/// line outside a block does: an object neither reaches is cut by neither.
#[test]
fn a_run_on_edge_in_a_large_reference_reaches_no_farther_than_outside_a_block() {
let mut s = Session::new();
let part = line(&mut s, [10.0, 4.0], [10.0, 12.0]);
block(&mut s, "B", &[part]);
// Drawn at x = 1e7 from y = 4e6 to 1.2e7, as the line beside it outside a block.
let r = reference(&mut s, "B", [0.0, 0.0], [1e6, 1e6], 0.0);
let plain = line(&mut s, [1e7, 4e6], [1e7, 1.2e7]);
let l = line(&mut s, [1e7 - 1e3, -1e10], [1e7 + 1e3, -1e10]);
for edge in [plain, r] {
assert!(s.execute("trim", &json!({ "handle": l.hex(), "pick": [1e7 + 900.0, -1e10], "edges": [edge.hex()], "edgeMode": "extend" })).is_err());
}
// Both reach an object within their run-on.
let near = line(&mut s, [1e7 - 1e3, -1e7], [1e7 + 1e3, -1e7]);
s.execute("trim", &json!({ "handle": near.hex(), "pick": [1e7 + 900.0, -1e7], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends_within(&s, near, [1e7 - 1e3, -1e7], [1e7, -1e7], 1e-3);
}
/// A drawing whose block "TINY" holds `part` alone, referenced at the origin with `scale` on both
/// axes. Returns the reference. The part goes into the block as it is, however small.
fn one_part_reference(part: EntityKind, scale: f64) -> (Session, Handle) {
use cadcraft_engine::doc::{Common, Insert, Space};
let mut s = Session::new();
let d = s.doc_mut().unwrap();
let mut blk = Block::new("TINY");
blk.entities.push(Entity::new(d.new_handle(), part));
d.blocks.insert("TINY".into(), std::sync::Arc::new(blk));
let insert = Insert { block: "TINY".into(), scale: Vec3::new(scale, scale, 1.0), ..Insert::default() };
let r = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
(s, r)
}
/// A construction line and a ray in a reference keep their direction however small or large the
/// reference draws them: along the X axis they cut a line that crosses it, as the same object
/// outside a block does.
#[test]
fn an_endless_line_in_a_very_small_or_large_reference_still_cuts() {
use cadcraft_engine::doc::RayLine;
let along_x = RayLine { base: Vec3::ZERO, dir: Vec3::new(1.0, 0.0, 0.0) };
for scale in [1e-10, 1e-6, 1.0, 1e6, 1e10] {
for part in [EntityKind::XLine(along_x.clone()), EntityKind::Ray(along_x.clone())] {
let (mut s, r) = one_part_reference(part, scale);
let l = line(&mut s, [1.0, -5.0], [1.0, 5.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [1, 4], "edges": [r.hex()] })).unwrap_or_else(|e| panic!("scale {scale}: {e}"));
assert_ends(&s, l, [1.0, -5.0], [1.0, 0.0]);
}
}
}
/// With edges that run on, a line too short to have a direction by the drawing tolerance in its
/// block runs on once a large reference draws it long: from (0, 0) to (1, 0) it reaches a line
/// at x = 2. A line drawn that short by a small reference runs on too.
#[test]
fn a_run_on_edge_runs_along_the_placed_line_however_short_it_is_in_its_block() {
for (len, scale) in [(1e-10, 1e10), (1e-12, 1e12), (1.0, 1e-10), (1.0, 1.0)] {
let part = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(len, 0.0, 0.0) });
let (mut s, r) = one_part_reference(part, scale);
let l = line(&mut s, [2.0, -5.0], [2.0, 5.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [2, 4], "edges": [r.hex()], "edgeMode": "extend" }))
.unwrap_or_else(|e| panic!("length {len}, scale {scale}: {e}"));
assert_ends(&s, l, [2.0, -5.0], [2.0, 0.0]);
}
}
/// A drawing with a proxy whose graphics are four vertical lines across the X axis: at x = 30 on
/// a layer that is off, at x = 40 on a frozen layer, at x = 50 hidden, and at x = 60 on layer 0,
/// the only one drawn. `in_block`: the proxy is the one part of a block referenced at the origin,
/// else it is in the drawing itself. Returns the reference or the proxy.
fn proxy_with_one_drawn_graphic(in_block: bool) -> (Session, Handle) {
use cadcraft_engine::doc::{Common, Insert, Space, Unknown};
let mut s = Session::new();
let d = s.doc_mut().unwrap();
for (name, on, frozen) in [("OFF", false, false), ("FROZEN", true, true)] {
d.ensure_layer(name);
let l = d.layer_mut(name).unwrap();
(l.on, l.frozen) = (on, frozen);
}
let graphic = |x: f64, layer: &str, visible: bool| {
let mut g = Entity::new(Handle(0), EntityKind::Line(Line { a: Vec3::new(x, -10.0, 0.0), b: Vec3::new(x, 10.0, 0.0) }));
g.common.layer = layer.into();
g.common.visible = visible;
g
};
let graphics = vec![graphic(30.0, "OFF", true), graphic(40.0, "FROZEN", true), graphic(50.0, "0", false), graphic(60.0, "0", true)];
let proxy = EntityKind::Unknown(Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics });
let h = if in_block {
let mut blk = Block::new("PROXIES");
blk.entities.push(Entity::new(d.new_handle(), proxy));
d.blocks.insert("PROXIES".into(), std::sync::Arc::new(blk));
d.add(&Space::Model, Common::default(), EntityKind::Insert(Insert { block: "PROXIES".into(), ..Insert::default() })).unwrap()
} else {
d.add(&Space::Model, Common::default(), proxy).unwrap()
};
(s, h)
}
/// A proxy is an edge by the graphics it draws: those on a layer that is off or frozen and the
/// hidden ones cut nothing and stop nothing, in a block reference and in the drawing itself, with
/// the edge named and with every object an edge.
#[test]
fn proxy_graphics_that_are_not_drawn_are_not_edges() {
let mut wrong = Vec::new();
for (in_block, named) in [(true, true), (true, false), (false, true), (false, false)] {
let (mut s, edge) = proxy_with_one_drawn_graphic(in_block);
let edges = if named { json!([edge.hex()]) } else { Value::Null };
// Picked at its start, the line loses the stretch up to the first edge: the drawn graphic.
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [1, 0], "edges": edges })).unwrap();
let (a, b) = ends(&s, l);
if !(a.near(Vec2::new(60.0, 0.0), 1e-9) && b.near(Vec2::new(100.0, 0.0), 1e-9)) {
wrong.push(format!("trim, in a block {in_block}, named {named}: {a:?} to {b:?}"));
}
s.execute("erase", &json!({ "handles": [l.hex()] })).unwrap();
// The first boundary a line running towards them reaches is the drawn graphic too.
let short = line(&mut s, [0.0, -2.0], [5.0, -2.0]);
s.execute("extend", &json!({ "handle": short.hex(), "pick": [4, -2], "edges": edges })).unwrap();
let (a, b) = ends(&s, short);
if !(a.near(Vec2::new(0.0, -2.0), 1e-9) && b.near(Vec2::new(60.0, -2.0), 1e-9)) {
wrong.push(format!("extend, in a block {in_block}, named {named}: {a:?} to {b:?}"));
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
/// One look for edges stays inside one bound on the objects it visits in block references,
/// however many references the drawing has: with far more references than the bound allows, the
/// edge in the first reference still cuts and the edge in the last one is no edge. (Each
/// reference had the whole bound to itself, so the walk over all of them had none.)
#[test]
fn the_look_for_edges_in_references_is_bounded_over_all_of_them() {
use cadcraft_engine::doc::{Common, Insert, Space};
let (mut s, _) = one_reference();
let d = s.doc_mut().unwrap();
let at = |x: f64, y: f64| EntityKind::Insert(Insert { block: "B".into(), insert: Vec3::new(x, y, 0.0), ..Insert::default() });
// The references between the two draw their line far above the X axis, where it cuts nothing.
for _ in 0..30_000 {
d.add(&Space::Model, Common::default(), at(0.0, 1000.0)).unwrap();
}
// The last reference draws the block's line at x = 40, nearer the pick than the first one's.
d.add(&Space::Model, Common::default(), at(-10.0, 0.0)).unwrap();
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [10, 0] })).unwrap();
assert_ends(&s, l, [70.0, 0.0], [100.0, 0.0]);
}
/// A drawing with six references to block "PROXY", whose one object is a proxy that draws the
/// vertical line x = 50 across the X axis and 5,000 short lines far above it. The first reference
/// draws the vertical line at x = 70 and the last one at x = 40; the four between draw theirs far
/// above the X axis. The graphics of the six are more than one look for edges may visit.
/// `drawn`: whether the short lines are drawn, or hidden (the vertical line always is drawn).
fn references_to_a_proxy_with_many_graphics(drawn: bool) -> Session {
use cadcraft_engine::doc::{Common, Insert, Space, Unknown};
let mut s = Session::new();
let d = s.doc_mut().unwrap();
let graphic =
|a: [f64; 2], b: [f64; 2]| Entity::new(Handle(0), EntityKind::Line(Line { a: Vec3::new(a[0], a[1], 0.0), b: Vec3::new(b[0], b[1], 0.0) }));
let mut graphics = vec![graphic([50.0, -10.0], [50.0, 10.0])];
graphics.extend((0..5_000).map(|i| {
let mut g = graphic([f64::from(i), 1000.0], [f64::from(i), 1001.0]);
g.common.visible = drawn;
g
}));
let mut blk = Block::new("PROXY");
blk.entities.push(Entity::new(d.new_handle(), EntityKind::Unknown(Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics })));
d.blocks.insert("PROXY".into(), std::sync::Arc::new(blk));
for at in [[20.0, 0.0], [0.0, 2000.0], [0.0, 2000.0], [0.0, 2000.0], [0.0, 2000.0], [-10.0, 0.0]] {
let insert = Insert { block: "PROXY".into(), insert: Vec3::new(at[0], at[1], 0.0), ..Insert::default() };
d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
}
s
}
/// The graphics of a proxy count toward the same bound: a proxy inside a block comes as one
/// object, but the look goes through every graphic it holds, in every reference, to take the
/// drawn ones. With a few references to a block whose proxy holds thousands of graphics, the edge
/// in the first reference is still an edge and the edge in the last one, reached after the bound
/// is spent, is none: for TRIM, for EXTEND and for the highlight under the cursor, which looks
/// for edges on every move, and whether those graphics are drawn or hidden.
#[test]
fn the_graphics_of_a_proxy_in_references_count_toward_the_bound() {
let mut wrong = Vec::new();
for drawn in [true, false] {
// TRIM: the pick is left of both lines; the cut is at the first reference's, the farther one.
let mut s = references_to_a_proxy_with_many_graphics(drawn);
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [10, 0] })).unwrap();
let (a, b) = ends(&s, l);
if !(a.near(Vec2::new(70.0, 0.0), 1e-9) && b.near(Vec2::new(100.0, 0.0), 1e-9)) {
wrong.push(format!("trim, drawn {drawn}: {a:?} to {b:?}"));
}
// EXTEND: the line grows to the right, past x = 40, to the first reference's line.
let mut s = references_to_a_proxy_with_many_graphics(drawn);
let l = line(&mut s, [0.0, 0.0], [30.0, 0.0]);
s.execute("extend", &json!({ "handle": l.hex(), "pick": [29, 0] })).unwrap();
let (a, b) = ends(&s, l);
if !(a.near(Vec2::new(0.0, 0.0), 1e-9) && b.near(Vec2::new(70.0, 0.0), 1e-9)) {
wrong.push(format!("extend, drawn {drawn}: {a:?} to {b:?}"));
}
// The highlight in the running TRIM: the piece a click at x = 10 removes ends at x = 70.
let mut s = references_to_a_proxy_with_many_graphics(drawn);
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.zoom_extents().unwrap();
s.start("trim").unwrap();
let part = s.highlight(l, Vec2::new(10.0, 0.0)).expect("a part of the line is highlighted");
let outline: Vec<Vec2> = part.iter().flat_map(|e| cadcraft_engine::select::hit_polylines(s.doc().unwrap(), e, 1e-4)).flatten().collect();
let by_x = |a: &Vec2, b: &Vec2| a.x.total_cmp(&b.x);
let (near, far) = (outline.iter().copied().min_by(by_x).unwrap(), outline.iter().copied().max_by(by_x).unwrap());
if !(near.near(Vec2::new(0.0, 0.0), 1e-6) && far.near(Vec2::new(70.0, 0.0), 1e-6)) {
wrong.push(format!("highlight, drawn {drawn}: {near:?} to {far:?}"));
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
+15 -14
View File
@@ -7,23 +7,24 @@ use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, set_io, set_write_as};
use serde_json::json;
/// A 2018 DXF with one mental ray render settings object, stored as `90 2` (class version 1 in the
/// 2013+ form).
/// A 2018 DXF with plain and mental ray settings. Both store base class version 2.
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\nMENTALRAYRENDERSETTINGS\n2\nAcDbMentalRayRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nENDSEC\n\
0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\nRENDERSETTINGS\n2\nAcDbRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nCLASS\n1\nMENTALRAYRENDERSETTINGS\n2\nAcDbMentalRayRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nENDSEC\n\
0\nSECTION\n2\nOBJECTS\n\
0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_RENDER_SETTINGS\n350\n20\n\
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n\
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n3\nPlain\n350\n22\n\
0\nMENTALRAYRENDERSETTINGS\n5\n21\n330\n20\n100\nAcDbRenderSettings\n90\n2\n1\nMedium\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n\
100\nAcDbMentalRayRenderSettings\n90\n2\n0\nENDSEC\n0\nEOF\n";
100\nAcDbMentalRayRenderSettings\n90\n2\n0\nRENDERSETTINGS\n5\n22\n330\n20\n100\nAcDbRenderSettings\n90\n2\n1\nPlain\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n0\nENDSEC\n0\nEOF\n";
/// The `AcDbRenderSettings` class version in a written DXF.
fn class_version(path: &std::path::Path) -> Option<i64> {
fn class_versions(path: &std::path::Path) -> [Option<i64>; 2] {
let text = std::fs::read_to_string(path).unwrap();
let l: Vec<&str> = text.lines().map(str::trim).collect();
let at = l.windows(2).position(|w| w == ["0", "MENTALRAYRENDERSETTINGS"])?;
let base = l[at..].windows(2).position(|w| w == ["100", "AcDbRenderSettings"])? + at;
l[base..].windows(2).find(|w| w[0] == "90").map(|w| w[1].parse().unwrap())
["RENDERSETTINGS", "MENTALRAYRENDERSETTINGS"].map(|kind| {
let at = l.windows(2).position(|w| w == ["0", kind])?;
let base = l[at..].windows(2).position(|w| w == ["100", "AcDbRenderSettings"])? + at;
l[base..].windows(2).find(|w| w[0] == "90").map(|w| w[1].parse().unwrap())
})
}
#[test]
@@ -43,13 +44,13 @@ fn saveas_down_and_back_up_keeps_the_render_settings_class_version() {
let save = |s: &mut Session, name: &str, version: &str| {
let path = dir.join(name);
s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": version })).unwrap();
class_version(&path)
class_versions(&path)
};
assert_eq!(save(&mut s, "2018.dxf", "2018"), Some(2), "same version: as read");
assert_eq!(save(&mut s, "2000.dxf", "2000"), Some(1), "the 2000 form is one lower");
assert_eq!(save(&mut s, "2018.dxf", "2018"), [Some(2), Some(2)], "same version: as read");
assert_eq!(save(&mut s, "2000.dxf", "2000"), [Some(1), Some(2)], "only plain settings have a lower 2000 form");
s.execute("qsave", &json!({})).unwrap();
assert_eq!(class_version(&dir.join("2000.dxf")), Some(1), "QSAVE keeps the 2000 form");
assert_eq!(save(&mut s, "back.dxf", "2018"), Some(2), "back to 2018: the 2018 file's value, not one higher");
assert_eq!(class_versions(&dir.join("2000.dxf")), [Some(1), Some(2)], "QSAVE keeps both 2000 forms");
assert_eq!(save(&mut s, "back.dxf", "2018"), [Some(2), Some(2)], "back to 2018: the 2018 file's value, not one higher");
let _ = std::fs::remove_dir_all(&dir);
}
+10 -7
View File
@@ -1,5 +1,8 @@
//! Saving over a drawing keeps the previous file as `<name>.bak` (ISAVEBAK, #540), and the
//! save itself replaces the file atomically: no temporary files are left behind.
//!
//! Some tests damage the file behind the session's back on purpose; the save after that passes
//! `overwrite: true`, since a save refuses a file changed on disk (`save_changed_on_disk.rs`).
use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, backup_path, looks_complete, looks_like_drawing, save_keeps_current, set_io};
@@ -98,7 +101,7 @@ fn a_damaged_file_never_replaces_a_good_backup_and_isavebak_0_keeps_none() {
// Another program truncates the drawing; the next save keeps the good backup.
std::fs::write(&path, b"").unwrap();
add_circle(&mut s, 10.0);
s.execute("qsave", &json!({})).unwrap();
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
assert_eq!((circles(&path), circles(&backup_path(&path))), (3, 1));
// Cut off with a drawing's start kept (half a DXF, a DWG's version tag alone): the backup
@@ -106,11 +109,11 @@ fn a_damaged_file_never_replaces_a_good_backup_and_isavebak_0_keeps_none() {
let whole = std::fs::read(&path).unwrap();
std::fs::write(&path, &whole[..whole.len() / 2]).unwrap();
add_circle(&mut s, 11.0);
s.execute("qsave", &json!({})).unwrap();
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
assert_eq!(circles(&backup_path(&path)), 1, "half a DXF");
std::fs::write(&path, b"AC1032").unwrap();
add_circle(&mut s, 12.0);
s.execute("qsave", &json!({})).unwrap();
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
assert_eq!(circles(&backup_path(&path)), 1, "a DWG's tag alone");
// ISAVEBAK 0: the backup is left as it was.
@@ -234,7 +237,7 @@ fn a_dwg_cut_off_anywhere_keeps_the_good_backup() {
// Another program leaves it cut off at 90%: the next save keeps the good backup.
std::fs::write(&path, &whole[..whole.len() * 9 / 10]).unwrap();
add_circle(&mut s, 10.0);
s.execute("qsave", &json!({})).unwrap();
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
assert_eq!(circles(&backup_path(&path)), 1, "{version}: the cut-off file didn't replace it");
let _ = std::fs::remove_dir_all(&dir);
}
@@ -255,7 +258,7 @@ fn a_file_that_looks_damaged_is_kept_when_there_is_no_backup_yet() {
let odd = b"AC1032 but not as this header expects it".to_vec();
std::fs::write(&path, &odd).unwrap();
add_circle(&mut s, 5.0);
s.execute("qsave", &json!({})).unwrap();
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
assert_eq!(std::fs::read(backup_path(&path)).unwrap(), odd);
let _ = std::fs::remove_dir_all(&dir);
}
@@ -281,14 +284,14 @@ fn the_backup_a_save_promises_is_the_one_it_writes() {
std::fs::write(&path, &dwg2007).unwrap();
assert!(save_keeps_current(&path));
add_circle(&mut s, 10.0);
s.execute("qsave", &json!({})).unwrap();
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
assert_eq!(std::fs::read(backup_path(&path)).unwrap(), dwg2007, "the promise was kept");
std::fs::write(backup_path(&path), &old).unwrap();
std::fs::write(&path, b"AC1032").unwrap();
assert!(!save_keeps_current(&path));
add_circle(&mut s, 15.0);
s.execute("qsave", &json!({})).unwrap();
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
assert_eq!(std::fs::read(backup_path(&path)).unwrap(), old, "cut off: nothing was promised");
cadcraft_engine::autosave::set_isavebak(false);
+2 -4
View File
@@ -35,8 +35,6 @@ craft-pdf = { workspace = true, features = ["read"] }
# Inspect DWG output only where craft-dwg builds its native bridge. An unconditional
# dev-dependency also builds acadrust during --all-targets, breaking FreeBSD aarch64 (#2526).
# The storytold/acadrust fork at tag `storytold/v0.6.6` (upstream v0.6.6), the source craft-dwg moves
# to in storytold/craft-libs#4762; until craft-libs is repinned, craft-dwg still takes the identical
# crates.io 0.6.6.
# Use the same fork revision as craft-dwg so these fixtures exercise its DWG representation.
[target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dev-dependencies]
acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "5d5c482b3fcb3dc77e8281474461760f32959436" }
acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "468b9d8e317755209020d5d3f2f1c8a76210c47f" }

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