Compare commits

...
Author SHA1 Message Date
dependabot[bot] 1810a47be6 ci(deps): bump the actions group across 1 directory with 2 updates
Bumps the actions group with 2 updates in the / directory: [step-security/harden-runner](https://github.com/step-security/harden-runner) and [storytold/craft-common-actions/actions/cache-prune](https://github.com/storytold/craft-common-actions).


Updates `step-security/harden-runner` from 2.22.4 to 2.23.0
- [Release notes](https://github.com/step-security/harden-runner/releases)
- [Commits](https://github.com/step-security/harden-runner/compare/1d88384fd173af6ecb012dfd0264a306b711241a...aebdcf6156ab6691adf63218240e476564a1ed4c)

Updates `storytold/craft-common-actions/actions/cache-prune` from b2726eb1defb6eccdfad920cc6988e1e3ec1c3c9 to 00aadd0cb7ecfd9543dbb59dd4c4a3c1fff897d2
- [Commits](https://github.com/storytold/craft-common-actions/compare/b2726eb1defb6eccdfad920cc6988e1e3ec1c3c9...00aadd0cb7ecfd9543dbb59dd4c4a3c1fff897d2)

---
updated-dependencies:
- dependency-name: step-security/harden-runner
  dependency-version: 2.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
- dependency-name: storytold/craft-common-actions/actions/cache-prune
  dependency-version: 94c8262155ee5424556db4e4983fe80ef9e779ba
  dependency-type: direct:production
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-12-04 11:05:41 +00:00
e07c3f0c11 Add Finnish interface language (#1246)
* Add Finnish interface language

Adds a Finnish (Suomi, `fi`) catalog with 1,330 rows: the union of the
existing catalogs, including the Ukrainian reference, four contextual
menu headings and two count templates. Finnish uses the one/other
plural rule with the partitive singular after any number but 1.

Menu headings keep Edit (Muokkaa) and Modify (Muuta) apart, and the
Dimension menu (Mitoitus) apart from a dimension object (Mitta).
Any fi-* locale selects Finnish; sv-FI keeps Swedish.

Tests cover locale resolution, preferences, plurals, menu headings
(including that every menu bar heading is distinct), live switching,
dialog rendering and font glyphs. No gaps are reported for Finnish.

Clean-room, AI-assisted (Claude Code) translation written from the
English strings; not yet proofread line by line by a native speaker.

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

* i18n(fi): Georgian joined the language list; translate 16 new labels

- `Language::ALL` and `LANGUAGES` grow by one for Finnish after the merge
  with main added Georgian (21 and 20 entries).
- fi.tsv: the save-loss prompt (Save Anyway, Saving {name} will remove
  content, ...), the text editor (Edit Text, Ctrl+Enter to apply) and Clip
  Xref; 1,492 rows. docs/localization.md row count updated.

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

* Run finnish_locales_preferences_and_plural_forms again (#[test] was lost in the last merge)

* Finnish tests install the headless runtime as main's do; two new labels

finnish_dialogs_render_with_stable_ids and the live-switch test now call
framework::install_headless, like main's dialog tests, and Finnish gets
the two labels main added since (New Layout from Area..., Quick Leader).

* Remove the duplicate automatic locale match arm

---------

Co-authored-by: Janiz-zzz <267742026+Janiz-zzz@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 10:51:43 +01:00
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 17fb7a3c43 Read Cargo.lock with CRLF line endings too in the wgpu-hal patch test (#1631) 2026-12-03 13:03:35 +07: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 5a7182240e Merge remote-tracking branch 'origin/main' into fix/metal-language-version-1631
# Conflicts:
#	crates/ui-egui/src/gpu.rs
2026-12-03 12:33:50 +07:00
FredApps e7d05e1b42 sonar: leave the vendored wgpu-hal out of the analysis (#1631) 2026-12-03 05:42:47 +01:00
FredApps d55ac7ba7a wgpu-hal patch: log Metal versions as major.minor (#1631) 2026-12-03 05:16:38 +01:00
FredApps 0623c42d10 macOS: compile shaders with the newest Metal version the system compiler accepts (#1631) 2026-12-03 05:15:12 +01:00
FredApps 738230f7ea vendor: wgpu-hal 30.0.1 unchanged, as published on crates.io (#1631) 2026-12-03 05:15:12 +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
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
283 changed files with 66549 additions and 796 deletions
+2 -2
View File
@@ -25,10 +25,10 @@ jobs:
actions: write
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
with:
egress-policy: audit
# A failed pass warns; the next run's prune deletes what it missed.
- name: Prune replaced cache entries
uses: storytold/craft-common-actions/actions/cache-prune@b2726eb1defb6eccdfad920cc6988e1e3ec1c3c9 # main
uses: storytold/craft-common-actions/actions/cache-prune@00aadd0cb7ecfd9543dbb59dd4c4a3c1fff897d2 # main
continue-on-error: true
+2 -2
View File
@@ -28,7 +28,7 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -58,7 +58,7 @@ jobs:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+4 -2
View File
@@ -30,9 +30,10 @@ Generated-in-code assets are original and have no file to list:
| Asset | Author | Source | Licence | Notes |
|---|---|---|---|---|
| `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`. |
@@ -88,6 +89,7 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star; terminology pass by @YannFR81 | Original French translations of CADCraft English strings; AI-assisted consistency pass (imperative prompts, cote/espace objet/réseau/présentation) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/zh.tsv` | @mayloglog | Original Simplified Chinese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/sv.tsv` | Erik Holmbom (@holmbom) with Claude Code (AI-assisted) | Original Swedish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the running app reviewed by a native speaker |
| `crates/ui-egui/src/i18n/fi.tsv` | @Janiz-zzz with Claude Code (AI-assisted) | Original Finnish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/it.tsv` | Emanuele Bottelli (AI-assisted); terminology corrections: Andrea Brandi (@starise) with OpenAI Codex (AI-assisted) | Original Italian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; targeted Chamfer terminology review by a native speaker |
| `crates/ui-egui/src/i18n/ko.tsv` | @huk082 (AI-assisted) | Original Korean translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; no font assets added |
| `crates/ui-egui/src/i18n/ar.tsv` | @hasan-sdaif; missing rows and the Find and Replace dialog: Saleh Hassan Alnemari (@salehnemari-max) with Claude Code (AI-assisted) | Original Arabic translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the added rows reviewed line by line by the translator, a native speaker |
Generated
+396 -139
View File
File diff suppressed because it is too large Load Diff
+49 -38
View File
@@ -1,6 +1,8 @@
[workspace]
resolver = "3"
members = ["crates/*", "apps/*", "xtask"]
# Patched third-party crates under [patch.crates-io], not ours to lint or test.
exclude = ["vendor/wgpu-hal"]
# default-members
[workspace.package]
@@ -14,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" }
@@ -29,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"] }
@@ -75,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 }
@@ -91,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 }
@@ -123,23 +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.
+15 -1
View File
@@ -124,7 +124,7 @@ numbers):
| Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF |
| Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit |
| Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror |
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski), Georgian (ქართული), Tamil (தமிழ், with an installed Tamil font), Dutch (Nederlands) and European Portuguese (Português (Portugal)) (catalogs in `storytold/craft-i18n`; fall back to English until embedded), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski), Georgian (ქართული), Tamil (தமிழ், with an installed Tamil font), Dutch (Nederlands) and European Portuguese (Português (Portugal)) (catalogs in `storytold/craft-i18n`; fall back to English until embedded), Finnish (Suomi), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
| Automation | MCP server, JSON control channel, `cadcraft-cli` (info, convert, run, commands, mcp) |
## Quick start
@@ -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)
+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.
+31 -1
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(),
]
}
@@ -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 {
+3
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,
@@ -207,6 +209,7 @@ impl Default for Settings {
highlight: true,
selectioneffect: 1,
selectionpreview: 3,
selectionannodisplay: true,
previeweffect: 2,
previewfilter: 3,
grips: 1,
+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()),
}
}
+9 -2
View File
@@ -55,6 +55,7 @@ const SESSION_VARS: &[&str] = &[
"HIGHLIGHT",
"SELECTIONEFFECT",
"SELECTIONPREVIEW",
"SELECTIONANNODISPLAY",
"PREVIEWEFFECT",
"PREVIEWFILTER",
"GRIPS",
@@ -185,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),
@@ -234,7 +236,10 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
"TEXTEVAL" => json!(i32::from(st.texteval)),
// Dialogs are available (read-only; a batch session is still told 1, as AutoCAD does).
"POPUPS" => json!(1),
"CMDNAMES" => json!(s.running.as_ref().map(|r| r.id.to_ascii_uppercase()).unwrap_or_default()),
// 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
@@ -244,7 +249,8 @@ 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.
@@ -478,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)?,
+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();
}
@@ -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());
}
@@ -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)),
+32
View File
@@ -2,10 +2,12 @@
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;
@@ -13,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;
@@ -21,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;
@@ -32,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;
@@ -49,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;
@@ -72,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;
@@ -99,6 +110,7 @@ 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;
@@ -106,18 +118,22 @@ 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;
@@ -135,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;
@@ -157,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;
@@ -173,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;
@@ -203,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;
@@ -214,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;
@@ -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" }
-106
View File
@@ -1,106 +0,0 @@
//! The angles of a hatch's elliptic boundary edges in the DXF a DWG is read through.
//!
//! A DWG holds an elliptic edge's start and end angles in radians, and so does the DXF the DWG
//! decoder writes (groups 50 and 51 of an edge of type 3). DXF itself keeps them in degrees, which
//! is how [`crate::dxf_read`] reads them: a circle stored as an elliptic edge with the end angle
//! 6.2832 became an arc of 6.28 degrees, and the hatch covered the hole it should have left open.
//! Only the DWG path needs this; a DXF file is read as written.
use std::f64::consts::PI;
/// `dxf` with the start and end angles (groups 50 and 51) of every elliptic hatch edge (edge type
/// 3, group 72) turned from radians to degrees. The text is handled as bytes: a drawing from
/// before 2007 is written in its code page, which is not UTF-8, and every other byte is kept as it
/// was. Binary DXF, and text with no such edge, come back as they were.
pub(crate) fn elliptic_edge_degrees(dxf: Vec<u8>) -> Vec<u8> {
if dxf.starts_with(b"AutoCAD Binary DXF") || !dxf.windows(5).any(|w| w == b"HATCH") {
return dxf;
}
let mut out = Vec::with_capacity(dxf.len());
let mut lines = dxf.split_inclusive(|b| *b == b'\n');
let mut in_hatch = false;
// After an elliptic edge's type, until the next edge or loop: the angles still to convert.
let mut ellipse = false;
let mut changed = false;
while let Some(code_line) = lines.next() {
let Some(value_line) = lines.next() else {
out.extend_from_slice(code_line);
break;
};
let code = code_line.trim_ascii();
let value = value_line.trim_ascii();
match code {
b"0" => {
in_hatch = value == b"HATCH";
ellipse = false;
}
b"72" if in_hatch => ellipse = value == b"3",
b"92" | b"97" if in_hatch => ellipse = false,
b"50" | b"51" if in_hatch && ellipse => {
if let Some(radians) = std::str::from_utf8(value).ok().and_then(|v| v.parse::<f64>().ok()).filter(|v| v.is_finite()) {
let ending = &value_line[value_line.trim_ascii_end().len()..];
out.extend_from_slice(code_line);
out.extend_from_slice(format!("{}", radians * 180.0 / PI).as_bytes());
out.extend_from_slice(ending);
changed = true;
continue;
}
}
_ => {}
}
out.extend_from_slice(code_line);
out.extend_from_slice(value_line);
}
if changed { out } else { dxf }
}
#[cfg(test)]
mod tests {
use super::*;
fn pairs(text: &str) -> Vec<(String, String)> {
let lines: Vec<&str> = text.lines().collect();
lines.chunks(2).filter_map(|c| Some((c.first()?.trim().to_string(), c.get(1)?.trim().to_string()))).collect()
}
const HATCH: &str = "0\r\nHATCH\r\n91\r\n1\r\n92\r\n1\r\n93\r\n2\r\n72\r\n3\r\n10\r\n5.0\r\n20\r\n6.0\r\n11\r\n-55.5\r\n21\r\n0.0\r\n40\r\n1.0\r\n50\r\n0.0\r\n51\r\n6.283185307179586\r\n73\r\n1\r\n72\r\n1\r\n10\r\n1.0\r\n20\r\n2.0\r\n11\r\n3.0\r\n21\r\n4.0\r\n50\r\n7.0\r\n0\r\nLINE\r\n50\r\n9.0\r\n";
#[test]
fn an_elliptic_edge_gets_its_angles_in_degrees_and_nothing_else_changes() {
let out = String::from_utf8(elliptic_edge_degrees(HATCH.as_bytes().to_vec())).unwrap();
let p = pairs(&out.replace("\r\n", "\n"));
let value = |code: &str, n: usize| p.iter().filter(|(c, _)| c == code).nth(n).map(|(_, v)| v.parse::<f64>().unwrap());
assert!((value("51", 0).unwrap() - 360.0).abs() < 1e-9);
assert_eq!(value("50", 0), Some(0.0));
// A line edge's 50 and another entity's are left alone, as is the line ending.
assert_eq!(value("50", 1), Some(7.0));
assert_eq!(value("50", 2), Some(9.0));
assert!(out.contains("\r\n") && !out.replace("\r\n", "").contains('\r'));
}
/// A drawing from before 2007 is written in its code page: an accented letter is one byte that
/// is not valid UTF-8, and it must not stop the angles being converted or change.
#[test]
fn a_code_page_drawing_still_has_its_angles_converted() {
let mut dxf = b"0\r\nTEXT\r\n1\r\ncaf".to_vec();
dxf.push(0xE9);
dxf.extend_from_slice(b"\r\n");
dxf.extend_from_slice(HATCH.as_bytes());
let out = elliptic_edge_degrees(dxf.clone());
assert!(std::str::from_utf8(&dxf).is_err(), "the input is not UTF-8");
assert!(out.windows(4).any(|w| w == b"caf\xE9"), "the accented byte is kept");
let text: String = out.iter().map(|b| char::from(*b)).collect();
assert!(text.contains("51\r\n360"), "the end angle is 360 degrees: {text}");
}
#[test]
fn text_without_a_hatch_ellipse_comes_back_untouched() {
let dxf = b"0\nLINE\n50\n1.5\n".to_vec();
assert_eq!(elliptic_edge_degrees(dxf.clone()), dxf);
let binary = b"AutoCAD Binary DXF\r\n\x1a\x00HATCH".to_vec();
assert_eq!(elliptic_edge_degrees(binary.clone()), binary);
// A hatch with no elliptic edge is left as it is.
let plain = "0\nHATCH\n72\n1\n50\n2.0\n".as_bytes().to_vec();
assert_eq!(elliptic_edge_degrees(plain.clone()), plain);
}
}
+85 -3
View File
@@ -11,8 +11,9 @@
//! CADCraft keeps an annotative object at paper size with the list of scales it supports
//! ([`cadcraft_doc::Common::anno_scales`]). It writes the object at its default scale with a
//! context per scale ([`plan`], [`objects`]), and reads the scales and paper size back from the
//! contexts ([`resolve`]). An object's position at each scale is the one the scale gives it:
//! AutoCAD lets a context move an object at one scale only, which CADCraft doesn't model.
//! contexts ([`resolve`]). A context can place the object somewhere else at its scale (moved with
//! grips at that scale in AutoCAD or CADCraft): that is the object's offset at the scale
//! ([`cadcraft_doc::AnnoMove`]), written into and read back from the context's position.
//!
//! Objects inside block definitions are left alone, and files older than AutoCAD 2007's format
//! (before annotation scaling) don't get contexts.
@@ -67,8 +68,16 @@ fn by_alignment(t: &Text) -> bool {
/// `e` at annotation scale `f`, as its groups are written there: sizes scaled (see
/// [`cadcraft_doc::anno_scaled`]) and justified text's start point moved with its size about its
/// alignment point. A dimension's definition gets that scale (DIMSCALE).
/// alignment point. A dimension's definition gets that scale (DIMSCALE). The object's offset at
/// that scale moves it there.
pub(crate) fn at_scale(e: &Entity, f: f64) -> Entity {
let mut out = shared_at_scale(e, f);
cadcraft_doc::shift_position(&mut out.kind, e.common.moved_at_factor(f));
out
}
/// [`at_scale`] at the object's shared position (without its offset there).
fn shared_at_scale(e: &Entity, f: f64) -> Entity {
let mut out = cadcraft_doc::anno_scaled(e, f);
if let (EntityKind::Text(t), EntityKind::Text(paper)) = (&mut out.kind, &e.kind)
&& by_alignment(paper)
@@ -79,6 +88,47 @@ pub(crate) fn at_scale(e: &Entity, f: f64) -> Entity {
out
}
/// The point that places `e` (as written at some scale): a text's start or alignment point, an
/// MText's insertion point, a dimension's text position, a multileader's landing.
fn anchor(d: &Drawing, e: &Entity) -> Option<cadcraft_geom::Vec2> {
let p = match &e.kind {
EntityKind::Text(t) if by_alignment(t) => t.align_pt?.xy(),
EntityKind::Text(t) => t.insert.xy(),
EntityKind::MText(t) => t.insert.xy(),
EntityKind::Dimension(dm) if dm.user_text_pos => dm.text_mid.xy(),
EntityKind::Dimension(dm) => cadcraft_render::dimension_in(d, dm).text_pos,
EntityKind::MLeader(m) => m.landing.xy(),
_ => return None,
};
p.is_finite().then_some(p)
}
/// The same point as a context of `e` holds it (`g`: the context's groups after its SCALE
/// handle).
fn context_anchor(e: &Entity, g: &[Tag]) -> Option<cadcraft_geom::Vec2> {
let xy = |code: i32| -> Option<cadcraft_geom::Vec2> {
let i = g.iter().position(|t| t.code == code)?;
let y = g.get(i + 1).filter(|t| t.code == code + 10)?;
let v = cadcraft_geom::Vec2::new(g.get(i)?.f64(), y.f64());
v.is_finite().then_some(v)
};
match &e.kind {
EntityKind::Text(t) if by_alignment(t) => xy(11),
EntityKind::Text(_) => xy(10),
EntityKind::MText(_) => xy(11),
// Only a text the user placed (294 = 0) holds its own position.
EntityKind::Dimension(_) => g.iter().find(|t| t.code == 294).is_some_and(|t| t.i64() == 0).then(|| xy(10)).flatten(),
EntityKind::MLeader(_) => {
let mut tags = vec![Tag::s(100, "AcDbMLeader"), Tag::s(300, "CONTEXT_DATA{")];
tags.extend(g.iter().cloned());
tags.push(Tag::s(301, "}"));
let p = crate::dxf_mleader::read(&tags).landing.xy();
p.is_finite().then_some(p)
}
_ => None,
}
}
/// One context: its handle, the SCALE object's handle and the scale.
pub(crate) struct Context {
handle: String,
@@ -347,6 +397,16 @@ pub(crate) fn mleader_at(tags: &mut [Tag], f: f64) {
}
}
/// A multileader's groups (as [`crate::dxf_mleader::entity_tags`] writes them) marked annotative:
/// the entity's "enable annotation scale" (its 293, after the `CONTEXT_DATA{` block) is on.
/// Without it AutoCAD keeps the contexts but its ANNORESET passes the multileader over.
pub(crate) fn mleader_annotative(tags: &mut [Tag]) {
let Some(close) = tags.iter().position(|t| t.code == 301) else { return };
if let Some(t) = tags.iter_mut().skip(close + 1).find(|t| t.code == 293) {
*t = Tag::i(293, 1);
}
}
// ---------------------------------------------------------------------------------------------
// Reading
@@ -422,6 +482,7 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
.and_then(|s| objs.get(&s));
let Some((_, dict)) = dict else { continue };
let mut list: Vec<(AnnoScale, bool)> = Vec::new();
let mut placed: Vec<(String, f64, cadcraft_geom::Vec2)> = Vec::new();
for c in all_entries(dict) {
let Some((_, t)) = objs.get(&c).filter(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")) else { continue };
let g = own(t);
@@ -431,6 +492,10 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
&& !list.iter().any(|(x, _)| x.name.eq_ignore_ascii_case(&s.name))
{
list.push((s.clone(), default));
let after = g.iter().position(|t| t.code == 340).map_or(&[][..], |i| g.get(i + 1..).unwrap_or(&[]));
if let Some(at) = context_anchor(e, after) {
placed.push((s.name.clone(), s.factor(), at));
}
}
}
if list.is_empty() {
@@ -443,6 +508,23 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
e.common.anno_scales = list;
to_paper(e, f);
});
// A context placing the object elsewhere than its scale would: its offset there.
let Some(e) = d.entity(h).map(|e| (**e).clone()) else { continue };
let moves: Vec<(String, cadcraft_geom::Vec2)> = placed
.iter()
.filter_map(|(name, f, at)| {
let by = *at - anchor(d, &shared_at_scale(&e, *f))?;
let tol = 1e-6 * (1.0 + at.len());
(by.is_finite() && by.len() > tol).then(|| (name.clone(), by))
})
.collect();
if !moves.is_empty() {
let _ = d.modify_entity(h, |e| {
for (name, by) in &moves {
e.common.move_at(name, *by);
}
});
}
}
}
+15 -1
View File
@@ -1024,6 +1024,11 @@ pub(crate) struct AnnoPayload {
struct AnnoObject {
handle: String,
scales: Vec<cadcraft_doc::AnnoScale>,
/// Where the object sits at a scale when it was moved there alone (see `Common::anno_moves`):
/// a format without annotation scale contexts (or a DWG, whose bridge doesn't convert them
/// yet) keeps them here.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
moves: Vec<cadcraft_doc::AnnoMove>,
}
/// Most annotative objects read from one file.
@@ -1041,7 +1046,7 @@ pub(crate) fn anno_chunks(d: &cadcraft_doc::Drawing, contexts: bool) -> Option<V
.iter()
.chain(d.layouts.iter().flat_map(|l| l.entities.iter()))
.filter(|e| cadcraft_doc::is_annotative(e) && !(contexts && crate::dxf_anno::has_contexts(e)))
.map(|e| AnnoObject { handle: e.handle.hex(), scales: e.common.anno_scales.clone() })
.map(|e| AnnoObject { handle: e.handle.hex(), scales: e.common.anno_scales.clone(), moves: e.common.anno_moves.clone() })
.collect();
if cannoscale == "1:1" && annoallvisible == 1 && blocks.is_empty() && objects.is_empty() {
return None;
@@ -1102,9 +1107,18 @@ pub(crate) fn apply_anno(d: &mut cadcraft_doc::Drawing, p: AnnoPayload) {
scales.push(s);
}
}
// Each move once, for a scale the object keeps, by a finite offset.
let mut moves: Vec<cadcraft_doc::AnnoMove> = Vec::new();
for m in o.moves.into_iter().take(cadcraft_doc::MAX_SCALES) {
let known = scales.iter().any(|s| s.name.eq_ignore_ascii_case(&m.scale));
if known && m.by.is_finite() && !moves.iter().any(|x| x.scale.eq_ignore_ascii_case(&m.scale)) {
moves.push(m);
}
}
store.modify(h, |e| {
if cadcraft_doc::can_be_annotative(&e.kind) {
e.common.anno_scales = scales;
e.common.anno_moves = moves;
}
});
}
+12 -24
View File
@@ -1861,37 +1861,25 @@ fn unknown_handles(d: &Drawing) -> HashSet<String> {
all_entities(d).filter(|e| matches!(e.kind, EntityKind::Unknown(_))).map(|e| e.handle.hex()).collect()
}
/// Render settings (`RENDERSETTINGS`, `MENTALRAYRENDERSETTINGS`, `RAPIDRTRENDERSETTINGS`) store
/// their `AcDbRenderSettings` class version (the first group 90 after that marker) in the form of
/// the file's version: a 2013+ file stores it one higher, and a 2013 file stores a rapid RT one
/// one lower, as acadrust reads and writes them (`write_render_settings_dxf` in acadrust 0.6.6's
/// `io/dxf/writer/section_writer.rs`, and its DWG class-object reader and writer; the test
/// `render_settings_class_version_matches_what_acadrust_writes` fails if the two drift apart). A
/// kept object carries the form of the file it was read from ([`Foreign::version`], not the
/// drawing's `$ACADVER`, which SAVEAS changes); written into a file read as another version, it
/// takes that version's form. The DWG bridge's R2000 text is read as the version the kept objects
/// came from (craft-dwg's `encode_kept_noted`), so there they stay as read (#907, #2471).
///
/// Only that first group 90 is converted, on purpose: the group 90 that starts a kind's own
/// subclass (`AcDbMentalRayRenderSettings`, `AcDbRapidRTRenderSettings`) is that kind's version,
/// stored the same in every file version, and is left as read.
/// Plain RENDERSETTINGS stores its base class version one higher in 2013+ files.
/// Mental ray and rapid RT settings store their base version verbatim in every file version.
/// Use the source of the retained objects, since SAVEAS can change the drawing's header.
pub(crate) fn render_settings_versions(tags: &mut [Tag], source: Option<Version>, declared: Version) {
let Some(source) = source.filter(|s| *s != declared) else { return };
let shift = |rapid: bool, v: Version| if rapid { -i64::from(v == Version::R2013) } else { i64::from(v >= Version::R2013) };
let (mut kind, mut in_base) = (String::new(), false);
let Some(source) = source else { return };
let delta = i64::from(declared >= Version::R2013) - i64::from(source >= Version::R2013);
if delta == 0 {
return;
}
let (mut plain, mut in_base) = (false, false);
for t in tags.iter_mut() {
match t.code {
0 => {
kind = up(&t.str());
plain = t.str().trim().eq_ignore_ascii_case("RENDERSETTINGS");
in_base = false;
}
100 if matches!(kind.as_str(), "RENDERSETTINGS" | "MENTALRAYRENDERSETTINGS" | "RAPIDRTRENDERSETTINGS") => {
in_base = t.str().trim().eq_ignore_ascii_case("AcDbRenderSettings");
}
100 if plain => in_base = t.str().trim().eq_ignore_ascii_case("AcDbRenderSettings"),
90 if in_base => {
let rapid = kind == "RAPIDRTRENDERSETTINGS";
let logical = t.i64().saturating_sub(shift(rapid, source));
*t = Tag::i(90, logical.saturating_add(shift(rapid, declared)));
*t = Tag::i(90, t.i64().saturating_add(delta));
in_base = false;
}
_ => {}

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