Compare commits

...
Author SHA1 Message Date
Dylan M. Taylor 0fcbe92a45 Merge pull request #3841 from storytold/docs/freebsd-15-1-requirement
Document FreeBSD 15.1+ binary requirement
2026-12-04 09:48:35 -05:00
Dylan M. Taylor 7adf543923 Document FreeBSD 15.1 requirement for prebuilt archives 2026-12-04 09:08:31 -05: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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
Co-authored-by: FredApps <[email protected]>
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 <[email protected]>
Co-authored-by: FredApps <[email protected]>
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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Docs: SELECTIONANNODISPLAY in the annotative scaling and selection rows

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* 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 <[email protected]>

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

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

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

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* fmt: dxf_anno's craft_dxf import in order

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fmt: dxf_anno's craft_dxf import in order

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* 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 <[email protected]>

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

---------

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
Co-authored-by: FredApps <[email protected]>
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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
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 <[email protected]>
Co-authored-by: FredApps <[email protected]>
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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* 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 <[email protected]>

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: austin62jake <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
Co-authored-by: FredApps <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 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 0be750a98a Reconcile the shared dependency repin with current CADCraft main 2026-12-04 03:58:29 +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
118 changed files with 6691 additions and 557 deletions
+3 -2
View File
@@ -32,8 +32,8 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/zh_shared.tsv` | @V1dalTheAbidal | [craft-i18n #444](https://github.com/storytold/craft-i18n/pull/444), [pinned Simplified Chinese CADCraft catalog](https://github.com/storytold/craft-i18n/blob/9fa32aecf2759cd61bb216a958df68da619798f3/locales/zh-hans/cadcraft.tsv#L201) | MIT OR Apache-2.0 | Exact generated one-row projection for offline builds; AI-assisted, not native-speaker reviewed. |
| `vendor/wgpu-hal/` | wgpu developers; Metal language probe by CADCraft contributors | [wgpu-hal 30.0.1](https://crates.io/crates/wgpu-hal/30.0.1) ([gfx-rs/wgpu 40f4a34e](https://github.com/gfx-rs/wgpu/tree/40f4a34ebaf56f9a046231f54125ad046239d3f3/wgpu-hal)), same patch as [storytold/craft-anything vendor/wgpu-hal](https://github.com/storytold/craft-anything/tree/6c7d1f07f9f33643714bd203e1e004f04481f28e/vendor/wgpu-hal) | MIT OR Apache-2.0 | Graphics dependency, patched in `src/metal/adapter.rs` only (#1631); see `vendor/wgpu-hal/CADCRAFT.md`. |
| `licenses/jpeg-encoder-0.6.1/` | jpeg-encoder contributors and Independent JPEG Group | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1) | (MIT OR Apache-2.0) AND IJG | Dependency license and SIMD notices; source hashes in SOURCE.json. |
| `licenses/dwg/acadrust-MPL-2.0.txt` | acadrust contributors | [acadrust 0.6.6](https://crates.io/crates/acadrust/0.6.6), [hakanaktt/acadrust](https://github.com/hakanaktt/acadrust), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MPL-2.0 | DWG read/write dependency, used unmodified through craft-dwg. Full licence text is also in NOTICE. |
| `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | Albert Domenech (ACadSharp) and acadrust contributors | [ACadSharp](https://github.com/DomCR/ACadSharp), via [acadrust 0.6.6 third-party notices](https://github.com/hakanaktt/acadrust/blob/v0.6.6/THIRD_PARTY_NOTICES.md), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MIT (ACadSharp, via acadrust) | Upstream notice for MIT code ported into acadrust's DWG reader and writer. Full text is also in NOTICE. |
| `licenses/dwg/acadrust-MPL-2.0.txt` | acadrust contributors | [acadrust 0.6.9](https://github.com/storytold/acadrust/blob/468b9d8e317755209020d5d3f2f1c8a76210c47f/LICENSE) | MPL-2.0 | DWG read/write dependency, used unmodified through craft-dwg. Full licence text is also in NOTICE. |
| `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | Albert Domenech (ACadSharp) and acadrust contributors | [ACadSharp](https://github.com/DomCR/ACadSharp), via [acadrust 0.6.9 third-party notices](https://github.com/storytold/acadrust/blob/468b9d8e317755209020d5d3f2f1c8a76210c47f/THIRD_PARTY_NOTICES.md) | MIT (ACadSharp, via acadrust) | Upstream notice for MIT code ported into acadrust's DWG reader and writer. Full text is also in NOTICE. |
| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 173cc737](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full monochrome fallback. Registered by the production default font definitions; dependency assets unmodified here, no font file copied into this repository. |
| `krilla 0.8.2 / icc/sGrey-v2-magic.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v2-magic.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v2-magic.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `4110169287e5f1b5149ca9f1da1814d32943905bba8030e849d1a3b729a19481`. |
| `krilla 0.8.2 / icc/sGrey-v4.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v4.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v4.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `00c0f94e09127520a17dc0e1d9264b5702081d96dbdb1549ee88e3631ce42a9d`. |
@@ -89,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
+303 -135
View File
File diff suppressed because it is too large Load Diff
+40 -40
View File
@@ -16,12 +16,12 @@ repository = "https://github.com/storytold/cadcraft"
# internal
cadcraft-geom = { path = "crates/geom" }
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "8945bdb09b36245a1d442438ce8876377ef430d0" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
cadcraft-color = { path = "crates/color" }
cadcraft-doc = { path = "crates/doc" }
cadcraft-constraints = { path = "crates/constraints" }
@@ -31,24 +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 = "8fa4db64a9bb943520259ea95331a303ba788f21" }
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 = "8fa4db64a9bb943520259ea95331a303ba788f21" }
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"] }
@@ -82,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 }
@@ -98,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 }
@@ -130,27 +130,27 @@ debug = 0
# PDF backends for craft-pdf: pinned to the same reviewed craft-libs revision as craft-pdf itself
# (Cargo ignores dependency-local patches).
[patch.crates-io]
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
# wgpu-hal that picks a Metal language version the system compiler accepts, not the OS's alone
# (#1631; upstream gfx-rs/wgpu#10687). See vendor/wgpu-hal/CADCRAFT.md for when to remove it.
wgpu-hal = { path = "vendor/wgpu-hal" }
# Keep the complete egui family and native event bridge on reviewed fork commits.
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
winit = { git = "https://github.com/storytold/winit.git", rev = "3fd7ae64762f82a73b78bd24f453f82c4291067d" }
+10 -12
View File
@@ -10,11 +10,10 @@ docs/brand/LICENSE-brand.txt.
Third-party material
Software dependencies are listed in Cargo.lock. One is under a weak-copyleft licence: the acadrust
crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) 0.6.6 is licensed under the
Mozilla Public License 2.0 and is used unmodified as a separate library via craft-dwg. Its source
is available from crates.io and the repository above. The licence text and upstream third-party
notices are retained in licenses/dwg/, copied verbatim from craft-libs at
8fa4db64a9bb943520259ea95331a303ba788f21, the revision this repository pins.
crate (DWG reading and writing) 0.6.9 is licensed under the Mozilla Public License 2.0
and is used as a separate library via craft-dwg. Its source is available at
https://github.com/storytold/acadrust/tree/468b9d8e317755209020d5d3f2f1c8a76210c47f. The licence text and
upstream third-party notices are retained in licenses/dwg/.
acadrust's DWG reader and writer include code ported and adapted from ACadSharp
(https://github.com/DomCR/ACadSharp), Copyright (c) 2021 Albert Domenech, under the MIT License.
@@ -432,13 +431,12 @@ SOFTWARE.
## DWG Format References
DWG field layouts and version behavior are based on the Open Design Alliance (ODA) DWG
specification and reverse engineering, including comparison with drawings produced by CAD
applications. LibreDWG is used as a secondary cross-check for selected field names and
layouts. The Reed-Solomon tests cite numeric reference values from LibreDWG's
`src/reedsolomon.c` to validate the Rust implementation; those values are test data, not
translated routines. The repository history and source review found no LibreDWG routines
ported into the implementation. The source comments identify the specific cross-checks.
The Open Design Alliance (ODA) DWG specification is the primary published reference for
the binary layouts documented by this project. Where the specification is incomplete or
ambiguous, implementation details are checked against native DWG files produced by CAD
applications. Source comments and regression tests identify the evidence used for each
layout and behavior. ACadSharp remains the attributed origin of the existing reader and
writer code described above.
CADCraft's icons, drafting font, hatch patterns and linetypes are drawn or defined in code.
+4 -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
@@ -412,6 +412,9 @@ instead. `CADCRAFT_TITLEBAR=app` or `CADCRAFT_TITLEBAR=system` overrides the det
### FreeBSD
Prebuilt FreeBSD archives require FreeBSD 15.1 or later. They are built against
FreeBSD 15.1-STABLE; older FreeBSD releases are not supported by these binaries.
| Build | File |
|---|---|
| x86_64 | `cadcraft-<ver>-freebsd-x86_64.tar.gz` |
+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 }
+1 -1
View File
@@ -61,7 +61,7 @@ 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"] }
+41
View File
@@ -233,6 +233,39 @@ pub fn anno_draw(e: &Entity, view: f64, all_visible: bool) -> AnnoDraw {
}
}
/// `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 {
@@ -346,6 +379,14 @@ impl Drawing {
_ => 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 {
+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"))]));
}
+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."),
},
+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) {
+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
+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,
}
+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()),
}
}
+4
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(),
@@ -9,6 +9,8 @@
pub const FILES: &[&str] = &[
"-hatch",
"-linetype",
"-pagesetup",
"-plot",
"-plottermanager",
"-wblock",
"-xref",
+8
View File
@@ -20,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;
@@ -63,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;
+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)),
+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;
+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)),
+31
View File
@@ -2,6 +2,7 @@
mod temp_dir;
mod acadver;
mod aliases;
mod angle_prompts;
mod angle_settings;
mod annotate_options;
@@ -14,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;
@@ -22,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;
@@ -33,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;
@@ -50,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;
@@ -73,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;
@@ -100,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;
@@ -107,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;
@@ -136,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;
@@ -158,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;
@@ -174,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;
@@ -204,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;
@@ -215,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);
}
}
+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;
}
_ => {}
+25 -8
View File
@@ -48,6 +48,7 @@ struct BlockProps {
/// Handle maps and references gathered while reading.
#[derive(Default)]
struct Rx {
from_dwg: bool,
/// STYLE record handle (upper case) → text style name.
styles: HashMap<String, String>,
/// BLOCK_RECORD handle (upper case) → block name.
@@ -177,7 +178,12 @@ fn draw_kept_dimensions_from_their_blocks(d: &mut Drawing) {
/// Read a DXF file into a drawing.
pub fn read(bytes: &[u8]) -> Result<Drawing> {
read_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS, None)
read_with_origin(bytes, false)
}
/// The DWG bridge emits explicit viewport defaults that are absent from its source.
pub(super) fn read_with_origin(bytes: &[u8], from_dwg: bool) -> Result<Drawing> {
read_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS, None, from_dwg)
}
/// A block definition read from BLOCKS: name, base point, description, entities (owner, paper
@@ -191,7 +197,13 @@ type LayoutDef = (String, u32, String, PageSetup, Option<(Vec2, Vec2)>, Option<i
/// Import DXF sections while sharing one materialized-table-cell budget and one hatch curve-point
/// budget across blocks and entity sections. `entities_refused_past` is for tests (see `Rx`).
fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize, entities_refused_past: Option<usize>) -> Result<Drawing> {
fn read_budgeted(
bytes: &[u8],
mut table_cells_left: usize,
curve_points: usize,
entities_refused_past: Option<usize>,
from_dwg: bool,
) -> Result<Drawing> {
let tags = craft_dxf::parse(bytes).map_err(|e| IoError::Format(e.to_string()))?;
let secs = section_slices(&tags);
if secs.is_empty() {
@@ -201,8 +213,13 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize,
d.layouts.clear();
// A file without $INSUNITS declares no units (#1209); only new drawings take the template's.
d.header.set_i64("INSUNITS", 0);
let mut rx =
Rx { pstyles: plot_style_names(&secs), curves: hatch::CurvePoints { left: curve_points, cut: 0 }, entities_refused_past, ..Rx::default() };
let mut rx = Rx {
pstyles: plot_style_names(&secs),
curves: hatch::CurvePoints { left: curve_points, cut: 0 },
entities_refused_past,
from_dwg,
..Rx::default()
};
let mut blocks: Vec<BlockDef> = Vec::new();
let mut layout_objs: Vec<LayoutDef> = Vec::new();
let mut entities = Vec::new();
@@ -426,7 +443,7 @@ mod table_budget_tests {
let dxf = format!(
"0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\nTEST\n10\n0\n20\n0\n{table}0\nENDBLK\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n{table}0\nENDSEC\n0\nSECTION\n2\nENTITIES\n{table}0\nENDSEC\n0\nEOF\n"
);
let d = read_budgeted(dxf.as_bytes(), 2, hatch::MAX_READ_CURVE_POINTS, None).unwrap();
let d = read_budgeted(dxf.as_bytes(), 2, hatch::MAX_READ_CURVE_POINTS, None, false).unwrap();
let block = d.block("TEST").unwrap();
let count = |e: &Entity| match &e.kind {
EntityKind::Table(t) => t.cells.iter().map(Vec::len).sum::<usize>(),
@@ -470,10 +487,10 @@ mod hatch_budget_tests {
#[test]
fn hatch_curves_stop_at_the_read_budget_and_say_so() {
let dxf = format!("0\nSECTION\n2\nENTITIES\n{}{}0\nENDSEC\n0\nEOF\n", spline_hatch(10), spline_hatch(10));
let full = read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, None).unwrap();
let full = read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, None, false).unwrap();
assert!(full.read_notes.is_empty(), "{:?}", full.read_notes);
assert!(hatch_points(&full) > 20_000, "{}", hatch_points(&full));
let d = read_budgeted(dxf.as_bytes(), 4_000_000, 1000, None).unwrap();
let d = read_budgeted(dxf.as_bytes(), 4_000_000, 1000, None, false).unwrap();
// The budget is checked before each edge: the last one sampled may pass it by its own
// points (at most about 4,000); every edge after it is its four control points.
assert!(hatch_points(&d) <= 1000 + 4001 + 20 * 4, "{}", hatch_points(&d));
@@ -604,7 +621,7 @@ mod entity_list_tests {
let block = |name: &str| format!("0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\n{name}\n10\n0\n20\n0\n{lines}0\nENDBLK\n0\nENDSEC\n0\nEOF\n");
let files = [format!("0\nSECTION\n2\nENTITIES\n{lines}0\nENDSEC\n0\nEOF\n"), block("*Model_Space"), block("*Paper_Space"), block("B")];
for dxf in &files {
let open = |refused_past| read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, refused_past);
let open = |refused_past| read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, refused_past, false);
let d = open(Some(3)).unwrap();
let in_layouts: usize = d.layouts.iter().map(|l| l.entities.len()).sum();
assert_eq!(d.model.len() + in_layouts + d.block("B").map_or(0, |b| b.entities.len()), 3, "{dxf}");
+1 -1
View File
@@ -143,7 +143,7 @@ pub(super) fn parse_entities(
if kind == "VIEWPORT" && crate::dxf_ext::is_paper_view(tags) {
rx.paper_views_dropped.push((owner.clone(), paper, rx.block.clone()));
}
let mut kindent = entity_with_table_budget(kind, tags, table_cells_left, &mut rx.curves);
let mut kindent = entity_with_table_budget(kind, tags, table_cells_left, &mut rx.curves, rx.from_dwg);
if let Some((c, _)) = kindent.as_mut()
&& let Some(n) = entity_plot_style(tags, rx)
{
+15 -4
View File
@@ -117,7 +117,7 @@ fn viewport_ucs(tags: &[Tag]) -> Option<ViewportUcs> {
/// A VIEWPORT's groups CADCraft doesn't model, as read ([`VIEWPORT_NOT_EXTRA`]), plus those of
/// CADCraft's xdata copy that the record lacks (a DWG drops some).
fn viewport_extra(tags: &[Tag]) -> Vec<RawTag> {
fn viewport_extra(tags: &[Tag], from_dwg: bool) -> Vec<RawTag> {
// Only groups that can stand inside the AcDbViewport subclass: no record start (0), handle (5,
// 105), subclass (100), group brace (102) or xdata (1000 on), which written back would break
// the record or give it a second handle.
@@ -137,7 +137,17 @@ fn viewport_extra(tags: &[Tag]) -> Vec<RawTag> {
out.push(RawTag { code, value });
}
}
let keep: Vec<bool> = out.iter().map(|t| !at_default(&out, t.code, &t.value)).collect();
// The DWG bridge writes an empty style sheet and UCS-at-origin 0 even for a viewport
// without its own UCS. Keep nonempty styles and nondefault UCS-icon settings.
let no_ucs = viewport_ucs(tags).is_none();
let keep: Vec<bool> = out
.iter()
.map(|t| {
!at_default(&out, t.code, &t.value)
&& !(from_dwg && t.code == 1 && t.value.is_empty())
&& !(from_dwg && no_ucs && t.code == 74 && t.value.trim().parse::<i32>().ok() == Some(0))
})
.collect();
let mut keep = keep.into_iter();
out.retain(|_| keep.next().unwrap_or(true));
out
@@ -145,7 +155,7 @@ fn viewport_extra(tags: &[Tag]) -> Vec<RawTag> {
/// Parse one entity record. POLYLINE/INSERT followers are handled by the caller.
pub(super) fn entity(kind: &str, tags: &[Tag]) -> Option<(Common, EntityKind)> {
entity_with_table_budget(kind, tags, &mut 4_000_000, &mut CurvePoints::default())
entity_with_table_budget(kind, tags, &mut 4_000_000, &mut CurvePoints::default(), false)
}
/// Parse one entity while charging materialized table cells to the caller's shared import budget.
@@ -286,6 +296,7 @@ pub(super) fn entity_with_table_budget(
tags: &[Tag],
table_cells_left: &mut usize,
curves: &mut CurvePoints,
from_dwg: bool,
) -> Option<(Common, EntityKind)> {
// The paper-space viewport our writer adds (dxf_write::paper_view) stays implicit.
if kind == "VIEWPORT" && crate::dxf_ext::is_paper_view(tags) {
@@ -493,7 +504,7 @@ pub(super) fn entity_with_table_budget(
twist,
ucs: viewport_ucs(tags),
ucs_per_viewport: t.i(71) == Some(1),
extra: viewport_extra(tags),
extra: viewport_extra(tags, from_dwg),
}
}),
"WIPEOUT" => {
+12 -2
View File
@@ -215,12 +215,22 @@ fn circular_edge(tags: &[Tag], index: &mut usize, vertices: &mut Vec<PolyVertex>
/// as the edge has groups.
const COARSE_ELLIPSE_POINTS: u32 = 8;
/// HATCH groups 50/51 are circular ray angles; an ellipse uses eccentric parameters.
/// Keep the same revolution so full turns and negative angles retain their sweep.
fn ellipse_parameter(angle: f64, ratio: f64) -> f64 {
if ratio == 1.0 || !(ratio > 0.0 && ratio.is_finite() && angle.is_finite()) {
return angle;
}
let param = angle.sin().atan2(ratio * angle.cos());
param + ((angle - param) / std::f64::consts::TAU).round() * std::f64::consts::TAU
}
fn elliptic_edge(tags: &[Tag], index: &mut usize, vertices: &mut Vec<PolyVertex>, budget: &mut EdgeBudget) {
let center = Vec2::new(edge_value(tags, *index), edge_value(tags, *index + 1));
let major = Vec2::new(edge_value(tags, *index + 2), edge_value(tags, *index + 3));
let ratio = edge_value(tags, *index + 4);
let start_angle = edge_value(tags, *index + 5).to_radians();
let end_angle = edge_value(tags, *index + 6).to_radians();
let start_angle = ellipse_parameter(edge_value(tags, *index + 5).to_radians(), ratio);
let end_angle = ellipse_parameter(edge_value(tags, *index + 6).to_radians(), ratio);
let ccw = tags.get(*index + 7).filter(|tag| tag.code == 73).map(Tag::i64).unwrap_or(1) != 0;
*index += 8;
let (start, end) = if ccw { (start_angle, end_angle) } else { (-end_angle, -start_angle) };
+4 -1
View File
@@ -96,11 +96,14 @@ pub(crate) fn read_table_style(name: &str, tags: &[Tag]) -> TableStyle {
i = next;
}
let data_h = blocks.first().and_then(|b| first(140, b)).filter(|h| *h > 0.0);
// A group 280 before the description (3) is the class version. Title suppression
// uses another 280 after it. Older writers sometimes omit the description.
let properties = head.iter().position(|t| t.code == 3).map_or(head, |i| &head[i + 1..]);
let mut st = TableStyle {
name: name.to_string(),
text_height: data_h.unwrap_or(def.text_height),
margin: first(40, head).filter(|m| *m >= 0.0).unwrap_or(def.margin),
title: head.iter().find(|t| t.code == 280).map(Tag::i64).unwrap_or(0) == 0,
title: properties.iter().find(|t| t.code == 280).map(Tag::i64).unwrap_or(0) == 0,
header: head.iter().find(|t| t.code == 281).map(Tag::i64).unwrap_or(0) == 0,
cell_styles: Vec::new(),
};
+3 -7
View File
@@ -2,8 +2,6 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
/// A DWG hatch's elliptic boundary edge angles, in degrees in the DXF the DWG is read through (#3332).
mod dwg_hatch;
/// What a DXF file holds that CADCraft doesn't model, kept and written back (#528).
mod dxf_raw;
@@ -103,9 +101,7 @@ pub fn read(bytes: &[u8], name: impl AsRef<Path>) -> Result<Drawing> {
pub(crate) fn read_source(bytes: &[u8], name: &Path) -> Result<(Drawing, Option<Vec<u8>>)> {
if craft_dwg::is_dwg(bytes) {
let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(dwg_error)?;
// The decoder writes an elliptic hatch edge's angles in radians; DXF keeps degrees.
let dxf = dwg_hatch::elliptic_edge_degrees(dxf);
let mut d = dxf_read::read(&dxf).map_err(|e| IoError::Format(format!("{e} (in the DXF converted from this DWG)")))?;
let mut d = dxf_read::read_with_origin(&dxf, true).map_err(|e| IoError::Format(format!("{e} (in the DXF converted from this DWG)")))?;
d.read_notes = notes.into_iter().map(|note| cadcraft_dwg_message(&note)).collect();
return Ok((d, Some(dxf)));
}
@@ -136,8 +132,8 @@ pub fn write_with(d: &Drawing, name: impl AsRef<Path>, opts: &SaveOptions) -> Re
// Before 2007 the text is in the code page the header declares.
let code_page = dxf_write::code_page(d, version);
Ok(match (opts.binary, version.utf8()) {
(true, true) => craft_dxf::write_binary(&tags, true),
(true, false) => craft_dxf::write_binary_in(&tags, &code_page),
(true, true) => craft_dxf::write_binary(&tags, true).map_err(|e| IoError::Format(e.to_string()))?,
(true, false) => craft_dxf::write_binary_in(&tags, &code_page).map_err(|e| IoError::Format(e.to_string()))?,
(false, true) => craft_dxf::write_ascii_as(&tags, true).into_bytes(),
(false, false) => craft_dxf::write_ascii_in(&tags, &code_page),
})
+14 -3
View File
@@ -1,6 +1,6 @@
//! A hatch boundary stored in a DWG as an elliptic edge keeps its sweep: a circle (0 to 2π) stays a
//! circle, so the hatch leaves the hole open. The DWG decoder writes the edge's angles in radians
//! and DXF reads degrees, so the circle used to come out as an arc of 6.28 degrees.
//! circle, so the hatch leaves the hole open. The DWG decoder used to write the edge's angles in radians
//! while DXF reads degrees, so the circle came out as an arc of 6.28 degrees.
// The DWG bridge is unavailable on wasm and FreeBSD ARM64 (#2526); DXF still works.
#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
@@ -16,6 +16,10 @@ fn line(a: (f64, f64), b: (f64, f64)) -> BoundaryEdge {
/// A DWG with a pattern hatch over a 100 x 100 square with a round hole of radius 10 stored as an
/// elliptic edge from `start` to `end` radians.
fn dwg_with_hole(start: f64, end: f64) -> Vec<u8> {
dwg_with_elliptic_hole(start, end, 1.0)
}
fn dwg_with_elliptic_hole(start: f64, end: f64, ratio: f64) -> Vec<u8> {
let mut hatch = Hatch::new();
hatch.is_solid = false;
let mut outer = BoundaryPath::new();
@@ -27,7 +31,7 @@ fn dwg_with_hole(start: f64, end: f64) -> Vec<u8> {
hole.edges = vec![BoundaryEdge::EllipticArc(EllipticArcEdge {
center: Vector2::new(50.0, 50.0),
major_axis_endpoint: Vector2::new(-10.0, 0.0),
minor_axis_ratio: 1.0,
minor_axis_ratio: ratio,
start_angle: start,
end_angle: end,
counter_clockwise: true,
@@ -66,3 +70,10 @@ fn a_quarter_arc_stored_as_an_elliptic_edge_keeps_its_quarter() {
// From the point at 0 degrees (60, 50) to the one at 90 degrees (50, 60), closed by a chord: x spans 10.
assert!(max - min > 9.9 && max - min < 10.5, "the arc spans {} in x", max - min);
}
#[test]
fn a_non_circular_elliptic_arc_keeps_its_dwg_endpoints() {
let (min, max) = hole_extent(&dwg_with_elliptic_hole(std::f64::consts::FRAC_PI_4, std::f64::consts::FRAC_PI_2, 0.5));
let expected_min = 50.0 - 10.0 / 2.0_f64.sqrt();
assert!((min - expected_min).abs() < 0.02 && (max - 50.0).abs() < 0.02, "arc x range {min}..{max}");
}
+19
View File
@@ -83,6 +83,25 @@ fn vertices(edges: &[Edge]) -> Vec<PolyVertex> {
loops.into_iter().next().map(|l| l.vertices).unwrap_or_default()
}
/// HATCH ellipse endpoints are circular ray angles, not the ellipse's eccentric parameters.
#[test]
fn a_non_circular_ellipse_edge_uses_ray_angles_in_both_directions() {
let expected = 10.0 / 5.0_f64.sqrt(); // x = y at 45 degrees on x²/100 + y²/25 = 1
let bounds = |l: &HatchLoop| l.vertices.iter().fold((f64::NEG_INFINITY, f64::INFINITY), |(max_x, min_y), v| (max_x.max(v.p.x), min_y.min(v.p.y)));
for (start, end, ccw) in [(45.0, 90.0, true), (270.0, 315.0, false), (405.0, 450.0, true)] {
let edge = Edge::Ellipse([0.0, 0.0], [10.0, 0.0], 0.5, start, end, ccw);
let drawing = cadcraft_io::read(dxf(&[vec![edge]]).as_bytes(), "ellipse.dxf").unwrap();
let loops = loops_of(&drawing);
let (max_x, min_y) = bounds(&loops[0]);
assert!((max_x - expected).abs() < 1e-8 && (min_y - expected).abs() < 1e-8, "{start} {end} {ccw}: {max_x} {min_y}");
// CADCraft writes the sampled contour as a polyline; the geometry survives a DXF save.
let saved = cadcraft_io::write_dxf(&drawing);
let reopened = cadcraft_io::read(saved.as_bytes(), "ellipse.dxf").unwrap();
let (x2, y2) = bounds(&loops_of(&reopened)[0]);
assert!((x2 - max_x).abs() < 1e-6 && (y2 - min_y).abs() < 1e-6);
}
}
/// The same vertices, up to the rounding of points and bulges computed from other stored values.
fn assert_same(got: &[PolyVertex], expected: &[PolyVertex]) {
let same = got.len() == expected.len() && got.iter().zip(expected).all(|(a, b)| a.p.near(b.p, 1e-9) && (a.bulge - b.bulge).abs() < 1e-12);
+11 -6
View File
@@ -5,20 +5,25 @@
use cadcraft_doc::EntityKind;
/// Stand-in OLE data as a DWG carries it: a two-byte marker, the frame's four corners (upper
/// left, upper right, lower right, lower left; x, y, z doubles), then the object's bytes, here
/// opaque text long enough to take several 310 groups.
/// A saved-layout OLE frame header followed by opaque stand-in object bytes, long enough to
/// take several 310 groups. The payload is not claimed to be a valid compound file.
fn payload() -> Vec<u8> {
let mut data = vec![0x80, 0x00];
let mut data = 0x5580u16.to_le_bytes().to_vec();
for [x, y] in [[10.0f64, 40.0], [70.0, 40.0], [70.0, 5.0], [10.0, 5.0]] {
for v in [x, y, 0.0] {
data.extend_from_slice(&v.to_le_bytes());
}
}
let mut extension = [0u8; 26];
extension[16..20].copy_from_slice(&1u32.to_le_bytes()); // embedded object
data.extend_from_slice(&extension);
let mut object = vec![];
for i in 0..12u8 {
data.extend_from_slice(b"synthetic embedded object ");
data.push(i);
object.extend_from_slice(b"synthetic embedded object ");
object.push(i);
}
data.extend_from_slice(&(object.len() as u32).to_le_bytes());
data.extend_from_slice(&object);
data
}
+5 -1
View File
@@ -12,12 +12,16 @@ const LR: (f64, f64) = (35.27, -22.39);
/// The OLE data: the envelope with the frame's corners.
fn blob() -> Vec<u8> {
let mut b = vec![1u8, 0];
let mut b = 0x5580u16.to_le_bytes().to_vec();
for (x, y) in [UL, (LR.0, UL.1), LR, (UL.0, LR.1)] {
for v in [x, y, 0.0] {
b.extend_from_slice(&v.to_le_bytes());
}
}
let mut extension = [0u8; 26];
extension[16..20].copy_from_slice(&1u32.to_le_bytes()); // embedded object
b.extend_from_slice(&extension);
b.extend_from_slice(&0u32.to_le_bytes()); // no compound-file bytes
b
}
+9 -15
View File
@@ -1,10 +1,5 @@
//! Render settings store their `AcDbRenderSettings` class version in the form of the file's
//! version: a 2013+ file stores it one higher (a 2013 file stores a rapid RT one one lower), as
//! acadrust reads and writes them. A kept object carries the form of the file it came from; written
//! into a file declaring another version, it takes that version's form. The DWG bridge is an R2000
//! DXF for a 2018 DWG: without this, a 2018 drawing's MENTALRAYRENDERSETTINGS went in with the 2018
//! form, the DWG writer raised it once more, and BricsCAD refused the DWG ("Object improperly
//! read", #907).
//! Plain render settings use a version-specific base class version. Mental ray and rapid RT
//! settings keep their stored value across both DXF and DWG versions (#907, #2471).
use cadcraft_io::{SaveOptions, Version};
@@ -50,7 +45,7 @@ fn written(d: &cadcraft_doc::Drawing, version: Version) -> String {
#[test]
fn render_settings_class_version_takes_the_declared_versions_form() {
let kind = "MENTALRAYRENDERSETTINGS";
let kind = "RENDERSETTINGS";
// From a 2018 file (stored 2 = class version 1 in the 2013+ form).
let d = cadcraft_io::read_dxf(dxf("AC1032", kind, 2).as_bytes()).unwrap();
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2), "same version: as read");
@@ -61,19 +56,19 @@ fn render_settings_class_version_takes_the_declared_versions_form() {
let d = cadcraft_io::read_dxf(dxf("AC1015", kind, 1).as_bytes()).unwrap();
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1));
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2));
// Rapid RT settings: the 2013 file alone stores one lower.
// Rapid RT keeps the stored base class version across file versions.
let kind = "RAPIDRTRENDERSETTINGS";
let d = cadcraft_io::read_dxf(dxf("AC1027", kind, 1).as_bytes()).unwrap();
assert_eq!(class_version(&written(&d, Version::R2013), kind), Some(1));
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2));
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(2));
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(1));
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1));
}
/// A file that declares no `$ACADVER` gives no source form: its kept objects are written as read,
/// not as if the new drawing's 2018 were their form.
#[test]
fn render_settings_without_a_declared_version_are_written_as_read() {
let kind = "MENTALRAYRENDERSETTINGS";
let kind = "RENDERSETTINGS";
let text = dxf("AC1032", kind, 1).replace("9\n$ACADVER\n1\nAC1032\n", "");
assert!(!text.contains("$ACADVER"));
let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
@@ -110,8 +105,7 @@ fn render_settings_class_version_matches_what_acadrust_writes() {
(DxfVersion::AC1027, Version::R2013),
(DxfVersion::AC1032, Version::R2018),
];
// As a 2018 file stores them: mental ray one higher than its class version, rapid RT as is.
for (kind, stored) in [("MENTALRAYRENDERSETTINGS", 2), ("RAPIDRTRENDERSETTINGS", 2)] {
for (kind, stored) in [("RENDERSETTINGS", 2), ("MENTALRAYRENDERSETTINGS", 2), ("RAPIDRTRENDERSETTINGS", 2)] {
let source = std::io::Cursor::new(dxf("AC1032", kind, stored).into_bytes());
let mut doc = acadrust::DxfReader::from_reader(source).unwrap().read().unwrap();
let by_acadrust: Vec<(Version, String)> = versions
@@ -122,7 +116,7 @@ fn render_settings_class_version_matches_what_acadrust_writes() {
})
.collect();
let forms: Vec<Option<i64>> = by_acadrust.iter().map(|(_, text)| class_version(text, kind)).collect();
let expected = if kind == "RAPIDRTRENDERSETTINGS" { [2, 2, 1, 2] } else { [1, 1, 2, 2] };
let expected = if kind == "RENDERSETTINGS" { [1, 1, 2, 2] } else { [2, 2, 2, 2] };
assert_eq!(forms, expected.map(Some), "{kind}: acadrust's own forms for 2000, 2010, 2013, 2018");
for (read_from, text) in &by_acadrust {
let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
+26 -12
View File
@@ -1,5 +1,5 @@
//! Shared preservation assertions for ordered entities, authored blocks and referenced tables.
//! Every field of the explicitly supported entities is checked; converted angles alone allow
//! Every field of the explicitly supported entities is checked; converted angles and interpolated spline controls allow
//! floating-point roundoff, never wrapping or geometric approximation. Blocks are visited once
//! as stored definitions, not recursively expanded, so cyclic references remain bounded.
//! Header defaults, generated objects and other drawing collections are outside this slice.
@@ -12,8 +12,7 @@ fn equal<T: PartialEq + Debug>(expected: &T, actual: &T, context: &str, field: &
assert_eq!(actual, expected, "{context}.{field}");
}
fn angle(expected: f64, actual: f64, context: &str, field: &str) {
// Two floating-point unit conversions, not a geometric approximation or angle wrapping.
fn roundoff(expected: f64, actual: f64, context: &str, field: &str) {
let tolerance = 8.0 * f64::EPSILON * expected.abs().max(1.0);
assert!(
expected.is_finite() && actual.is_finite() && (actual - expected).abs() <= tolerance,
@@ -144,7 +143,7 @@ fn linetype(expected: Option<&cadcraft_doc::Linetype>, actual: Option<&cadcraft_
equal(shape, &b.shape, &path, "shape");
equal(style, &b.style, &path, "style");
equal(scale, &b.scale, &path, "scale");
angle(*rotation, b.rotation, &path, "rotation");
roundoff(*rotation, b.rotation, &path, "rotation");
equal(offset, &b.offset, &path, "offset");
equal(absolute, &b.absolute, &path, "absolute");
}
@@ -167,8 +166,23 @@ fn entity(expected: &Entity, actual: &Entity, context: &str) {
(EntityKind::Arc(Arc { center, radius, start, end }), EntityKind::Arc(b)) => {
equal(center, &b.center, context, "arc.center");
equal(radius, &b.radius, context, "arc.radius");
angle(*start, b.start, context, "arc.start");
angle(*end, b.end, context, "arc.end");
roundoff(*start, b.start, context, "arc.start");
roundoff(*end, b.end, context, "arc.end");
}
(EntityKind::Spline(a), EntityKind::Spline(b)) if !a.fit.is_empty() => {
// DWG stores the fit points. The decoder interpolates the cubic controls for DXF.
let cadcraft_geom::Spline { degree, knots, control, weights, fit, closed, fit_opts } = a;
equal(degree, &b.degree, context, "spline.degree");
equal(knots, &b.knots, context, "spline.knots");
equal(weights, &b.weights, context, "spline.weights");
equal(fit, &b.fit, context, "spline.fit");
equal(closed, &b.closed, context, "spline.closed");
equal(fit_opts, &b.fit_opts, context, "spline.fit_opts");
equal(&control.len(), &b.control.len(), context, "spline.control.len");
for (p, q) in control.iter().zip(&b.control) {
roundoff(p.x, q.x, context, "spline.control.x");
roundoff(p.y, q.y, context, "spline.control.y");
}
}
(EntityKind::MText(a), EntityKind::MText(b)) => mtext(a, b, context),
(EntityKind::AttDef(a), EntityKind::AttDef(b)) => attrib(a, b, context),
@@ -240,9 +254,9 @@ fn text(expected: &Text, actual: &Text, context: &str) {
equal(align_pt, &actual.align_pt, context, "align_pt");
equal(height, &actual.height, context, "height");
equal(value, &actual.value, context, "value");
angle(*rotation, actual.rotation, context, "rotation");
roundoff(*rotation, actual.rotation, context, "rotation");
equal(width_factor, &actual.width_factor, context, "width_factor");
angle(*oblique, actual.oblique, context, "oblique");
roundoff(*oblique, actual.oblique, context, "oblique");
equal(style, &actual.style, context, "style");
equal(halign, &actual.halign, context, "halign");
equal(valign, &actual.valign, context, "valign");
@@ -256,7 +270,7 @@ fn mtext(expected: &MText, actual: &MText, context: &str) {
equal(height, &actual.height, context, "mtext.height");
equal(width, &actual.width, context, "mtext.width");
equal(attach, &actual.attach, context, "mtext.attach");
angle(*rotation, actual.rotation, context, "mtext.rotation");
roundoff(*rotation, actual.rotation, context, "mtext.rotation");
equal(style, &actual.style, context, "mtext.style");
equal(contents, &actual.contents, context, "mtext.contents");
equal(line_spacing, &actual.line_spacing, context, "mtext.line_spacing");
@@ -288,7 +302,7 @@ fn insert(expected: &Insert, actual: &Insert, context: &str) {
equal(block, &actual.block, context, "insert.block");
equal(insert, &actual.insert, context, "insert.insert");
equal(scale, &actual.scale, context, "insert.scale");
angle(*rotation, actual.rotation, context, "insert.rotation");
roundoff(*rotation, actual.rotation, context, "insert.rotation");
equal(cols, &actual.cols, context, "insert.cols");
equal(rows, &actual.rows, context, "insert.rows");
equal(col_spacing, &actual.col_spacing, context, "insert.col_spacing");
@@ -389,9 +403,9 @@ fn comparison_rejects_block_and_attribute_dependency_losses() {
#[test]
fn angle_tolerance_does_not_hide_real_changes_or_nonfinite_values() {
angle(0.7, 0.7_f64.to_degrees().to_radians(), "self-test", "angle");
roundoff(0.7, 0.7_f64.to_degrees().to_radians(), "self-test", "angle");
for actual in [0.700001, f64::NAN, f64::INFINITY] {
assert!(std::panic::catch_unwind(|| angle(0.7, actual, "self-test", "angle")).is_err());
assert!(std::panic::catch_unwind(|| roundoff(0.7, actual, "self-test", "angle")).is_err());
}
}
+21 -1
View File
@@ -375,7 +375,27 @@ fn layer_states() {
}
#[test]
fn layouts_and_paperspace() {
collection(collections::layouts(), collections::assert_layouts);
let case = collections::layouts();
for version in Version::ALL {
let mut expected = case.drawing.clone();
if version >= Version::R2007 {
// DWG stores effective viewport lighting from R2007 onward. Preserve it for DXF export.
for layout in expected.layouts.iter_mut() {
let handles: Vec<_> = layout.entities.iter().map(|e| e.handle).collect();
for handle in handles {
layout.entities.modify(handle, |e| {
if let cadcraft_doc::EntityKind::Viewport(v) = &mut e.kind {
v.extra = [(292, "1"), (282, "1"), (141, "0.0"), (142, "0.0")]
.into_iter()
.map(|(code, value)| cadcraft_doc::RawTag { code, value: value.into() })
.collect();
}
});
}
}
}
super::check_version_with(&case.name, &case.drawing, &expected, version, collections::assert_layouts);
}
}
fn with_dimension_styles(cases: Vec<Case>) {
+78 -3
View File
@@ -395,9 +395,69 @@ fn hostile_viewport_ucs_groups_do_not_panic() {
assert_eq!((u.x_axis, u.y_axis), (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)));
}
#[test]
fn a_viewport_keeps_its_nondefault_style_sheet_and_ucs_icon_origin() {
let (d, h) = base();
let text = cadcraft_io::write_dxf(&d);
let groups = [(1, "monochrome.ctb".into()), (74, "1".into())];
let back = cadcraft_io::read_dxf(inject(&text, h, &groups).as_bytes()).unwrap();
let (_, viewport) = the_viewport(&back);
assert!(viewport.extra.iter().any(|t| t.code == 1 && t.value == "monochrome.ctb"));
assert!(viewport.extra.iter().any(|t| t.code == 74 && t.value == "1"));
}
/// An explicit 282=1 selects two lights. A DXF consumer can interpret an omitted 282
/// as one light; keep the authored groups even when they match DWG-generated values.
#[test]
fn explicit_dxf_lighting_survives_save_and_reopen() {
let (d, h) = base();
let text = cadcraft_io::write_dxf(&d);
for (enabled, brightness, ambient) in [("1", "0.0", false), ("0", "0.0", false), ("1", "0.25", false), ("1", "0.0", true)] {
let mut groups = vec![(292, enabled.into()), (282, "1".into()), (141, brightness.into()), (142, "0.0".into())];
if ambient {
groups.push((63, "250".into()));
}
let drawing = cadcraft_io::read_dxf(inject(&text, h, &groups).as_bytes()).unwrap();
let saved = cadcraft_io::write_dxf(&drawing);
let native = viewport_record(&saved, h);
for (code, value) in &groups {
assert_eq!(group(&native, &code.to_string()).and_then(num), num(value), "native DXF viewport group {code}");
}
let back = cadcraft_io::read_dxf(saved.as_bytes()).unwrap();
let (_, viewport) = the_viewport(&back);
for (code, value) in &groups {
assert!(viewport.extra.iter().any(|t| t.code == *code && num(&t.value) == num(value)), "{code}: {:?}", viewport.extra);
}
}
}
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
#[test]
fn dwg_preserves_explicit_viewport_lighting() {
cadcraft_io::dwg_worker::allow_in_process();
let (d, h) = base();
let text = cadcraft_io::write_dxf(&d);
for (enabled, brightness) in [("1", "0.0"), ("0", "0.0"), ("1", "0.25")] {
let groups = [(292, enabled.into()), (282, "1".into()), (141, brightness.into()), (142, "0.0".into())];
let drawing = cadcraft_io::read_dxf(inject(&text, h, &groups).as_bytes()).unwrap();
let bytes = cadcraft_io::write_with(
&drawing,
"lighting.dwg",
&cadcraft_io::SaveOptions { version: Some(cadcraft_io::Version::R2010), binary: false },
)
.unwrap();
let back = cadcraft_io::read(&bytes, "lighting.dwg").unwrap();
let (_, viewport) = the_viewport(&back);
for (code, value) in &groups {
let want = num(value).unwrap();
assert!(viewport.extra.iter().any(|t| t.code == *code && num(&t.value) == Some(want)), "{code}: {:?}", viewport.extra);
}
}
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_default_viewport_reads_back_without_ucs_or_extras() {
fn a_default_dwg_viewport_exports_its_effective_lighting() {
cadcraft_io::dwg_worker::allow_in_process();
for version in [cadcraft_io::Version::R2000, cadcraft_io::Version::R2010] {
let (d, _) = base();
@@ -406,7 +466,17 @@ fn a_default_viewport_reads_back_without_ucs_or_extras() {
let (_, viewport) = the_viewport(&back);
assert!(viewport.ucs.is_none(), "{version}: {:?}", viewport.ucs);
assert!(!viewport.ucs_per_viewport, "{version}");
assert!(viewport.extra.is_empty(), "{version}: {:?}", viewport.extra);
let native = viewport_record(&cadcraft_io::write_dxf(&back), the_viewport(&back).0);
let lighting = [(292, "1"), (282, "1"), (141, "0.0"), (142, "0.0")];
if version >= cadcraft_io::Version::R2007 {
assert_eq!(viewport.extra.len(), lighting.len());
for (code, value) in lighting {
assert_eq!(group(&native, &code.to_string()).and_then(num), num(value), "exported DWG lighting {code}");
}
} else {
assert!(viewport.extra.is_empty(), "{version}: {:?}", viewport.extra);
assert!(group(&native, "282").is_none());
}
}
}
@@ -427,6 +497,11 @@ fn a_viewport_with_non_default_snap_keeps_it() {
for code in [14, 24] {
assert_eq!(viewport.extra.iter().find(|t| t.code == code).and_then(|t| num(&t.value)), Some(2.0), "{version}");
}
assert_eq!(viewport.extra.len(), 2, "only the non-default snap spacing remains: {version}: {:?}", viewport.extra);
let extras = viewport.extra.iter().map(|t| t.code).collect::<Vec<_>>();
let mut expected = vec![14, 24];
if version >= cadcraft_io::Version::R2007 {
expected.extend([292, 282, 141, 142]);
}
assert_eq!(extras, expected, "{version}");
}
}
+11 -2
View File
@@ -65,7 +65,16 @@ fn check(bytes: &[u8], name: &str) -> cadcraft_doc::Drawing {
assert_eq!(proxy.payload.bit_count, 9);
assert_eq!(proxy.payload.data(), [0xA5, 0x80]);
assert_eq!(proxy.graphics.data(), [0x12, 0x34, 0x56]);
let class = classes.get(usize::try_from(proxy.class_id - 500).unwrap()).unwrap();
// The DXF refers to the CLASSES section by ordinal, while the decoder renumbers
// that same proxy against its document class table.
let entities = sections.iter().find(|s| s.name == "ENTITIES").unwrap();
let records = craft_dxf::records(&entities.tags);
let (_, record) = records.iter().find(|(kind, _)| kind == "ACAD_PROXY_ENTITY").unwrap();
let file_id = record.iter().skip_while(|t| t.code != 100 || t.str() != "AcDbProxyEntity").find(|t| t.code == 91).unwrap().i64();
let class = classes.get(usize::try_from(file_id - 500).unwrap()).unwrap();
let decoded_class = decoded.classes.iter().find(|c| i32::from(c.class_number) == proxy.class_id).unwrap();
assert_eq!(decoded_class.dxf_name, "SPDSNOTEPOSITION");
assert_eq!(decoded_class.cpp_class_name, "mcsDbObjectNotePosition");
assert!(class.1.iter().any(|t| t.code == 1 && t.str() == "SPDSNOTEPOSITION"));
assert!(class.1.iter().any(|t| t.code == 2 && t.str() == "mcsDbObjectNotePosition"));
drawing
@@ -121,7 +130,7 @@ fn duplicate_names_keep_distinct_classes_for_entities_and_dictionary_objects() {
cadcraft_io::dwg_worker::allow_in_process();
let source = duplicate_class_dxf();
for binary in [false, true] {
let input = if binary { craft_dxf::write_binary(&craft_dxf::parse(&source).unwrap(), true) } else { source.clone() };
let input = if binary { craft_dxf::write_binary(&craft_dxf::parse(&source).unwrap(), true).unwrap() } else { source.clone() };
let mut drawing = cadcraft_io::read(&input, "source.dxf").unwrap();
for _ in 0..3 {
for name in ["copy.dxf", "copy.dwg"] {
+21 -3
View File
@@ -34,7 +34,7 @@ use dyn_boxes::dynamic_input;
pub(crate) use dyn_boxes::length_units;
use grid::draw_grid;
use grips::{click_grip, draw_selection_grips, grip_at, grip_menu, grip_options};
use list::{OnlyList, PrimIndex, ensure_list, rebuilt_preview};
use list::{AnnoOthers, OnlyList, PrimIndex, draw_anno_others, ensure_list, rebuilt_preview};
#[cfg(test)]
use list::{preview_options, prims_of};
use pick::{edit_text_at, hatch_at, wheel_zoom_points};
@@ -141,6 +141,8 @@ pub struct CanvasState {
/// The selection and hover highlights inside the active MSPACE viewport (see [`VpHighlight`]).
vp_sel: VpHighlight,
vp_hover: VpHighlight,
/// Selected annotative objects at their other scales (see [`AnnoOthers`]).
anno_others: AnnoOthers,
/// The part of the hovered object a running command highlights instead of all of it (see
/// [`HoverPart`]).
hover_part: HoverPart,
@@ -532,6 +534,7 @@ fn paint_content_highlights(frame: &mut CanvasPaint<'_>, bg: Rgb, sel: &[Handle]
if let Some(look) = selection_look
&& !sel.is_empty()
{
draw_anno_others(&mut c.anno_others, &app.session, &clipped, &xf, sel, look);
c.vp_sel.update(st, sel, scale);
let list = &c.vp_sel.list;
let all = || (0..list.prims.len()).collect::<Vec<_>>();
@@ -548,8 +551,20 @@ fn paint_content_highlights(frame: &mut CanvasPaint<'_>, bg: Rgb, sel: &[Handle]
}
}
}
} else if let CanvasState { list: Some(list), list_gen, prim_index, hover, hover_part, gpu, hl_key, hl_slot, hl_origin, hl_infinite, .. } =
&mut app.canvas
} else if let CanvasState {
list: Some(list),
list_gen,
prim_index,
hover,
hover_part,
gpu,
hl_key,
hl_slot,
hl_origin,
hl_infinite,
anno_others,
..
} = &mut app.canvas
{
if let Some(part) = &hover_part.list {
draw_hover_part(painter, &xf, part, t.hover, preview_look);
@@ -559,6 +574,9 @@ fn paint_content_highlights(frame: &mut CanvasPaint<'_>, bg: Rgb, sel: &[Handle]
draw_highlight(painter, &xf, list, &prim_index.prims(*list_gen, list, &[h]), t.hover, preview_look);
}
if let Some(look) = selection_look {
if !sel.is_empty() {
draw_anno_others(anno_others, &app.session, painter, &xf, sel, look);
}
if gpu.is_some() && !sel.is_empty() {
let list_id = *list_gen;
let hl = (hl_key, &*hl_slot, hl_origin, &mut *hl_infinite);
+47 -1
View File
@@ -1,4 +1,5 @@
use super::viewport::{split_viewport, stencil_clip};
use super::draw::{Look, draw_highlight};
use super::viewport::{split_viewport, stencil_clip, viewport_highlight_tolerance};
use super::{Bounds2, CadApp, DisplayList, Handle, ListKey, Rgb, Tokens, Vec2, Xf, rebuild, same_content};
/// Primitives of `list` sorted by entity handle, built on the first highlight after each list
@@ -179,6 +180,51 @@ pub(super) fn ensure_list(app: &mut CadApp, xf: &Xf, views: &[(Bounds2, f64)], c
app.canvas.build_ms = crate::now_ms() - t0;
}
/// The selected annotative objects at their other scales (SELECTIONANNODISPLAY), tessellated in
/// model units from [`cadcraft_engine::Session::selection_anno_others`]; rebuilt only when the
/// drawing, the selection, the setting, the active viewport or the zoom band change.
#[derive(Default)]
pub(super) struct AnnoOthers {
pub(super) key: Option<u64>,
list: DisplayList,
}
impl AnnoOthers {
pub(super) fn update(&mut self, session: &cadcraft_engine::Session, sel: &[Handle], scale: f64) -> &DisplayList {
let tolerance = viewport_highlight_tolerance(scale);
let key = session.state().ok().map(|st| {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
let on = session.settings.selectionannodisplay;
// An unlocked viewport's zoom changes its scale without a new revision.
let vp_scale = st.anno_view().map(f64::to_bits);
(st.uid, st.revision, std::sync::Arc::as_ptr(&st.doc) as usize, tolerance.to_bits(), sel, on, st.mspace, vp_scale).hash(&mut h);
h.finish()
});
if self.key != key {
let others = session.selection_anno_others();
self.list = match session.state() {
Ok(st) if !others.is_empty() => {
cadcraft_render::build_entities(&st.doc, others.iter(), &cadcraft_render::Options { tolerance, ..Default::default() })
}
_ => DisplayList::default(),
};
self.key = key;
}
&self.list
}
}
/// Draw the selected annotative objects' other scales faded (SELECTIONANNODISPLAY), under the
/// selection highlight; `xf` maps model units to the screen.
pub(super) fn draw_anno_others(others: &mut AnnoOthers, session: &cadcraft_engine::Session, p: &egui::Painter, xf: &Xf, sel: &[Handle], look: Look) {
let list = others.update(session, sel, xf.scale);
if !list.prims.is_empty() {
let all: Vec<usize> = (0..list.prims.len()).collect();
draw_highlight(p, xf, list, &all, Tokens::get().selection_faded, Look { width: 1.0, ..look });
}
}
/// The display list of what a running command shows in place of the drawing
/// ([`cadcraft_engine::Session::display_only`]: DVIEW's preview set), rebuilt when the drawing,
/// the set or the 2x zoom band changes.
+27
View File
@@ -28,6 +28,33 @@ fn hs(v: &[u64]) -> Vec<Handle> {
v.iter().map(|&h| Handle(h)).collect()
}
/// Zooming an unlocked viewport (no new revision) changes its scale: the faded other scales
/// of the selection are built again.
#[test]
fn anno_others_follow_a_viewport_zoom() {
use serde_json::json;
let mut s = cadcraft_engine::Session::new();
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
let r = s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap();
let h = r["handle"].as_str().unwrap().to_string();
s.execute("objectscale", &json!({ "handles": [h], "add": "1:50" })).unwrap();
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().unwrap().to_string();
s.execute("viewport.set", &json!({ "handle": vh, "scale": "1:50", "center": [0, 0] })).unwrap();
s.execute("mspace", &json!({ "handle": vh })).unwrap();
s.execute("select", &json!({ "handles": [h] })).unwrap();
let sel = s.selection();
let mut others = AnnoOthers::default();
others.update(&s, &sel, 1.0);
let before = others.key;
let v = s.state().unwrap().view();
s.state_mut().unwrap().set_view_quiet(cadcraft_engine::View { height: v.height / 50.0, ..v });
assert!((s.anno_view().unwrap() - 1.0).abs() < 1e-9, "{:?}", s.anno_view());
others.update(&s, &sel, 1.0);
assert_ne!(others.key, before);
}
/// A dragged object keeps its transparency in the GPU preview when TRANSPARENCYDISPLAY is
/// on, and is opaque when it is off.
#[test]
+10 -2
View File
@@ -61,9 +61,11 @@ pub enum Preference {
Dutch,
#[serde(rename = "pt-PT")]
Portuguese,
#[serde(rename = "fi")]
Finnish,
}
impl Preference {
pub const ALL: [Self; 25] = [
pub const ALL: [Self; 26] = [
Self::Auto,
Self::English,
Self::Greek,
@@ -89,6 +91,7 @@ impl Preference {
Self::Tamil,
Self::Dutch,
Self::Portuguese,
Self::Finnish,
];
/// Every preference in the order the Interface Language dialog lists them: Auto, then English
@@ -144,6 +147,7 @@ impl Preference {
Self::Tamil => "ta",
Self::Dutch => "nl",
Self::Portuguese => "pt-PT",
Self::Finnish => "fi",
}
}
@@ -208,6 +212,7 @@ impl Preference {
}
Self::Dutch => "Nederlands",
Self::Portuguese => "Português (Portugal)",
Self::Finnish => "Suomi",
}
}
@@ -247,6 +252,7 @@ impl Preference {
Self::Dutch => "nl",
Self::Portuguese => "pt-PT",
Self::Auto => locales.iter().find_map(|s| resolve_locale(s, language_is_available)).unwrap_or("en"),
Self::Finnish => "fi",
}
}
}
@@ -262,7 +268,7 @@ pub struct Language {
catalog: OnceLock<Catalog<'static>>,
}
pub static LANGUAGES: [Language; 24] = [
pub static LANGUAGES: [Language; 25] = [
Language { code: "en", name: "English", source: "", plural: plural_en, plural_forms: 2, catalog: OnceLock::new() },
Language { code: "pl", name: "Polski", source: include_str!("i18n/pl.tsv"), plural: plural_pl, plural_forms: 3, catalog: OnceLock::new() },
// Greek: one for exactly 1; other for zero and all other integer counts.
@@ -337,6 +343,8 @@ pub static LANGUAGES: [Language; 24] = [
// European Portuguese integer plurals (CLDR `pt-PT`): one (1), other.
// Catalog lives in storytold/craft-i18n (`locales/pt-pt/cadcraft.tsv`); falls back to English until cutover.
Language { code: "pt-PT", name: "Português (Portugal)", source: "", plural: plural_en, plural_forms: 2, catalog: OnceLock::new() },
// Finnish plurals follow the English rule: one (1), other (partitive singular after the number).
Language { code: "fi", name: "Suomi", source: include_str!("i18n/fi.tsv"), plural: plural_en, plural_forms: 2, catalog: OnceLock::new() },
];
/// BCP 47 and POSIX locale tags, including `uk-UA`, `uk_UA.UTF-8`, `pt_BR.UTF-8`, `pt-PT`
File diff suppressed because it is too large Load Diff
+115 -4
View File
@@ -349,7 +349,7 @@ fn assert_additional_locale_aliases() {
fn assert_unrecognized_locale_tags() {
// Look-alike codes, three-letter codes and endonyms pick nothing: `se` is Northern Sami.
let look_alikes = ["ua", "ukulele", "fi-FI", "", "garbage", "💙", "ptolemy", "cz", "csharp", "csomething", "italic"];
let look_alikes = ["ua", "ukulele", "", "garbage", "💙", "ptolemy", "cz", "csharp", "csomething", "italic"];
let others = ["kr", "korean", "kotlin", "se", "swe", "svenska", "hun", "magyar", "tur", "türkçe", "elvish", "kat", "geo", "kab", "kartuli"];
let tamil = ["tam", "tamil", "தமிழ்"];
for tag in look_alikes.into_iter().chain(others).chain(tamil) {
@@ -358,11 +358,11 @@ fn assert_unrecognized_locale_tags() {
}
fn assert_auto_locale_precedence() {
assert_eq!(Preference::Auto.resolve(&["fi-FI".into(), "pt-BR".into()]), "pt-BR");
assert_eq!(Preference::Auto.resolve(&["ja-JP".into(), "pt-BR".into()]), "pt-BR");
assert_eq!(Preference::Auto.resolve(&["pl-PL".into(), "pt-BR".into()]), "pl");
assert_eq!(Preference::Auto.resolve(&["fr-FR".into(), "pt-BR".into()]), "fr");
assert_eq!(Preference::Auto.resolve(&["es-ES".into(), "pt-BR".into()]), "es");
let locales = vec!["fi-FI".into(), "uk-UA".into(), "en-US".into()];
let locales = vec!["ja-JP".into(), "uk-UA".into(), "en-US".into()];
assert_eq!(Preference::Auto.resolve(&locales), "uk");
assert_eq!(Preference::English.resolve(&locales), "en");
assert_eq!(Preference::Auto.resolve(&["en-US".into(), "uk-UA".into()]), "en");
@@ -385,7 +385,7 @@ fn assert_preference_resolution(preference: Preference) {
// A chosen language wins over the system's; Auto takes the first system language there is.
assert_eq!(preference.resolve(&["uk-UA".into()]), preference.code());
if preference != Preference::English && LANGUAGES.iter().any(|l| l.code == preference.code() && !l.source.is_empty()) {
assert_eq!(Preference::Auto.resolve(&["fi-FI".into(), preference.code().into(), "en-US".into()]), preference.code());
assert_eq!(Preference::Auto.resolve(&["ja-JP".into(), preference.code().into(), "en-US".into()]), preference.code());
}
}
@@ -938,3 +938,114 @@ fn dutch_and_european_portuguese_registration_and_plurals() {
assert_eq!(((pt_pt.plural)(0), (pt_pt.plural)(1), (pt_pt.plural)(2)), (1, 0, 1));
assert_eq!(((pt_br.plural)(0), (pt_br.plural)(1), (pt_br.plural)(2)), (0, 0, 1));
}
#[test]
fn finnish_locales_preferences_and_plural_forms() {
for tag in ["fi", "fi-FI", "fi_FI.UTF-8", "FI-fi", " fi-FI "] {
assert_eq!(locale_language(tag), Some("fi"), "{tag}");
}
// `fil` is Filipino and `fin` the three-letter code; neither picks Finnish. `sv-FI` stays Swedish.
for tag in ["fil", "fin", "suomi"] {
assert_eq!(locale_language(tag), None, "{tag}");
}
assert_eq!(locale_language("sv-FI"), Some("sv"));
assert_eq!(Preference::parse("fi"), Some(Preference::Finnish));
assert_eq!(Preference::Finnish.name(), "Suomi");
assert_eq!(Preference::Finnish.resolve(&["en-US".into()]), "fi");
assert_eq!(Preference::Auto.resolve(&["ja-JP".into(), "fi-FI".into(), "en-US".into()]), "fi");
let mut app = CadApp::new(Session::new(), Services::default());
app.ui.interface_language = Preference::Finnish;
let mut restored = CadApp::new(Session::new(), Services::default());
restored.load_prefs(&app.prefs_json());
assert_eq!(restored.ui.interface_language, Preference::Finnish);
with_language("fi", || {
for n in [0, 1, 2, 5, 21, u64::MAX] {
// Other numbers than 1 take the partitive singular: 1 osallistuja, 2 osallistujaa.
let (contributor, commit) = if n == 1 { ("osallistuja", "kommitti") } else { ("osallistujaa", "kommittia") };
assert_eq!(count(n, "{n} contributor", "{n} contributors"), format!("{n} {contributor}"));
assert_eq!(count(n, "{n} commit", "{n} commits"), format!("{n} {commit}"));
}
assert_eq!(format("Current: {color}", &[("color", "{n} Open".into())]), "Nykyinen: {n} Open");
});
}
#[test]
fn finnish_menu_headings_keep_object_labels() {
with_language("fi", || {
assert_eq!(menu("Dimension"), "Mitoitus");
assert_eq!(t("Dimension"), "Mitta");
assert_eq!(menu("View"), "Näytä");
assert_eq!(menu("Draw"), "Piirrä");
assert_eq!(menu("Edit"), "Muokkaa");
assert_eq!(menu("Modify"), "Muuta");
assert_eq!(menu("File"), "Tiedosto");
// Every menu bar heading reads differently.
let headings: BTreeSet<_> = crate::menus::MENUS.iter().map(|m| menu(m)).collect();
assert_eq!(headings.len(), crate::menus::MENUS.len());
});
}
#[test]
fn live_finnish_switch_preserves_drawing_command_and_saved_choice() {
let mut app = CadApp::new(Session::new(), Services::default());
app.ui.in_window_menu = true;
app.session.state_mut().unwrap().title = "Open".into();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
app.logic(&ctx);
assert!(render(&mut app, &ctx).contains("Properties"));
app.start("line");
let prompt = crate::control::cmdline_state(&app);
let commands = crate::control::all_commands(&app);
app.run("ui.language", json!({"lang":"fi"})).unwrap();
let text = render(&mut app, &ctx);
for label in ["Ominaisuudet", "Tiedosto", "Näytä", "Piirrä", "Mitoitus", "Määritä ensimmäinen piste"] {
assert!(text.contains(label), "missing {label}: {text}");
}
assert_eq!(app.language(), "fi");
assert_eq!(app.session.state().unwrap().title, "Open");
assert_eq!(crate::control::cmdline_state(&app), prompt);
assert_eq!(crate::control::all_commands(&app), commands);
app.run("ui.language", json!({"lang":"en"})).unwrap();
assert!(render(&mut app, &ctx).contains("Properties"));
}
#[test]
fn finnish_dialogs_render_with_stable_ids() {
for (dialog, heading) in [
("dsettings", "Piirtoasetukset"),
("about", "Tietoja CADCraftista"),
("commands", "Komentojen viiteopas"),
("layers", "Tasojen ominaisuuksien hallinta"),
("qselect", "Pikavalinta"),
("parameters", "Parametrien hallinta"),
("language", "Suomi"),
("options:preferences", "Käyttäjän asetukset"),
] {
let mut app = CadApp::new(Session::new(), Services::default());
app.ui.interface_language = Preference::Finnish;
app.ui.dialog = Some(dialog.into());
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
app.logic(&ctx);
let text = render(&mut app, &ctx);
assert!(text.contains(heading), "{dialog}: {text}");
assert_eq!(app.ui.dialog.as_deref(), Some(dialog));
}
}
#[test]
fn default_fonts_cover_finnish_letters_and_quotes() {
let ctx = egui::Context::default();
let mut output = ctx.run_ui(Default::default(), |_| {});
output.textures_delta.clear();
let letters: BTreeSet<_> = "ÄÖÅäöåŠšŽž”–".chars().collect();
ctx.fonts_mut(|view| {
for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] {
let chars = view.characters(&family);
for c in &letters {
assert!(chars.contains_key(c), "missing {c} in {family:?}");
}
}
});
}
+7 -2
View File
@@ -73,6 +73,7 @@ pub mod palettes;
pub mod parametric;
pub mod plotstyles;
pub mod quick;
pub mod save_changed;
pub mod save_loss;
pub mod shortcut_menus;
pub mod theme;
@@ -403,6 +404,8 @@ pub struct CadApp {
pub save_loss: Option<save_loss::Pending>,
/// The loss the user last agreed to, so saving again doesn't ask again ([`save_loss`]).
pub save_loss_accepted: Option<save_loss::Accepted>,
/// A save waiting for an answer about a file another program changed ([`save_changed`]).
pub save_changed: Option<save_changed::Pending>,
/// Autosave (desktop; `None` until [`Self::enable_autosave`]).
pub autosave: Option<cadcraft_engine::autosave::Autosaver>,
/// Drawing Recovery: autosave files a crashed app left behind.
@@ -492,6 +495,7 @@ impl CadApp {
closing: None,
save_loss: None,
save_loss_accepted: None,
save_changed: None,
autosave: None,
recovery: autosave::Recovery::default(),
gpu_faults: std::sync::Arc::default(),
@@ -1164,11 +1168,11 @@ impl CadApp {
ctx.request_repaint_of(egui::ViewportId::ROOT);
}
/// Whether a modal dialog is up: the "Save changes?" prompt, the lossy-save warning or Drawing Recovery. The
/// Whether a modal dialog is up: the "Save changes?" prompt, the lossy-save warning, the changed-file question or Drawing Recovery. The
/// floating panels' own OS windows take no input meanwhile (egui's `Modal` blocks only the
/// main window). The app's other dialogs are ordinary windows that leave the drawing usable.
pub fn shows_modal(&self) -> bool {
self.close_prompt().is_some() || self.save_loss.is_some() || !self.recovery.items.is_empty()
self.close_prompt().is_some() || self.save_loss.is_some() || self.save_changed.is_some() || !self.recovery.items.is_empty()
}
/// Input hook: refresh the raw surface snapshot, put in keys forwarded from floating panels'
@@ -1351,6 +1355,7 @@ impl CadApp {
palettes::patterns::prompt_picker(self, ui.ctx());
closing::prompt(self, ui.ctx());
save_loss::prompt(self, ui.ctx());
save_changed::prompt(self, ui.ctx());
autosave::show(self, ui.ctx());
autosave::gpu_notice(self, ui.ctx());
autosave::failure_notice(self, ui.ctx());
+14 -4
View File
@@ -401,8 +401,9 @@ fn should_pick_file_path(id: &str, params: &Value) -> bool {
}
/// A user's QSAVE: a drawing with no file yet picks one, and saving over a file that would lose
/// content asks first. `None` lets the engine save. JSON calls carry params and never get here;
/// they report the loss in their result instead.
/// content asks first ([`crate::save_loss`]), then saving over a file another program changed
/// ([`crate::save_changed`]). `None` lets the engine save. JSON calls carry params and never get
/// here; they report the loss in their result, and the engine refuses the changed file.
fn user_qsave(app: &mut CadApp) -> Option<Result<Value, String>> {
if app.file_providers.enabled() {
return Some(crate::file_provider_app::save(app, false));
@@ -410,7 +411,11 @@ fn user_qsave(app: &mut CadApp) -> Option<Result<Value, String>> {
if app.session.state().is_ok_and(|s| s.path.is_none()) {
return run_ui_command(app, "ui.saveas", &Value::Null);
}
app.hold_lossy_save().then_some(Ok(Value::Null))
if app.hold_lossy_save() {
return Some(Ok(Value::Null));
}
let path = app.session.state().ok().and_then(|s| s.path.clone())?;
app.hold_changed_save(&path, crate::save_changed::Save::Qsave).then_some(Ok(Value::Null))
}
fn run_settings_and_close_command(app: &mut CadApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
@@ -505,7 +510,12 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option<Re
let name = format.suggested_name(title.as_deref());
// Bound to this drawing: the answer saves it, not whichever drawing is active then.
app.pick_then(Pick::Save(name), |app, p| {
app.session.execute("saveas", &crate::exchange::version_params(&app.ui, &p)).map_err(|e| e.to_string())
let params = crate::exchange::version_params(&app.ui, &p);
// Onto the drawing's own file, which another program changed: ask first.
if app.hold_changed_save(&p, crate::save_changed::Save::SaveAs(params.clone())) {
return Ok(Value::Null);
}
app.session.execute("saveas", &params).map_err(|e| e.to_string())
})
.unwrap_or(Ok(Value::Null))
}
+1 -1
View File
@@ -10,7 +10,7 @@
//! |---|---|
//! | `theme` | `"system"`, `"light"` or `"dark"` |
//! | `animations` | `"system"`, `"on"` or `"off"`: dialog and menu fades and smoothed scrolling |
//! | `interfaceLanguage` | `"auto"`, `"en"`, `"uk"`, `"pt-BR"`, `"de"`, `"es"`, `"cs"`, `"ru"`, `"fr"`, `"zh"`, `"it"`, `"ko"`, `"sv"`, `"ar"`, `"he"`, `"hu"`, `"tr"`, `"bs"`, `"vi"`, `"el"`, `"ka"`, `"ta"`, `"nl"` or `"pt-PT"` |
//! | `interfaceLanguage` | `"auto"`, `"en"`, `"uk"`, `"pt-BR"`, `"de"`, `"es"`, `"cs"`, `"ru"`, `"fr"`, `"zh"`, `"it"`, `"ko"`, `"sv"`, `"ar"`, `"he"`, `"hu"`, `"tr"`, `"bs"`, `"vi"`, `"el"`, `"ka"`, `"ta"`, `"nl"`, `"pt-PT"` or `"fi"` |
//! | `saveFormat` | `"dxf"` or `"dwg"`: the format Save As suggests for new drawings |
//! | `saveVersion` | `"2000"` … `"2018"`: the version drawings with no file yet are saved in |
//! | `SAVETIME` | minutes between automatic saves, 0–600 (0: off) |
+169
View File
@@ -0,0 +1,169 @@
//! Asking before a save replaces a drawing file that another program changed. The engine refuses
//! to save over the drawing's own file when it no longer holds what was opened or last saved here
//! (`cadcraft_engine::cmd::file::on_disk`), and automation passes `overwrite: true` to save anyway.
//! A user has no way to pass that, so a user's save asks instead: File ▸ Save, its shortcut or
//! typed QSAVE, Save As onto the drawing's own file, Save in the close prompt, and Save Anyway in
//! the lossy-save warning ([`crate::save_loss`], which asks first). The choices are Save As... /
//! Cancel / Overwrite. The answer covers that one save to the file the question names: the next
//! save compares again, and Overwrite saves nothing if the drawing's file changed meanwhile.
//!
//! Save in the close prompt stops closing while this asks, as it does for the lossy-save warning:
//! the drawing stays open with its changes, and closing again after the answer goes on.
//!
//! Programmatic saves (`engine.execute`, the control channel, MCP, scripts) never ask: they get the
//! engine's refusal, which says how to save anyway.
use egui::{RichText, vec2};
use serde_json::{Value, json};
use cadcraft_engine::cmd::file::on_disk;
use cadcraft_engine::disk_stamp::OnDisk;
use crate::CadApp;
use crate::theme::Tokens;
/// The user's answer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Choice {
/// Save the drawing over the file anyway.
Overwrite,
/// Pick another file: the drawing goes there and the changed file stays.
SaveAs,
Cancel,
}
/// The save to repeat with `overwrite: true` if the user says so.
#[derive(Clone, Debug, PartialEq)]
pub enum Save {
Qsave,
/// SAVEAS with these parameters (the path picked, the version and format chosen).
SaveAs(Value),
}
/// A save held back until the user answers.
#[derive(Clone, Debug, PartialEq)]
pub struct Pending {
uid: u64,
path: String,
/// Why the file could not be read to compare. `None`: it holds something else.
unchecked: Option<String>,
save: Save,
}
impl Pending {
/// The file the save would replace.
pub fn path(&self) -> &str {
&self.path
}
/// Whether the file could not be read to compare, so it may or may not have changed.
pub fn unchecked(&self) -> bool {
self.unchecked.is_some()
}
}
impl CadApp {
/// Hold a user's save of the active drawing to `path` if the file there changed on disk (or
/// can't be read to tell), and ask. Returns whether it was held.
pub fn hold_changed_save(&mut self, path: &str, save: Save) -> bool {
let Ok(uid) = self.session.state().map(|st| st.uid) else { return false };
let unchecked = match on_disk(&self.session, path) {
OnDisk::Same => return false,
OnDisk::Changed => None,
OnDisk::Unchecked(why) => Some(why),
};
self.save_changed = Some(Pending { uid, path: path.to_string(), unchecked, save });
true
}
/// Answer the open question (no-op without one).
pub fn answer_save_changed(&mut self, choice: Choice) {
let Some(Pending { uid, path, save, .. }) = self.save_changed.take() else { return };
// The drawing can go away, or stop being the active one, while the question is up.
let i = self.session.docs.iter().position(|d| d.uid == uid);
match (choice, i) {
(Choice::Cancel, _) | (_, None) => self.session.echo(crate::tf!("Save cancelled: {path} was not changed.", path = path)),
(Choice::SaveAs, Some(i)) => {
self.activate_doc(i);
let _ = self.run("ui.saveas", Value::Null);
}
(Choice::Overwrite, Some(i)) => {
self.activate_doc(i);
let _ = match save {
Save::Qsave => {
// QSAVE writes to the drawing's file as it is now. A save under another name
// while the question was up (the control channel, a script) moved it, and
// the answer was about the file the question named: save nothing.
let now = self.session.state().ok().and_then(|st| st.path.clone());
if now.as_deref() != Some(path.as_str()) {
self.session.echo(crate::tf!(
"Save cancelled: the drawing is no longer saved to {path}. Save again to check the file it uses now.",
path = path
));
return;
}
self.run("qsave", json!({ "overwrite": true }))
}
// SAVEAS names its file: Overwrite writes there and nowhere else.
Save::SaveAs(mut params) => {
params["overwrite"] = Value::Bool(true);
self.run("saveas", params)
}
};
}
}
}
}
/// The question, while a save waits for an answer. Cancel is what Escape does.
pub fn prompt(app: &mut CadApp, ctx: &egui::Context) {
let Some(pending) = app.save_changed.clone() else { return };
let t = Tokens::get();
let path = std::path::Path::new(pending.path());
let file = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| pending.path().to_string());
let mut choice = None;
crate::modal::instant(ctx, egui::Id::unique("cc_save_changed_prompt")).show(ctx, |ui| {
ui.set_width(420.0);
match &pending.unchecked {
None => {
ui.label(RichText::new(crate::tf!("{name} changed on disk", name = file)).strong());
ui.add_space(4.0);
ui.label(crate::tl!(
"Another program or person saved this file after you opened it. Overwrite replaces their changes with this drawing."
));
}
Some(why) => {
ui.label(RichText::new(crate::tf!("{name} could not be checked", name = file)).strong());
ui.add_space(4.0);
ui.label(crate::tf!(
"The file could not be read to check whether someone else saved it ({reason}). Overwrite may replace their changes.",
reason = why
));
}
}
ui.label(
RichText::new(crate::tl!("Save As keeps both: this drawing goes to a new file and the file on disk stays as it is.")).color(t.text_dim),
);
ui.add_space(10.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let size = vec2(96.0, 22.0);
let save_as = ui.add(egui::Button::new(RichText::new(crate::tl!("Save As...")).color(t.text)).fill(t.accent).min_size(size));
if save_as.clicked() {
choice = Some(Choice::SaveAs);
}
if ui.add(egui::Button::new(crate::tl!("Cancel")).min_size(size)).clicked() {
choice = Some(Choice::Cancel);
}
if ui.add(egui::Button::new(crate::tl!("Overwrite")).min_size(size)).clicked() {
choice = Some(Choice::Overwrite);
}
});
if crate::framework::escape_pressed(ui.ctx()) {
choice = Some(Choice::Cancel);
}
});
if let Some(c) = choice {
app.answer_save_changed(c);
ctx.request_repaint();
}
}
+6 -2
View File
@@ -105,13 +105,17 @@ impl CadApp {
}
(Choice::SaveAnyway, Some(i)) => {
self.activate_doc(i);
let path = loss.path.clone();
self.save_loss_accepted = Some(loss);
let _ = self.run("qsave", json!({}));
// A file another program changed meanwhile is asked about next.
if !self.hold_changed_save(&path, crate::save_changed::Save::Qsave) {
let _ = self.run("qsave", json!({}));
}
}
}
}
fn activate_doc(&mut self, i: usize) {
pub(crate) fn activate_doc(&mut self, i: usize) {
if self.session.active != i {
let _ = self.run("document.switch", json!({ "index": i }));
}
+12 -1
View File
@@ -88,6 +88,9 @@ pub struct Tokens {
pub icon_point: Color32,
pub accent: Color32,
pub selection: Color32,
/// A selected annotative object at its other scales (SELECTIONANNODISPLAY): the selection
/// colour, faded.
pub selection_faded: Color32,
pub hover: Color32,
pub grip: Color32,
pub grip_hot: Color32,
@@ -148,6 +151,7 @@ impl Tokens {
icon_point: Color32::from_rgb(0xf0, 0x7a, 0x3a),
accent: Color32::from_rgb(0x3d, 0x8b, 0xfd),
selection: Color32::from_rgb(0x4a, 0x8f, 0xff),
selection_faded: Color32::from_rgba_premultiplied(0x21, 0x40, 0x72, 0x73),
hover: Color32::from_rgb(0x9c, 0xc6, 0xff),
grip: Color32::from_rgb(0x2f, 0x6b, 0xff),
grip_hot: Color32::from_rgb(0xff, 0x3b, 0x3b),
@@ -253,6 +257,9 @@ pub struct Canvas {
pub selection: Option<Color32>,
}
/// How opaque [`Tokens::selection_faded`] is next to the selection colour.
const SELECTION_FADE: f32 = 0.45;
/// The default object snap marker size.
pub const SNAP_MARKER: f32 = 11.0;
@@ -268,7 +275,11 @@ impl Canvas {
Some(bg) => t.with_model_background(bg),
None => t,
};
Tokens { paper: self.paper.unwrap_or(t.paper), selection: self.selection.unwrap_or(t.selection), ..t }
let (selection, selection_faded) = match self.selection {
Some(c) => (c, c.gamma_multiply(SELECTION_FADE)),
None => (t.selection, t.selection_faded),
};
Tokens { paper: self.paper.unwrap_or(t.paper), selection, selection_faded, ..t }
}
}

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