Compare commits

..
Author SHA1 Message Date
Dylan M. Taylor c3d23ce225 docs: soften normative phrasing and add agent anti-overbuilding guardrail 2026-11-24 00:25:38 -05:00
Dylan M. Taylor cd96a12ae4 docs: add ACCESSIBILITY.md 2026-11-23 22:24:56 -05:00
Tanish Manku ddb9a424ef Merge pull request #3423 from storytold/land/2697
Land #2697: draw the proxy graphics of objects from other applications
2026-11-23 17:12:17 -07:00
icelyfireandClaude Opus 5.5 a974b2026f Add the Write Block dialog for WBLOCK (#1778)
* Add the Write Block dialog for WBLOCK

WBLOCK typed or started from a menu now opens a Write Block dialog instead of
failing with "`path` is required": source (block, entire drawing or objects),
base point and destination file, with Select objects and Pick point that hide
the dialog for a canvas pick and bring it back. JSON calls are unchanged.

A new WBLOCKPICK command runs those picks and keeps the result in
Session::wblock_picks, like HATCHPICK does for the Hatch dialog. Escape closes
the dialog, and ends the command while picking.

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

* fix(wblock): address CodeRabbit review comments

- WblockPickM Objects: use SelectPhase::default() instead of begin(s)
  so canvas picking always prompts explicitly, even with a pre-existing
  selection (the dialog pre-fills handles itself)
- wblock.rs: reject non-numeric/non-finite base coordinates with an
  error message instead of silently defaulting to 0
- Add i18n strings for the two new coordinate-error messages (it)
- Add test: preexisting_selection_still_prompts

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

* fix(wblock): address review comments from skylartaylor

1. EntireDrawing now passes `name: "*"` to run_wblock, which clones the
   whole drawing (all layouts, paper space, INSBASE preserved) instead of
   sending only d.model handles and resetting INSBASE.
2. Add integration tests in wblock_dialog.rs that call run_wblock and
   read back the written file for EntireDrawing and Objects+base modes.
3. Reformat parse_coord's early return to satisfy rustfmt.
4. Drop the two "Mouse wheel zooms…" rows from it.tsv; they belong to
   the wheelzoom PR, not this one.
5. resume() now checks that the current drawing UID matches the one the
   pick started in, mirroring hatchdlg::resume; start_pick restores the
   dialog when wblockpick fails to start instead of closing silently.
6. Add all wblock dialog labels to uk.tsv (Source, Destination, Base
   point, Pick point, File name and path, etc.); fix the period mismatch
   in the "No objects selected" error key.

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

* test(wblock): call confirm() directly and add layout-entity coverage

- Make confirm() and picked_handles pub so integration tests can reach them.
- wblock_dialog.rs now calls wblock::confirm() instead of app.run, so the
  test fails if confirm constructs wrong params (addresses CodeRabbit comment).
- app_with_two_entities adds one paper-space entity via Drawing::add so the
  EntireDrawing test can also assert j["layouts"] == 1 (second CodeRabbit
  comment).

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

* test(wblock): assert base-point translation and INSBASE preservation

- write hook now records Line endpoints so the Objects test can verify
  that the base-point offset is actually applied to entity coordinates:
  line (0,0)→(10,0) with base (5,3) becomes (-5,-3)→(5,-3).
- EntireDrawing test sets INSBASE to (7,3) before confirm() and asserts
  the exported drawing still carries (7,3), covering the preservation
  behaviour of whole-drawing mode.

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

* wblock: the chosen path clears an earlier file-dialog refusal

Clicking "…" while the save panel is still open shows "A file dialog is
already open; answer it first." The message stayed after the panel was
answered; the path chosen now clears it. The button's code moves into
browse(), with a test.

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

* wblock: the dialog belongs to the drawing it was opened on

Opened on drawing A and left open while drawing B was shown (its file tab),
OK applied the retained source, handles and destination to B: with
drawing-local handles colliding, B's objects were written to A's file.

The dialog now keeps the drawing's uid when it opens (and binds to the
current drawing when opened by name with no state). It closes once another
drawing is shown, as the Hatch dialog does, and confirm() refuses to write
from another drawing, saying why.

Tests: for Objects, Block and Entire drawing, the dialog opened on A, B
shown through document.switch (what the tab runs), B holding the same
handles and a block of the same name: confirm() writes nothing, one frame
closes the dialog, and back on A nothing is written either. The two
existing confirm() tests now open the dialog first.

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

* wblock: English keys only, and the completion message through i18n

As AGENTS.md rule 16 asks, the Italian and Ukrainian rows this PR added
to the app catalogs go to a linked storytold/craft-i18n PR instead. The
Chinese row for the WBLOCKPICK command label stays: every command label
must be in zh for chinese_menus_and_commands_are_fully_translated, and a
test can't be weakened to make a check pass (rule 31).

The completion message ("N objects written to …") and the dialog's
selected-object count were English built with format!; they now go
through crate::tf! and crate::i18n::count, so each has a catalog key
and a plural form.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 17:36:26 -06:00
Tanish Manku 9d6f82dc9f Merge pull request #3422 from storytold/land/899
Land #899: opening a drawing that is already open selects its tab
2026-11-23 13:10:06 -07:00
Tanish Manku e811a5183e Merge pull request #3421 from storytold/stack/i1
Land #2235, #2898, #2900, #3260, #2901: French, Arabic, Georgian and Swedish catalog updates
2026-11-23 13:09:55 -07:00
Tanish Manku 6855f76f5a Proxy graphics: a filled polygon's loop has no boundary path flags of its own 2026-11-23 13:09:30 -07:00
Tanish Manku fc82a0d148 Merge #2697: draw the proxy graphics of ACAD_PROXY_ENTITY (#2646) 2026-11-23 12:49:40 -07:00
Tanish Manku 223314c8eb Merge #899: Reuse existing drawing tabs when reopening paths 2026-11-23 12:49:15 -07:00
Tanish Manku 7b8ca63926 Arabic catalog test: check the words themselves, so it fails on the old catalog and on a missing row 2026-11-23 12:48:57 -07:00
Tanish Manku 6601baf63d Merge pull request #3418 from storytold/stack/u9
Land #3397, #3409, #3369, #3370, #3374, #3367, #3363, #2979: MTEXT corner and Ortho, window selection drift, CLI fixes, per-column MTEXT boxes, DIMASSOC in DXF
2026-11-23 12:47:43 -07:00
Tanish Manku ff0bde679c Merge pull request #3417 from storytold/stack/s9
Land #3372, #3408, #3349, #3386, #3389, #3391, #3393: hatch islands, fitted text, Model plot flag, DWG 2007 visual styles, PLINE elevation, script BOM
2026-11-23 12:47:30 -07:00
Tanish Manku 7506ffc83d Merge #2901: i18n(sv): translate 705 new strings 2026-11-23 12:46:26 -07:00
Tanish Manku 9254277db3 Merge #3260: i18n(ka): update the Georgian catalog (33 strings) 2026-11-23 12:46:24 -07:00
Tanish Manku 3a4cf04b76 Merge #2900: i18n(ka): Georgian for 20 new strings 2026-11-23 12:46:23 -07:00
Tanish Manku 61b420cfbe Merge #2898: i18n(ar): tell Trim, Stretch and Extend apart, and call Point a point 2026-11-23 12:46:21 -07:00
Tanish Manku 59f27fb38c Merge #2235: i18n(fr): consistent French CAD terminology in existing rows 2026-11-23 12:46:19 -07:00
Dylan M. Taylor 25bfb60078 revert: restore scheduled release.yml dry-run on main (#3420) 2026-11-23 14:44:45 -05:00
Tanish Manku 1ae4c29990 Merge pull request #3344 from storytold/land/1347
Land #1347: macOS opens drawings from Finder, the Dock and open -a; Quit asks about unsaved changes
2026-11-23 12:40:37 -07:00
Tanish Manku 6ad7d9dfb7 Apple events test: allow the in-process DWG converter, as each test runs in its own process 2026-11-23 12:25:32 -07:00
Tanish Manku ca92d330a3 Merge #2979: fix(io): keep DIMASSOC when saving DXF drawings 2026-11-23 12:23:39 -07:00
Tanish Manku cfed9aa27a Merge #3363: MTEXT layout: a box per column, so a background mask can leave the gutters bare (#3319) 2026-11-23 12:23:36 -07:00
Tanish Manku 0b4337d3ed Merge #3367: fix(macos): keep Clear Recent Files disabled when empty 2026-11-23 12:23:34 -07:00
Tanish Manku 02f8f6df4d Merge #3374: Warn about undrawn entities in run image exports 2026-11-23 12:23:31 -07:00
Tanish Manku ba7c7b5845 Merge #3370: fix(cli): send roundtrip progress to the supplied stderr 2026-11-23 12:23:29 -07:00
Tanish Manku 5e5b5133e6 Merge #3369: Report flush failures when printing CLI help 2026-11-23 12:23:26 -07:00
Tanish Manku 73eb57b638 Merge #3409: Keep window selection open after small first-corner pointer drift 2026-11-23 12:23:24 -07:00
Tanish Manku bf5538d482 Merge #3397: fix(engine): ignore Ortho mode for MTEXT opposite corner (#3388) 2026-11-23 12:23:21 -07:00
Tanish Manku 051b11a271 Merge #3393: DWG 2007: omit older-layout visual styles and report the loss 2026-11-23 12:22:09 -07:00
Tanish Manku c5c32e805b Merge #3391: Preserve fitted text when saving DXF and DWG 2026-11-23 12:22:08 -07:00
Tanish Manku 685bc51442 Merge #3389: DXF and DWG save: a hatch keeps its boundary path flags, so islands stay holes in other programs 2026-11-23 12:22:06 -07:00
Tanish Manku 25a7835d04 Merge #3386: DXF/DWG: the Model layout's plot settings carry the ModelType flag (1024) 2026-11-23 12:22:04 -07:00
Tanish Manku 264368b7db Merge #3349: Suggest DXF when Save As is opened from the DWG content-loss warning. 2026-11-23 12:22:02 -07:00
Tanish Manku 3673897110 Merge #3408: Keep the current drawing elevation when creating a polyline 2026-11-23 12:22:00 -07:00
Tanish Manku d2d754564e Merge #3372: fix(script): accept a leading UTF-8 byte-order mark 2026-11-23 12:21:58 -07:00
Tanish Manku f5b201f15d Merge main 2026-11-23 12:14:04 -07:00
Dylan M. Taylor 16929ef8ef ci(release): publish scheduled nightly prereleases (#3416) 2026-11-23 13:16:38 -05:00
Jon Breen b1cfeedf81 Review: pin nonfinite alignment points in the degenerate-geometry test
An imported Aligned text whose alignment point is not finite keeps its edited
height. Also formats the earlier degenerate-geometry test.
2026-11-23 12:11:29 -06:00
skylar taylor-barrick a8c50b0924 Regression tests for #618, #651 and #1336 (#1961)
* #1336: test that the DXF LAYER table stops at the record cap

The LAYER, LTYPE, STYLE and DIMSTYLE tables had no record cap, unlike VIEW, UCS and VPORT. The test reads a DXF with over a million LAYER records and checks the layer list stays at the cap; without the guard it holds every record (1000102 layers). The other three tables scan their lists linearly per record, so a million-record file is too slow to build in a test and they stay uncovered.

* #651: test that small filled text is simplified on screen and keeps full detail in plots

Filled TrueType text was triangulated at full outline detail at every zoom, which froze the canvas on pages of small text.

The test draws four O glyphs in a font built in the test itself (a 128-point ring registered through `cadcraft_fonts::ttf::register`), so it needs no installed font and no font file in the repository, and it never skips. At 10 px per cap height the rings are simplified and the shapes keep their extent; with an em under two pixels each glyph is the ink's box, two triangles; a plot keeps every point. Without the fix the on-screen build has the plot's 1024 triangles.

`crates/render/src/text.rs` gains the same policy without any font: `detail` returns Full for a plot, Box for an em under two pixels and Reduced for a small one, and `simplify` drops the points of a flattened curve at a coarse band and keeps them at a fine one.

* #618: test that OFFSET takes a clicked distance and picks its source under grid snap

OFFSET only accepted a typed distance, and with grid snap on a click meant to pick the source object was moved to the nearest grid point.

The engine test clicks two points for the distance and checks the second-point prompt and its base, the guide line in the preview, OFFSETDIST and the resulting offset. The canvas test does the same through grid-snapped clicks, then picks the source line and checks the side click puts the copy 5 units up, that OFFSET asks for the next object and that Enter ends it. Both live in the per-crate integration-test binary (#1989).

Without the fix the engine and canvas tests stay at the distance prompt; with only the cursor's point-prompt test reverted the canvas test never picks the line.

* Tests: one synthetic TrueType builder for render and PDF, and the exact LAYER cap

Sonar's duplicate-lines gate flags 84 of the 334 new lines (25.15% against a 3% limit): the render
level-of-detail fixture's `fixture_font_bytes` and the PDF writer's `test_font` build the same sfnt
tables, so the two suites carried a copy each.

Both now build their fonts with `crates/fonts/tests/support/sfnt.rs`, which the two suites include
with `#[path]`. The fonts layer owns the table format it reads (`crates/fonts/src/ttf.rs`), so the
skeleton lives beside its tests and neither consumer is turned into a published API or a dependency;
no Cargo entry changes. The glyph shapes (`ring`), the cmap ranges and the metrics each font records
stay at the caller: the render fixture keeps its two 128-point contours with the counter wound the
other way, its 1000-unit em and 700-unit cap height, and the PDF fixtures keep their three fonts.

The font files are byte-identical before and after the refactor: render 1704 bytes, sha256
83b9914cdf6e704df1ca5851ecefc98708c947b0d5be818cf5b6282761d31db0; PDF embeddable 484 bytes
2711cc7394b2057ba7e6bee22bb25a6c25edd4ecec0d35ba326759a04fcdefb9 and `fsType=2` restricted 484
bytes 3e6b534115429e8cbfdefd97e40ebdeb874222fcd7929f69b02d261cef622db4, one byte apart at OS/2
`fsType`; and the deliberately short `hmtx` 476 bytes
dbcc548f59a4d3e414deb959014b8548632a7fa66fe12201895cdcbe6e66a000, whose `hhea` still declares three
metrics while `hmtx` holds one.

The DXF LAYER cap test asserted `<= 1_000_000` and `> 900_000`, which lets up to 99,999 valid
records go missing unnoticed. It now asserts exactly the million layers the parser keeps, written as
a literal so a changed constant fails the test instead of following it, with a records-specific
message. Removing the guard reads 1000101 layers; a cap of 950,000 reads 950,000.
2026-11-23 09:39:05 -06:00
Dylan M. Taylor bebbdca51a ci(release): forward ARTCRAFT_SERVICES_DISPATCH_TOKEN secret (#3410) 2026-11-23 09:33:17 -05:00
Jon Breen 2e047907f7 Review: missing or coincident points and empty defaults keep current fitted values
Imported text with no alignment point, or with coincident points, no longer
takes the read-time measurement, so an edited height is saved as edited. An
Aligned ATTDEF with an empty default keeps its stored height when its points
move; its rotation still follows the points.
2026-11-23 08:20:59 -06:00
ViktorBystrov72 1cfc7d8f17 PLINE: keep the current drawing elevation 2026-11-23 18:24:18 +05:00
ViktorBystrov72 2733c9d31a Selection: keep the first corner open after pointer drift 2026-11-23 18:21:45 +05:00
Walter Haslbeck 4680fd28a6 Merge main (a70b9b02) into fix/2646-proxy-graphics
Conflicts: dxf_read.rs (proxy tables next to the UCS names), render/blocks.rs
(proxy graphics inherit the proxy's own transparency without its locked-layer
fade, as block contents now do), roundtrip test (allow_in_process). Two tests
main added build an Unknown and get the graphics field.
2026-11-23 10:56:07 +01:00
Zaxaerith e5972c994e fix(engine): ignore Ortho mode for MTEXT opposite corner (#3388) 2026-11-23 10:58:38 +08:00
Jon Breen 6c5fdfdd32 DWG 2007: omit older-layout visual styles and report the loss
Leave fixed-property visual styles out of DWG 2007 saves and count them in the save report. Expose the same count to hosts and cover the affected and unaffected save paths with synthetic tests.
2026-11-22 17:29:42 -06:00
Jon Breen a4d8cae573 DXF and DWG save: a hatch keeps its boundary path flags, so islands stay holes in other programs
See the pull request description for the cause, the change and the tests.
2026-11-22 16:24:59 -06:00
Jon Breen 8e9dc8a6cb Preserve fitted text when saving DXF and DWG
See the pull request description for the cause, the change and the tests.
2026-11-22 16:24:59 -06:00
STE1200andClaude Opus 5.5 371baf176b DXF/DWG: the Model layout's plot settings carry the ModelType flag (1024)
The Model LAYOUT is written from a synthetic page setup without kept plot
flags, so its plot layout flags (AcDbPlotSettings group 70) were always
688 (512|128|32|16) and never had 1024, "ModelType", which the DXF
Reference (PLOTSETTINGS, group 70 "Plot layout flag") defines for the plot
settings of model space. Every saved DXF, and every DWG built from the same
DXF text, had a Model layout without it.

plot_layout_flags now sets 1024 for the Model layout and clears it for a
paper-space layout, also when a file's kept flags had it there, since it
would mark that layout as model space. The other bits stay as in #3227.

Test: layout_plot_flags::only_the_model_layout_carries_the_model_type_flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:37:29 +01:00
Mex 3d9b5f6175 Check image warnings on stderr without changing native exports 2026-11-21 20:26:18 +01:00
Mex 924a37abac Report undrawn entities when running an image export 2026-11-21 20:25:56 +01:00
Mex 892a7e2a0b Cover BOM-prefixed commands and first-line comments
Add test for scripts allowing one leading UTF-8 BOM.
2026-11-21 19:44:22 +01:00
Mex 3d9a59c0a0 fix(script): accept a leading UTF-8 byte-order mark 2026-11-21 19:43:23 +01:00
Vincent Cloutier 71929191a9 Refresh DXF DIMASSOC persistence against current main 2026-11-21 13:27:54 -05:00
Mex cf6046cc62 Check roundtrip progress on the supplied error stream 2026-11-21 18:55:37 +01:00
Mex 22c03def7a fix(cli): send roundtrip progress to the supplied stderr 2026-11-21 18:54:53 +01:00
Mex dbef5a6bba Report flush failures when printing CLI help 2026-11-21 18:43:49 +01:00
Mex e8114fdaa3 Reuse the shared Clear Recent Files command ID 2026-11-21 18:28:11 +01:00
Mex 2a0454cacc fix(macos): keep Clear Recent Files disabled when empty 2026-11-21 18:27:51 +01:00
moandClaude Opus 5.5 f28011ecec MTEXT layout: each column gets its own box, so a mask can leave the gutters bare
MTextLayout only had `bounds`, one box over every column and the gutters
between them, so a background mask drawn from it (the MTEXT background
fill of PR #3240) paints the empty gutters too. Add `column_bounds`: one
box per column in the order the text flows through them, measured like
`bounds` (same corners, rotation and attachment) but each only as wide as
a column and as tall as that column's own height or its text, whichever
is taller. Columns the text leaves empty keep their place; reversed
columns are placed right to left like their text.

A layout with one column, columned or not, has `column_bounds` equal to
`bounds`, so a consumer that switches to it draws exactly what it drew
before. `bounds` itself is unchanged for every other consumer.

For issue #3319.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:59:36 -05:00
FredApps a70b9b02e4 Merge pull request #1673 from ohagmann/feat/osnap-tab-every-candidate
Object snaps: Tab cycles every candidate snap under the cursor, not one per mode
2026-11-21 17:27:26 +07:00
FredApps b206eab39b Merge branch 'main' into feat/osnap-tab-every-candidate 2026-11-21 17:07:38 +07:00
bnjgoeandCursor fba67a1c76 Suggest DXF when Save As is opened from the DWG content-loss warning.
The dialog says DXF keeps the objects DWG would drop. File Save As still uses the user's default format.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 17:59:26 -06:00
Tanish Manku a5da799a8c Land #1347: read the open test's synthetic DWG in process
Main now reads and writes DWG through a worker process that only main()
starts, so the test's DWG write failed. The file is the test's own.
2026-11-20 10:00:30 -07:00
Tanish Manku 9537bbbb48 Land #1347: build and run the Apple-event dispatch tests on every platform
The macOS app code is not compiled by PR CI (Linux). The dispatch and its
tests do not need the Apple-event crate, so they now build everywhere and
check the opening and unsaved-changes paths against CadApp on each change.
2026-11-20 10:00:18 -07:00
Tanish Manku d83bf7be22 Merge #1347: macOS: open drawings from Finder, the Dock and open -a; keep the unsaved-changes prompt on quit
# Conflicts:
#	apps/cadcraft/Cargo.toml
#	apps/cadcraft/src/main.rs
#	docs/gaps.md
#	docs/target-app-parity.md
#	docs/ui-parity.md
2026-11-20 09:50:14 -07:00
Patrik LermonandClaude Opus 5.5 8725cc48b2 i18n(sv): translate 172 new strings
Brings the Swedish catalog up to date with upstream main (a770fa5a).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 10:21:05 +01:00
Patrik Lermon a4364499d4 Merge upstream/main into swedish-ui-2026-11-07 2026-11-19 09:59:44 +01:00
Davit Matchakhelidze 6fb27ffa9e Merge origin/main into ka-update-2026-11-07 2026-11-18 15:06:41 +04:00
Davit Matchakhelidze b84f6a8994 i18n(ka): leave the rows of #2900 to that PR 2026-11-18 04:55:22 +04:00
Davit Matchakhelidze a0f3f25760 i18n(ka): update the Georgian catalog 2026-11-18 04:54:20 +04:00
Walter Haslbeck b69dc2a380 Merge main (ed0fbce2) into fix/2646-proxy-graphics 2026-11-16 10:21:09 +01:00
markmonkey 9b05dbed43 Reuse existing drawing tabs when reopening paths 2026-11-16 11:16:11 +08:00
SoldierPePe 59d5d20ab2 Merge remote-tracking branch 'origin/main' into i18n/ar-trim-stretch-point
# Conflicts:
#	crates/ui-egui/src/i18n/tests.rs
2026-11-16 02:02:48 +03:00
Patrik LermonandClaude Opus 5.5 32d5bd85db i18n(sv): update the Swedish catalog
Brings the Swedish catalog up to date with upstream main (7064a685).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 15:46:19 +01:00
Patrik Lermon a684cd506d Merge upstream/main into swedish-ui-2026-11-07 2026-11-15 15:34:55 +01:00
Davit Matchakhelidze b4ca4fd2b0 Merge origin/main into ka-update-2026-11-07 2026-11-14 20:36:13 +04:00
Walter Haslbeck 787929ee50 Merge origin/main into fix/2646-proxy-graphics
Both sides added a test at the same place in crates/render/src/tests.rs; both are kept.
2026-11-12 07:35:17 +01:00
Vincent Cloutier c421d2005b PR #2979: refresh shared DXF dependency imports 2026-11-11 21:01:36 -05:00
YannFR81 6ac52455d9 i18n(fr): credit the terminology review in the catalog header 2026-11-11 23:30:10 +01:00
YannFR81 4e482cf617 i18n(fr): align four shared rows with #2580
Dimension Space, Dimension Style Override and Object Snap Tracking (with its
F11 variant) are also changed by #2580. Use one wording in both pull requests
so they merge in either order:

- Dimension Space: "Espacer les cotes" (menu labels keep the infinitive)
- Dimension Style Override: "Remplacement de style de cote"
- Object Snap Tracking: "Repérage d'accrochage aux objets", as #2102 already
  uses for Object Snap Tracking Settings
2026-11-11 18:26:14 +01:00
YannFR81andClaude Opus 5.5 c17cbc9c73 i18n(fr): consistent French CAD terminology in existing rows
Follow-up to the French catalog: harmonises rows already on main, without
touching the rows added by #2102.

- Command-line prompts use the imperative (Sélectionnez, Spécifiez, Entrez),
  as the other prompts already did; menu and button labels keep the infinitive.
- A dimension object and its style are "cote" / "style de cote"; "Cotation"
  stays for the Dimension menu and Quick Dimension.
- Model space is "espace objet", Array is "réseau", a layout is a
  "présentation", tracking is "repérage" (object snap and polar).

Rebased on main after #2563: the prompts that lost their trailing "or" keep
the imperative wording on their new keys. The docs/localization-parity.md
row is left to the maintainers, as AGENTS.md asks.

Original wording written from CADCraft's English strings; no proprietary
localization resources were used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C4cGqxCFJD1m28x2aqwf7Q
2026-11-11 18:22:47 +01:00
Davit Matchakhelidze 0e40437d8f i18n(ka): Export = ექსპორტირება, Print = ბეჭდვა (the wording used across the Craft apps) 2026-11-11 02:06:36 +04:00
Vincent Cloutier 97903aa83a Merge official main font-test correction into PR2979 2026-11-10 09:54:37 -05:00
Vincent Cloutier 392b0e1678 PR2979: document DIMASSOC persistence contracts 2026-11-09 15:53:57 -05:00
Vincent Cloutier 52dfb93b8b fix(io): retain DIMASSOC in drawings and templates 2026-11-09 13:52:30 -05:00
Walter Haslbeck 7b81b92906 Merge origin/main into fix/2646-proxy-graphics
main now draws, measures, picks and transforms OLE2FRAME records (#2587), which are Unknown
too. Keep that working next to the proxy graphics:
- select: `kept_as_read` leaves out every Unknown but an OLE2FRAME, for picks, windows, ALL,
  Last, SELECT by handles and QSELECT;
- render and extents: one Unknown arm for a proxy's graphics and an OLE2FRAME's frame, in
  `draw_unknown` and `unknown_bounds`, which also keeps both functions within the cognitive
  complexity limit;
- new Unknown literals from main get `graphics: Vec::new()`.
2026-11-09 07:47:18 +01:00
SoldierPePe 410bdc733f i18n(ar): test that Stretch, Trim and Point keep words of their own 2026-11-08 07:24:34 +03:00
Patrik LermonandClaude Opus 5.5 2dd428dc2d i18n(sv): translate 41 new strings
Brings the Swedish catalog up to date with upstream main (865fa9af).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 08:48:19 +01:00
SoldierPePe 17da6ab38a i18n(ar): call Stretch «تمطيط», in the same form as the other edit verbs 2026-11-07 10:29:56 +03:00
SoldierPePe 53cebb9020 i18n(ar): tell Trim, Stretch and Extend apart, and call Point a point
Trim read «حدود التشذيب» ("trim boundaries"), Stretch read «تمديد», the
same word as Extend, and Point read «تأشير», the word the catalog uses
for Dimension. Trim is now «تشذيب», and its two selection prompts match
it (they said «قص», which is also Cut). Stretch, its grip and vertex
items and its selection prompt use «مط». Point is «نقطة», as in Point
Style and Single Point. Written from the meaning of the English strings.
2026-11-07 10:14:07 +03:00
Davit MatchakhelidzeandClaude Sonnet 5.5 9eb81b3588 i18n(ka): Georgian for 20 new strings
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 03:01:02 +04:00
Walter Haslbeck 34b4899eee fix(io): text styles keep the file's order too, so a saved proxy text keeps its style
A proxy text takes the first style whose font file it names. The drawing's styles started with
CADCraft's Standard, which the file's Standard replaced in place, so a file listing ISO before
Standard (both on the same font) was saved with Standard first, and the reopened text took it.
Reading now keeps the STYLE table in the file's order as well. Test:
`a_proxy_text_keeps_its_style_after_a_save`.
2026-11-04 14:04:25 +01:00
Walter Haslbeck 6ed01dea96 fix(io): layer and linetype tables keep the file's order, so saved proxies keep their layers; Last searches from the top
Proxy graphics name layers and linetypes by their index in the file's tables, and saving writes
the proxy unchanged. The drawing's LAYER table started with CADCraft's 0 and Defpoints and took
the file's layers after them, so a file without Defpoints at index 1 was saved with its layers
shifted: reopened, the proxy's graphics went to Defpoints, which never plots. Reading now orders
the layer and linetype tables as the file lists them (ByBlock and ByLayer first), with what
CADCraft adds after them. The round-trip test checks that the reopened graphics stay on BALLOONS.

Last searches the store from the top down (`EntityStore::iter_rev`) and stops at the first
selectable object instead of scanning the whole space.
2026-11-04 12:33:07 +01:00
Walter Haslbeck ce4b33ade2 fix(engine): Last takes the last selectable object; SELECT by handles leaves proxies out
Last skipped only proxies, so with a proxy drawn last it could take an object on a layer turned
off or frozen before it. It now takes the last object a selection may take in
(`select::selectable`), at "Select objects" and in STRETCH. SELECT given handles outright leaves
proxies out as well; other named objects are kept as before. The test covers both.
2026-11-04 11:42:57 +01:00
Walter Haslbeck 50a1f833ad fix(engine, doc): keep proxies out of every selection; leave out proxy circles and texts a matrix moves out of range
A proxy's graphics are drawn, measured and snapped to, but no command can edit a proxy, and
saving writes its record as read: a MOVE that took it in left it behind, a COPY stacked a second
one on top. So no selection takes a proxy in: picks, windows, fences, polygons, ALL, Last,
SELECTALL, group members and QSELECT leave it out (`select::selectable`). A test moves a window
round a line and a proxy: the line moves, the proxy stays.

A circle centre or text point that a finite but huge pushed matrix moves past the largest float
is left out, as a polyline's points already were, so no infinity reaches the extents.
2026-11-04 07:38:29 +01:00
Walter Haslbeck e36d1fde4b fix(doc): read UTF-16 proxy text with as_chunks (clippy chunks_exact_to_as_chunks); document the decoder's helpers 2026-11-03 10:26:32 +01:00
Walter Haslbeck 44a4e05506 contributors: add whaslbeck 2026-11-03 09:10:55 +01:00
Walter Haslbeck 0829bfa0eb feat(io, render): draw the proxy graphics of ACAD_PROXY_ENTITY (#2646)
An ACAD_PROXY_ENTITY carries the picture its application left for
programs without it (groups 92/160 and 310); AutoCAD draws it with
PROXYSHOW 1. CADCraft read these entities but drew nothing, so AutoCAD
Mechanical balloons, notes and the like were missing from screen, plots
and extents.

- doc: a decoder for the proxy graphics (ODA DWG specification, "Proxy
  Entity Graphics") into read-only entities: circles, arcs, polylines,
  filled polygons (solid hatch), TEXT/TEXT2 and their Unicode forms,
  colour, layer, linetype, lineweight, ltscale, fill and model matrices.
  Bounds-checked, with capped sizes and counts. TEXT2 draws the number
  of characters its length field gives.
- io: Unknown gets `graphics`, filled for ACAD_PROXY_ENTITY while the
  DXF (and so the DWG bridge) is read. The graphics index layers and
  linetypes by the file's table order, which the reader keeps; CADCraft's
  own tables are ordered differently. The raw tags are written back
  unchanged.
- render, extents, prims: the graphics draw and measure like block
  contents (layer 0 and ByBlock are the proxy's own), and can be picked.
2026-11-03 09:10:55 +01:00
Oliver HagmannandClaude Opus 5.5 2bd916661d Object snaps: a click across spaces picks as before; viewports stay apart in Tab's list
osnap_all ranked paper-space snaps and snaps seen through viewports in
one list, so a farther Endpoint through a viewport could come before a
closer paper-space Nearest and take the click. The click's snap now
comes first as main picks it (a viewport's best replaces paper space's
only when it scores closer); the rest follow in Tab order.

Two snaps at one paper point from different viewports (overlapping
viewports showing different model points) are no longer merged: each
keeps its model point for DIST.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 06:50:22 +01:00
Oliver HagmannandClaude Fable 5.1 b3a1e1af40 Object snaps: Tab cycles every candidate snap under the cursor, not one per mode
Tab cycling offered the closest snap of each running mode: two endpoints
within the aperture, or a circle's tangent and perpendicular at the same
spot, could not both be reached. `snap::osnap_all` now returns every
object snap within the aperture, ranked as `osnap` picks: specific
snaps nearest first (Endpoint and Intersection favoured a little), then
deferred tangents and perpendiculars, then Nearest, without repeats;
`osnap` is its first entry, so the pick order is unchanged.
`pointmod::snap_candidates` cycles that list. Snaps seen through layout
viewports are included.

Split from #1582 as asked in review; the display settings (magnet,
aperture box, marker and tooltip switches) stay there.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-03 06:50:22 +01:00
filipemirilli 5f44be5bdf Recognize AutoCAD DWG and LibreOffice DXF document types 2026-10-15 14:23:43 -03:00
filipemirilli 3e4068246d Document Finder opening and unsaved quit handling 2026-10-15 14:23:38 -03:00
filipemirilli 032b73347c Update Finder opening evidence without changing parity scores 2026-10-15 14:23:24 -03:00
filipemirilli 45065cc061 Record the macOS Finder opening gap as fixed 2026-10-15 14:23:21 -03:00
filipemirilliandIsaac Levine 7dc9e0ec6f Handle Finder opens and preserve unsaved Apple-event quit prompts
Add the safe macOS event bridge adapted from #683 and six opening/quit regression tests. All six cargo xtask ci gates passed, with 2,014 tests, plus packaged LaunchServices smoke tests.

Co-authored-by: Isaac Levine <isaacmlevine4@gmail.com>
2026-10-15 14:23:00 -03:00
filipemirilliandIsaac Levine 54d0e034e4 Connect Finder document events to the desktop application
Adapted from PR #683 to current main, retaining the existing accessibility dependency and async opening behavior. Validated together with the Apple-event module and regression tests.

Co-authored-by: Isaac Levine <isaacmlevine4@gmail.com>
2026-10-15 14:21:11 -03:00
filipemirilli 2a9c14e96e Enable the Apple-event bridge only on macOS 2026-10-15 14:18:47 -03:00
filipemirilli bfadb1a94e Pin the macOS Apple-event bridge dependency
Part of the tested fix for #158, adapted from #683. Full local cargo xtask ci and packaged macOS opening checks passed.
2026-10-15 13:09:54 -03:00
135 changed files with 5747 additions and 2661 deletions
+1
View File
@@ -60,3 +60,4 @@ jobs:
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+69
View File
@@ -0,0 +1,69 @@
# Accessibility
Source: `standards/app-accessibility.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib/blob/main/standards/app-accessibility.md); do not edit this copy directly. Propose changes to the shared statement in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib).
We want people who use screen readers, braille displays, screen magnifiers, voice control, high contrast, large text, reduced motion, or keyboard navigation to be able to get their work done in the Craft applications.
## Supported environments and how accessibility works
The Craft applications draw their own interface in Rust with `egui` and expose accessibility information through **AccessKit**:
- **Windows:** UI Automation (for tools such as NVDA, JAWS, and Narrator)
- **macOS:** NSAccessibility (VoiceOver)
- **Linux and FreeBSD:** AT-SPI (Orca)
- **Web (WebAssembly):** Browser accessibility tree in modern evergreen browsers
- **Display and motion:** Light and dark themes, along with ongoing work to honour system high-contrast, text-scaling, and reduced-motion settings
- **Headless and command-line workflows:** Most Craft applications also ship a command-line and automation binary (`<app>-cli`) that can inspect and edit documents from a terminal without using the graphical interface; see [This application](#this-application) below
**Current status:** The Craft suite is in early-alpha development. We use WCAG 2.2 and W3C's [WCAG2ICT](https://www.w3.org/TR/wcag2ict-22/) as practical reference points for user needs ([RFC-0014](https://github.com/storytold/craft-contrib/blob/main/rfcs/0014-accessibility.md)), while manual testing with assistive technologies across every tool and surface is still in progress.
## Known limitations and workarounds
Shared framework improvements are tracked in [storytold/craft-libs#437](https://github.com/storytold/craft-libs/issues/437). Current suite-wide gaps include:
- **Custom drawn surfaces (canvases, pages, grids, timelines, node graphs, and layer lists):** Some custom-painted views do not yet publish complete `AccessKit` nodes, caret bounds for magnifiers, or editable states (for example, `AccessKit`'s Windows adapter reporting `Document` nodes as read-only, which can prevent typing echo in screen readers). *Workaround:* Use structured inspector panels where available, or run headless commands through `<app>-cli` when a task does not need direct canvas interaction.
- **Focus in menus, toolbars, and dialogs:** Some popups, menus, or keyboard access-key overlays may leave focus in the underlying document or not yet restore focus cleanly when dismissed. *Workaround:* Press `Escape` to close open popups, `Alt` or `F10` for menu/toolbar navigation, and `F6` to move between major regions where supported.
- **Unannounced state changes:** Shortcuts or background tasks that change state away from focus do not yet consistently announce updates through a live region.
- **Pointer-heavy interactions:** Certain timeline, node-wiring, or object-placement gestures do not yet have non-dragging keyboard alternatives.
See [This application](#this-application) below for repository-specific links and details.
## Reporting an accessibility barrier
If you run into an accessibility barrier, please open an issue using the link in [This application](#this-application) below (or let us know in the [ArtCraft Discord](https://discord.gg/artcraft) if GitHub's issue form gets in the way).
- **No personal disclosure needed:** You never have to disclose a disability or explain why you use assistive technology.
- **Screenshots and recordings are optional:** Plain-text descriptions are always welcome and sufficient.
- **Helpful details to share (when convenient):**
- What you were trying to do, what happened, and what you expected
- Application version (or commit) and operating system or browser
- Input method, display settings, or assistive technology and version (for example, NVDA, JAWS, Narrator, VoiceOver, Orca, screen magnifier, high contrast, text scaling, or keyboard-only)
## How we respond
- **Triage and labels:** Maintainers and triagers label barrier reports with `accessibility` and set priority during triage based on impact—barriers that block a core workflow are treated as high-priority bugs, and barriers that risk losing work are critical.
- **Assistive-technology verification (`needs screen reader test`):** Pull requests that fix a reported assistive-technology barrier or add custom accessibility-tree or focus behaviour are labelled `needs screen reader test` so someone using assistive technology can verify a build and share what they observed; if the barrier remains, we reopen the issue.
## Note for contributors and coding agents
`ACCESSIBILITY.md` is a user-facing overview, **not** an extra rule set or audit checklist for coding agents:
- **Follow `AGENTS.md` and [`standards/accessibility.md`](https://github.com/storytold/craft-contrib/blob/main/standards/accessibility.md) for engineering work,** and keep every pull request scoped strictly to its issue. Do not widen an unrelated change to audit or rework surrounding UI.
- **Design for the actual user need—do not overbuild or apply naive readings of standards.** Accessibility guidelines exist to support real workflows and give flexible ways to meet them. Understand what a criterion genuinely requires in context before changing UI: for example, a button whose label or icon is legible and whose focus or selection ring already has clear contrast does **not** need its resting fill or border restyled to hit a 3:1 ratio, and inherently spatial or freehand tools should not have artificial keyboard grids bolted onto them.
- **Preserve visual design and shared primitives.** Use shared theme tokens and shared widgets from `storytold/craft-libs` instead of inventing one-off styling, contrast overrides, focus shims, or live-region scaffolding inside an application.
- **Be candid in pull requests.** Automated accessibility-tree checks never prove a change works with a real screen reader; describe only what was actually verified.
## Ownership
Maintained by the `craft-app-team` maintainers in [`storytold`](https://github.com/storytold). Shared updates belong in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib); repository-specific facts follow below.
## This application
**CADCraft** (`storytold/cadcraft`) is an open-source computer-aided design and drafting application written in pure Rust.
- **Published application builds:** macOS, Windows, Linux, FreeBSD, and Web (WebAssembly)
- **Command-line and automation interface:** `cadcraft-cli` provides headless terminal and automation access for scripted workflows without the graphical interface
- **Report an accessibility barrier:** [Open an issue in `storytold/cadcraft`](https://github.com/storytold/cadcraft/issues/new)
- **Tracked accessibility issues:** [Open issues labelled `accessibility` in `storytold/cadcraft`](https://github.com/storytold/cadcraft/issues?q=is%3Aissue+state%3Aopen+label%3Aaccessibility)
- **Pull requests awaiting assistive-technology verification:** [Pull requests labelled `needs screen reader test` in `storytold/cadcraft`](https://github.com/storytold/cadcraft/pulls?q=is%3Apr+label%3A%22needs+screen+reader+test%22)
- **Contributor and agent rules for this repository:** [`AGENTS.md`](AGENTS.md)
+4 -2
View File
@@ -19,7 +19,9 @@ Generated-in-code assets are original and have no file to list:
- the standard linetype and hatch-pattern libraries (`crates/doc/src/library.rs`; industry-common
names, our own dash/spacing values);
- the colour index palette, generated from its structure (`crates/color/src/lib.rs`);
- the sample drawings (`crates/engine/src/sample.rs`).
- the sample drawings (`crates/engine/src/sample.rs`);
- the synthetic two-hexagon hatch logo (`crates/io/tests/it/hatch_loop_flags.rs`, `logo`):
original contributor geometry, generated in code from invented points, under MIT OR Apache-2.0.
| Asset | Author | Source | Licence | Notes |
|---|---|---|---|---|
@@ -70,7 +72,7 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/bs.tsv` | Nine (@nine-codes) with Claude Code (AI-assisted) | Original Bosnian translations of CADCraft English strings, shared with storytold/craft-i18n `locales/bs/` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; not yet reviewed by a native speaker |
| `crates/ui-egui/src/i18n/cs.tsv` | @Losminek (AI-assisted) | Original Czech translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/ru.tsv` | @pechnikov2026-star | Original Russian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star | Original French translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `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/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 |
Generated
+12
View File
@@ -661,6 +661,7 @@ dependencies = [
"craft-window",
"eframe",
"egui",
"fmv-macos-events",
"hidapi",
"log",
"muda",
@@ -2056,6 +2057,17 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8"
[[package]]
name = "fmv-macos-events"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90642cf66dde7f205dc8b42dfe57b47d0f3a29f571b832742883ef512e23fe55"
dependencies = [
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
]
[[package]]
name = "foldhash"
version = "0.1.5"
+21 -1
View File
@@ -58,6 +58,7 @@ fn install_io() {
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
}
/// `path` as text, for the engine and io calls that take a file name as a string.
@@ -95,7 +96,7 @@ where
Ok(cli) => cli,
Err(e) => {
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
return match write!(to, "{}", e.render()) {
return match write!(to, "{}", e.render()).and_then(|()| to.flush()) {
Err(w) if w.kind() != std::io::ErrorKind::BrokenPipe => {
let _ = writeln!(err, "error: can't write the output: {w}");
1
@@ -165,6 +166,25 @@ mod tests {
assert_eq!(run(["--help"], &mut FailingWriter(std::io::ErrorKind::BrokenPipe), &mut Vec::new()), 0);
}
struct FailingFlush(std::io::ErrorKind);
impl Write for FailingFlush {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Err(self.0.into())
}
}
#[test]
fn a_failed_flush_of_help_exits_1_unless_the_pipe_is_closed() {
let mut err = Vec::new();
assert_eq!(run(["--help"], &mut FailingFlush(std::io::ErrorKind::StorageFull), &mut err), 1);
assert!(String::from_utf8_lossy(&err).starts_with("error: "));
assert_eq!(run(["--help"], &mut FailingFlush(std::io::ErrorKind::BrokenPipe), &mut Vec::new()), 0);
}
#[test]
fn write_atomic_replaces_file_and_leaves_no_staging_files() {
let dir = scratch_dir("replace");
+1 -1
View File
@@ -58,7 +58,7 @@ pub(crate) fn roundtrip(a: &RoundtripArgs, io: &mut Streams) -> Result {
if a.keep_saved {
opts.keep_saved = Some(out.join("saved"));
}
let report = corpus::run(&root, &files, &opts, &mut |i, n, rel| eprintln!("[{}/{n}] {rel}", i + 1));
let report = corpus::run(&root, &files, &opts, &mut |i, n, rel| io.errln(format_args!("[{}/{n}] {rel}", i + 1)));
for f in &report.files {
let routes: Vec<String> = f
.routes
+10 -2
View File
@@ -1,7 +1,7 @@
use super::args::{CmdStep, Drawing, RunArgs, Step};
use super::error::Result;
use super::open;
use super::output::{Streams, export, export_framed, export_window, model_views};
use super::output::{Streams, export, export_framed, export_window, model_views, undrawn_message};
use cadcraft_engine::Session;
use cadcraft_engine::doc::Handle;
use serde_json::Value;
@@ -216,7 +216,15 @@ pub(crate) fn run_cmds(a: &RunArgs, io: &mut Streams) -> Result {
export(&s, p, io)?;
}
if let Some(p) = export_to {
let window = if cadcraft_io::is_image(p) { export_window(&s, framing, Some(&before))? } else { None };
let window = if cadcraft_io::is_image(p) {
let window = export_window(&s, framing, Some(&before))?;
if let Some(message) = undrawn_message(s.doc()?, &p.to_string_lossy()) {
io.errln(format_args!("{message}"));
}
window
} else {
None
};
export_framed(&s, p, window, io)?;
}
Ok(())
+24 -2
View File
@@ -1,5 +1,5 @@
//! `convert` to an image says how many model-space entities it can't draw, by type, instead of
//! leaving them out silently (#1208). The exit code stays 0.
//! Image exports report how many model-space entities they can't draw, by type. The exit code
//! stays 0 (#1208).
use std::process::{Command, Output};
@@ -70,6 +70,28 @@ fn convert_to_an_image_warns_about_entities_it_cannot_draw() {
assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr));
}
#[test]
fn run_image_export_warns_about_undrawn_entities() {
let scratch = Scratch::new("run-undrawn");
let input = scratch.0.join("proxies.dxf");
std::fs::write(&input, PROXIES).unwrap();
let image = scratch.0.join("out.svg");
let out = cli(&["run", input.to_str().unwrap(), "--export", image.to_str().unwrap()]);
let err = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "{:?}: {err}", out.status);
assert!(image.is_file());
assert!(out.stdout.is_empty(), "the warning belongs on stderr");
let warnings: Vec<&str> = err.lines().filter(|l| l.contains("not drawn")).collect();
assert_eq!(warnings, [format!("{}: 3 entities not drawn (PDFUNDERLAY: 1, REGION: 2)", image.display())], "{err}");
let copy = scratch.0.join("copy.dxf");
let out = cli(&["run", input.to_str().unwrap(), "--export", copy.to_str().unwrap()]);
let err = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "{:?}: {err}", out.status);
assert!(copy.is_file());
assert!(!err.contains("not drawn"), "{err}");
}
/// An OLE2FRAME's frame outline is drawn, so an image export doesn't call it an undrawn entity (#2422); it
/// says once that the OLE content inside the frame is not drawn (review on #2587).
#[test]
+8
View File
@@ -949,3 +949,11 @@ fn json_output_is_pretty_unless_compact() {
assert_eq!(r.stdout.lines().count(), 2, "one line per --cmd result: {}", r.stdout);
assert_eq!(invoke(&["run", "--sample", "--compact"]).code, 2, "run takes no --compact");
}
#[test]
fn roundtrip_progress_uses_the_requested_stderr() {
run_cases(
"roundtrip-progress",
&[case("roundtrip progress", &["roundtrip", "{b}", "--same-format", "--no-census"], 0, Starts("b.dxf: opened;"), Line("[1/1] b.dxf"))],
);
}
+1
View File
@@ -132,6 +132,7 @@ mod web {
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
let Some(canvas) = app_canvas() else {
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
return;
+5
View File
@@ -62,6 +62,11 @@ winit = { version = "0.30", default-features = false, features = ["rwh_06"] }
# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already
# in Cargo.lock through eframe.
pollster = "1"
# Finder double-click, Open With, Dock drops and `open -a CADCraft plan.dxf` arrive as a
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle (#158). Keep the Objective-C
# handler behind a safe API, without relaxing the workspace's unsafe-code lint.
# Pinned exactly: review the implementation before bumping.
fmv-macos-events = "=0.1.0"
# Rust HID backends: no proprietary SDK or C HID library.
[target.'cfg(target_os = "windows")'.dependencies]
+211
View File
@@ -0,0 +1,211 @@
//! macOS open-documents and quit Apple events (#158).
//!
//! A Finder double-click, Open With, a drop on the Dock icon and `open -a CADCraft plan.dxf` don't
//! put the path in argv: LaunchServices sends the running (or just-launched) app a
//! `kAEOpenDocuments` ('odoc') Apple event. winit 0.30 doesn't handle it and owns the
//! `NSApplicationDelegate`, so AppKit answered "CADCraft cannot open files in the Drawing Exchange
//! Format format". Handling it ourselves needs Objective-C class declarations, i.e. `unsafe`, which
//! this workspace forbids. The pinned `fmv-macos-events` crate wraps exactly that, an
//! `NSAppleEventManager` handler registered before Finder's
//! launch event that leaves winit's delegate alone, behind a safe main-thread API.
use std::path::PathBuf;
use cadcraft_ui_egui::CadApp;
#[cfg(target_os = "macos")]
use fmv_macos_events::{Event, Inbox, Registration};
/// The shape of `fmv_macos_events::Event`, so [`dispatch`] and its tests also build and run where
/// that crate is not compiled (PR CI runs on Linux). On macOS the crate's own type is used.
#[cfg(not(target_os = "macos"))]
enum Event {
Open(Vec<PathBuf>),
Quit,
}
/// Keeps the Apple-event handlers registered; hold it until the event loop returns.
#[cfg(target_os = "macos")]
pub struct AppleEvents {
_registration: Registration,
inbox: Inbox,
}
#[cfg(target_os = "macos")]
impl AppleEvents {
/// Register the handlers. Call on the main thread before the event loop starts, so the event
/// that launched the app (a Finder double-click) is caught too.
pub fn install() -> Self {
let (registration, inbox) = Registration::install();
Self { _registration: registration, inbox }
}
/// The queue the app drains every frame ([`poll`]); events arriving later wake `ctx`.
pub fn connect(&self, ctx: &egui::Context) -> Inbox {
let ctx = ctx.clone();
self.inbox.set_wake(move || ctx.request_repaint());
self.inbox.clone()
}
}
/// The paths to hand to OPEN: UTF-8 and non-empty, each once, in the order they arrived. A second
/// copy of the same path (Finder sends one per selected item, and a drop can repeat) would open
/// the drawing twice.
fn openable(paths: impl IntoIterator<Item = PathBuf>) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for p in paths {
if let Some(s) = p.to_str().filter(|s| !s.is_empty())
&& !out.iter().any(|o| o == s)
{
out.push(s.to_string());
}
}
out
}
/// Dispatch a batch through the regular opening and unsaved-changes paths. Returns whether the
/// window may close now; a queued quit must not bypass the Save / Don't Save / Cancel prompt.
fn dispatch(events: impl IntoIterator<Item = Event>, app: &mut CadApp) -> bool {
let mut quit = false;
for e in events {
match e {
Event::Open(paths) => {
for p in openable(paths) {
app.open_path(std::path::Path::new(&p));
}
}
Event::Quit => quit = true,
}
}
quit && !app.request_quit()
}
/// Drain the inbox each frame; a quit closes the window like Cmd+Q, prompting for unsaved drawings.
#[cfg(target_os = "macos")]
pub fn poll(inbox: &Inbox, app: &mut CadApp, ctx: &egui::Context) {
if dispatch(inbox.drain(), app) {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
}
#[cfg(test)]
mod tests {
use super::{Event, dispatch, openable};
use cadcraft_engine::Session;
use cadcraft_ui_egui::closing::Choice;
use cadcraft_ui_egui::{CadApp, Services};
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
struct TestDir(PathBuf);
impl TestDir {
fn new() -> Self {
let dir = std::env::temp_dir().join(format!("cadcraft-apple-events-{}-{}", std::process::id(), NEXT_DIR.fetch_add(1, Ordering::Relaxed)));
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
}
impl Drop for TestDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn app() -> CadApp {
crate::install_io();
// The DWG written and read here is the test's own synthetic file; the app starts its DWG
// worker in `main`, which a test does not run.
cadcraft_io::dwg_worker::allow_in_process();
CadApp::new(Session::new(), Services::default())
}
fn settle(app: &mut CadApp) {
let deadline = Instant::now() + Duration::from_secs(10);
while app.opening.busy() && Instant::now() < deadline {
app.finish_opening();
std::thread::sleep(Duration::from_millis(5));
}
app.finish_opening();
assert!(!app.opening.busy(), "background opening completed");
}
#[test]
fn keeps_order_and_drops_duplicates_and_empty_paths() {
let paths = ["/a/plan.dxf", "", "/b/site.dwg", "/a/plan.dxf"].map(PathBuf::from);
assert_eq!(openable(paths), ["/a/plan.dxf", "/b/site.dwg"]);
assert!(openable(Vec::new()).is_empty());
}
#[cfg(unix)]
#[test]
fn skips_paths_that_are_not_utf8() {
use std::os::unix::ffi::OsStringExt;
let bad = PathBuf::from(std::ffi::OsString::from_vec(vec![b'/', 0xff, b'.', b'd', b'x', b'f']));
assert_eq!(openable([bad, PathBuf::from("/ok.dxf")]), ["/ok.dxf"]);
}
#[test]
fn opens_dwg_and_dxf_without_replacing_an_unsaved_drawing() {
// Writing and opening the DWG here needs the converter in this process: each test is its own.
cadcraft_io::dwg_worker::allow_in_process();
let dir = TestDir::new();
let dxf = dir.0.join("planta com espaços.dxf");
let dwg = dir.0.join("Documentac\u{327}a\u{303}o.dwg");
let bytes = b"0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0\n20\n0\n11\n10\n21\n10\n0\nENDSEC\n0\nEOF\n";
let drawing = cadcraft_io::read(bytes, "synthetic.dxf").unwrap();
std::fs::write(&dxf, bytes).unwrap();
std::fs::write(&dwg, cadcraft_io::write(&drawing, "synthetic.dwg").unwrap()).unwrap();
let mut app = app();
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
let original = app.session.docs[0].uid;
assert!(app.session.docs[0].is_dirty());
assert!(!dispatch([Event::Open(vec![dxf.clone(), dwg.clone(), dxf.clone(), PathBuf::new()])], &mut app));
settle(&mut app);
assert_eq!(app.session.docs.len(), 3, "each file is opened once alongside the unsaved drawing");
assert_eq!(app.session.docs[0].uid, original);
assert!(app.session.docs[0].is_dirty());
for path in [&dxf, &dwg] {
assert!(app.session.docs.iter().any(|d| d.path.as_deref() == path.to_str()));
}
}
#[test]
fn a_failed_open_reports_the_path_and_keeps_existing_drawings() {
let dir = TestDir::new();
let missing = dir.0.join("missing drawing.dwg");
let mut app = app();
let original = app.session.docs[0].uid;
assert!(!dispatch([Event::Open(vec![missing.clone()])], &mut app));
settle(&mut app);
assert_eq!(app.session.docs.len(), 1);
assert_eq!(app.session.docs[0].uid, original);
assert!(app.session.log.iter().any(|line| line.contains(missing.to_str().unwrap())));
}
#[test]
fn a_quit_event_asks_before_closing_unsaved_work_and_can_be_cancelled() {
let mut app = app();
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
assert!(!dispatch([Event::Quit], &mut app), "must not issue a window close before the answer");
assert!(app.close_prompt().is_some());
assert!(!app.quit_confirmed);
assert!(!app.quit_requested);
app.answer_close(Choice::Cancel);
assert!(app.close_prompt().is_none());
assert!(app.session.docs[0].is_dirty());
assert!(!app.quit_requested);
}
#[test]
fn a_quit_event_can_close_a_clean_session() {
let mut app = app();
assert!(dispatch([Event::Quit], &mut app));
assert!(app.close_prompt().is_none());
}
}
+25
View File
@@ -14,6 +14,8 @@
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(any(target_os = "macos", test))]
mod apple_events;
mod control_server;
mod desktop_theme;
mod env;
@@ -54,6 +56,9 @@ struct App {
/// The `movable` flag last set on the main window.
#[cfg(target_os = "macos")]
movable: Option<bool>,
/// Drawings and quit requests from Finder, the Dock and `open -a` (see `apple_events`).
#[cfg(target_os = "macos")]
apple_events: fmv_macos_events::Inbox,
}
impl App {
@@ -102,6 +107,9 @@ impl eframe::App for App {
}
}
}
// Drawings and quit requests from Finder, the Dock and `open -a` (macOS).
#[cfg(target_os = "macos")]
apple_events::poll(&self.apple_events, &mut self.cad, ctx);
// Consume control/open/screenshot queues and time-based autosave, including hidden ticks.
self.cad.guarded_logic(ctx);
// Host frame work runs here, once per frame, and so also on a hidden logic-only tick (which
@@ -176,6 +184,7 @@ pub fn install_io() {
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
}
fn services() -> Services {
@@ -437,6 +446,12 @@ fn main() -> eframe::Result {
b.with_close_requested_on_terminate(true);
}));
}
// Registered before the event loop starts, so it catches the Finder event that launched us as
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
#[cfg(target_os = "macos")]
let apple_events = apple_events::AppleEvents::install();
#[cfg(target_os = "macos")]
let apple_events = &apple_events;
eframe::run_native(
"CADCraft",
options,
@@ -500,6 +515,14 @@ fn main() -> eframe::Result {
for f in &files {
app.open_path(f);
}
// Start reading any launch-time documents before the first frame. Later events use
// this same inbox, including the normal unsaved-changes handling for quit requests.
#[cfg(target_os = "macos")]
let apple_events = {
let inbox = apple_events.connect(&cc.egui_ctx);
apple_events::poll(&inbox, &mut app, &cc.egui_ctx);
inbox
};
if app.session.docs.is_empty() {
// In the units the profile asks for (MEASUREINIT, restored above).
let metric = app.session.settings.measureinit;
@@ -527,6 +550,8 @@ fn main() -> eframe::Result {
menus_in_window: vars.no_native_menu == Switch::On,
#[cfg(target_os = "macos")]
movable: None,
#[cfg(target_os = "macos")]
apple_events,
}))
}),
)
+4
View File
@@ -144,6 +144,10 @@ impl NativeMenu {
self.last_refresh = now;
let typing = menus::text_field_window(ctx).is_some();
for (cmd, _, item) in self.items.values() {
// Open Recent rebuilds this item with the correct enabled state.
if cmd == menus::RECENT_CLEAR {
continue;
}
let en = (typing && menus::edits_text(cmd)) || cadcraft_engine::find_command(cmd).is_none_or(|c| (c.enabled)(&app.session).is_ok());
item.set_enabled(en);
}
+5
View File
@@ -123,6 +123,11 @@ sync_github_name = true
[people.helenkwok]
real_name = "Helen Kwok"
[people.whaslbeck]
real_name = "Walter Haslbeck"
display_name = "Walter Haslbeck"
sync_github_name = false
[people.V1dalTheAbidal]
sync_github_name = true
+9 -1
View File
@@ -43,6 +43,7 @@ mod curves;
mod dim;
mod fill;
mod layout;
mod proxy;
mod text;
mod wipeout;
@@ -52,12 +53,18 @@ pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, Polyface
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
pub use fill::{Gradient, Hatch, HatchLoop};
pub use layout::{Image, Table, TableCell, Viewport};
pub use proxy::{ProxyTables, proxy_entities};
pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign};
pub use wipeout::Wipeout;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Unknown {
pub dxf_type: String,
pub tags: Vec<RawTag>,
/// What an ACAD_PROXY_ENTITY draws: its proxy graphics as read-only entities, made when the
/// drawing is read (the graphics refer to table rows by their place in the file). Drawn and
/// measured like block contents; saving writes `tags` unchanged.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub graphics: Vec<Entity>,
}
impl Unknown {
@@ -264,7 +271,8 @@ impl EntityKind {
EntityKind::Image(i) => vec![Prim::Point(i.insert.xy())],
EntityKind::Table(t) => vec![Prim::Point(t.insert.xy())],
EntityKind::Tolerance(t) => vec![Prim::Point(t.insert.xy())],
EntityKind::Unknown(_) => Vec::new(),
// What its proxy graphics draw, so a proxy can be picked and snapped to.
EntityKind::Unknown(u) => u.graphics.iter().flat_map(|g| g.kind.prims()).collect(),
}
}
+5
View File
@@ -7,6 +7,11 @@ pub struct HatchLoop {
pub vertices: Vec<PolyVertex>,
#[serde(default)]
pub outer: bool,
/// Original DXF group 92 bits. Writing keeps only Derived (4), Textbox (8) and
/// Outermost (16), derives External (1) from `outer`, and sets Polyline (2).
/// None uses the flags of a locally created loop.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub boundary_flags: Option<i64>,
/// The objects the loop was made from (DXF group 97 count, 330 handles): an associative
/// hatch re-fills the loop from them when they change.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
+717
View File
@@ -0,0 +1,717 @@
//! The proxy graphics an ACAD_PROXY_ENTITY carries (DXF groups 92/160 and 310): the picture
//! the owning application left for programs that don't have it, drawn as AutoCAD draws it with
//! PROXYSHOW 1. The layout follows the Open Design Alliance's public DWG specification
//! ("Proxy Entity Graphics"): a header (total size, chunk count), then chunks of (size, type,
//! data), sizes in bytes including the 8-byte chunk header, all little-endian.
//!
//! The picture becomes ordinary, read-only entities: drawn and measured like the contents of a
//! block, with layer 0, ByBlock colour, linetype and lineweight standing for the proxy's own
//! until a chunk sets them. Chunks CADCraft doesn't decode (meshes, shells, lightweight
//! polylines, materials) are skipped.
use super::{Arc, Circle, Common, Entity, EntityKind, Handle, Hatch, HatchLoop, Line, Lineweight, LwPolyline, Text, Unknown};
use cadcraft_color::{Color, Rgb};
use cadcraft_geom::{PolyVertex, Vec2, Vec3};
/// Bytes of proxy graphics read at most from one entity.
const MAX_BYTES: usize = 16 << 20;
/// Entities made at most from one entity's proxy graphics.
const MAX_ENTITIES: usize = 100_000;
/// Vertices read at most from one polyline or polygon chunk.
const MAX_VERTICES: usize = 1_000_000;
/// Matrices pushed at most.
const MAX_MATRICES: usize = 64;
/// The table names proxy graphics refer to by index, in the order of the file's tables.
#[derive(Clone, Debug, Default)]
pub struct ProxyTables {
/// LAYER records in file order.
pub layers: Vec<String>,
/// LTYPE records in file order, without ByBlock and ByLayer (indices count only the others).
pub linetypes: Vec<String>,
/// Text styles (name, font file) in file order: a text chunk names its font, and the first
/// style with that font draws it.
pub styles: Vec<(String, String)>,
}
impl Unknown {
/// The proxy graphics bytes of an ACAD_PROXY_ENTITY: the 310 groups after its size group
/// (92, or 160 in newer files), cut to that size. Empty for other records, for an entity
/// without graphics and for one whose data isn't hex.
pub fn proxy_graphics_bytes(&self) -> Vec<u8> {
if !self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") {
return Vec::new();
}
let Some(at) = self.tags.iter().position(|t| t.code == 92 || t.code == 160) else { return Vec::new() };
let size = self.tags.get(at).and_then(|t| t.value.trim().parse::<usize>().ok()).unwrap_or(0).min(MAX_BYTES);
let mut out = Vec::with_capacity(size);
for t in self.tags.iter().skip(at + 1).take_while(|t| t.code == 310) {
// Damaged data draws nothing rather than a picture cut at a guess.
if !push_hex(&mut out, &t.value) {
return Vec::new();
}
if out.len() >= size {
break;
}
}
out.truncate(size);
out
}
}
/// Append the bytes of hex string `s`. False on a character that isn't a hex digit.
fn push_hex(out: &mut Vec<u8>, s: &str) -> bool {
let digits: Vec<u8> = s.trim().bytes().collect();
for pair in digits.chunks(2) {
let (Some(&hi), Some(&lo)) = (pair.first(), pair.get(1)) else { return false };
let (Some(hi), Some(lo)) = ((hi as char).to_digit(16), (lo as char).to_digit(16)) else { return false };
out.push((hi * 16 + lo) as u8);
}
true
}
/// The entities the proxy graphics `bytes` draw, all with `handle` (the proxy's): selecting one
/// selects the proxy.
pub fn proxy_entities(bytes: &[u8], tables: &ProxyTables, handle: Handle) -> Vec<Entity> {
let mut r = Decoder {
tables,
handle,
pen: Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..Common::default() },
fill: false,
matrices: Vec::new(),
out: Vec::new(),
};
let mut at = 8;
while let (Some(size), Some(kind)) = (u32_at(bytes, at), u32_at(bytes, at + 4)) {
let size = size as usize;
if size < 8 || r.out.len() >= MAX_ENTITIES {
break;
}
let Some(data) = bytes.get(at + 8..at.saturating_add(size)) else { break };
r.chunk(kind, data);
at += size;
}
r.out
}
struct Decoder<'a> {
tables: &'a ProxyTables,
handle: Handle,
/// Layer, colour, linetype and lineweight for the entities that follow.
pen: Common,
fill: bool,
/// Model transforms pushed by PUSH_MATRIX, innermost last (row-major 3x4 of the 4x4).
matrices: Vec<[f64; 12]>,
out: Vec<Entity>,
}
impl Decoder<'_> {
/// Decode one chunk of type `kind`: draw it, or change the pen for what follows.
fn chunk(&mut self, kind: u32, data: &[u8]) {
let mut b = Bytes { data, at: 0 };
match kind {
// CIRCLE: centre, radius, normal.
2 => {
if let (Some(c), Some(r)) = (b.point(), b.f64()) {
self.circle(c, r);
}
}
// CIRCLE_3P: three points on it.
3 => {
if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point())
&& let Some((c, r)) = circle_through(self.xy(p1), self.xy(p2), self.xy(p3))
{
self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r }));
}
}
// CIRCULAR_ARC: centre, radius, normal, start vector, sweep angle (around the normal).
4 => {
if let (Some(c), Some(r), Some(n), Some(v), Some(sweep)) = (b.point(), b.f64(), b.point(), b.point(), b.f64()) {
self.arc(c, r, n, v, sweep);
}
}
// CIRCULAR_ARC_3P: start, a point on the arc, end.
5 => {
if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point()) {
self.arc_3p(self.xy(p1), self.xy(p2), self.xy(p3));
}
}
// POLYLINE and POLYGON: a count, then the points.
6 | 7 => {
let Some(n) = b.u32() else { return };
let n = (n as usize).min(MAX_VERTICES);
let pts: Vec<Vec2> = (0..n).map_while(|_| b.point()).map(|p| self.xy(p)).collect();
self.polyline(pts, kind == 7);
}
// TEXT: position, normal, direction, height, width factor, oblique, string.
10 => {
if let (Some(p), Some(_), Some(dir), Some(h), Some(w), Some(o)) = (b.point(), b.point(), b.point(), b.f64(), b.f64(), b.f64()) {
let s = b.string();
self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font: String::new() });
}
}
// TEXT2: position, normal, direction, string, length (the characters drawn), raw
// flag, height, width factor, oblique, tracking, five style flags, font, big font.
11 => {
if let (Some(p), Some(_), Some(dir)) = (b.point(), b.point(), b.point()) {
let s = b.string();
let s = first_chars(s, b.u32());
b.skip(4);
if let (Some(h), Some(w), Some(o)) = (b.f64(), b.f64(), b.f64()) {
b.skip(8 + 20);
let font = b.string();
self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font });
}
}
}
// UNICODE_TEXT: as TEXT with a UTF-16 string.
36 => {
if let (Some(p), Some(_), Some(dir), Some(h), Some(w), Some(o)) = (b.point(), b.point(), b.point(), b.f64(), b.f64(), b.f64()) {
let s = b.unicode();
self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font: String::new() });
}
}
// UNICODE_TEXT2: as TEXT2 with UTF-16 strings, and bold, italic, charset, pitch and
// the typeface before the font file.
38 => {
if let (Some(p), Some(_), Some(dir)) = (b.point(), b.point(), b.point()) {
let s = b.unicode();
let s = first_chars(s, b.u32());
b.skip(4);
if let (Some(h), Some(w), Some(o)) = (b.f64(), b.f64(), b.f64()) {
b.skip(8 + 20 + 16);
let _typeface = b.unicode();
let font = b.unicode();
self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font });
}
}
}
// ATTRIBUTE_COLOR: ACI, 0 ByBlock, 256 ByLayer.
14 => {
if let Some(c) = b.u32() {
self.pen.color = Color::from_aci(i16::try_from(c).unwrap_or(256));
}
}
// ATTRIBUTE_LAYER: index into the layer table; an index past it leaves the layer.
16 => {
if let Some(name) = b.u32().and_then(|i| self.tables.layers.get(i as usize)) {
self.pen.layer = name.clone();
}
}
// ATTRIBUTE_LINETYPE: index into the linetypes other than ByBlock and ByLayer;
// 32766 is ByBlock, 32767 and anything past the table ByLayer.
18 => {
if let Some(i) = b.u32() {
self.pen.linetype = match i {
32766 => "ByBlock".into(),
_ => self.tables.linetypes.get(i as usize).cloned().unwrap_or_else(|| "ByLayer".into()),
};
}
}
// ATTRIBUTE_FILL: the next polygon is filled.
20 => self.fill = b.u32().is_some_and(|f| f != 0),
// ATTRIBUTE_TRUE_COLOR: a colour with its method in the top byte.
22 => {
if let Some(v) = b.u32() {
self.pen.color = match v >> 24 {
0xC0 => Color::ByLayer,
0xC1 => Color::ByBlock,
0xC2 => Color::True(Rgb::from_u32(v & 0x00FF_FFFF)),
0xC3 => Color::from_aci((v & 0xFF) as i16),
_ => self.pen.color,
};
}
}
// ATTRIBUTE_LINEWEIGHT: hundredths of a millimetre, or -1 ByLayer, -2 ByBlock,
// -3 the default.
23 => {
if let Some(v) = b.u32() {
self.pen.lineweight = Lineweight::from_dxf(i16::try_from(v as i32).unwrap_or(-1));
}
}
// ATTRIBUTE_LTSCALE.
24 => {
if let Some(s) = b.f64().filter(|s| s.is_finite() && *s > 0.0) {
self.pen.ltscale = s;
}
}
// PUSH_MATRIX, PUSH_MATRIX2: a 4x4 model transform for what follows; POP_MATRIX.
29 | 30 => {
let m: Vec<f64> = (0..16).map_while(|_| b.f64()).collect();
if let Some(m) = m.get(..12).and_then(|m| <[f64; 12]>::try_from(m).ok())
&& m.iter().all(|x| x.is_finite())
&& self.matrices.len() < MAX_MATRICES
{
self.matrices.push(m);
}
}
31 => {
self.matrices.pop();
}
_ => {}
}
}
/// Add an entity drawn with the current pen (up to [`MAX_ENTITIES`]).
fn push(&mut self, kind: EntityKind) {
if self.out.len() < MAX_ENTITIES {
self.out.push(Entity { handle: self.handle, common: self.pen.clone(), kind });
}
}
/// `p` through the pushed matrices, innermost first, in the XY plane.
fn xy(&self, p: Vec3) -> Vec2 {
let mut p = p;
for m in self.matrices.iter().rev() {
p = Vec3::new(
m[0] * p.x + m[1] * p.y + m[2] * p.z + m[3],
m[4] * p.x + m[5] * p.y + m[6] * p.z + m[7],
m[8] * p.x + m[9] * p.y + m[10] * p.z + m[11],
);
}
p.xy()
}
/// How much the pushed matrices scale lengths (1 without any).
fn scale(&self) -> f64 {
self.matrices.iter().map(|m| (m[0] * m[5] - m[1] * m[4]).abs().sqrt()).product()
}
/// A full circle around `c`, through the pushed matrices.
fn circle(&mut self, c: Vec3, r: f64) {
let r = r * self.scale();
let c = self.xy(c);
if r.is_finite() && r > 0.0 && c.is_finite() {
self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r }));
}
}
/// An arc around `c` from the direction `start`, turned by `sweep` around `normal`.
fn arc(&mut self, c: Vec3, r: f64, normal: Vec3, start: Vec3, sweep: f64) {
if !(r.is_finite() && r > 0.0 && sweep.is_finite() && sweep != 0.0) || start.xy().len() < 1e-12 {
return;
}
// The start point and the end point (the start vector turned by the sweep around the
// normal: clockwise in plan for a normal pointing down), through the matrices.
let dir = if normal.z < 0.0 { -1.0 } else { 1.0 };
let a0 = start.y.atan2(start.x);
let a1 = a0 + dir * sweep;
let on = |a: f64| c + Vec3::new(r * a.cos(), r * a.sin(), 0.0);
let mid = on((a0 + a1) / 2.0);
if sweep.abs() >= std::f64::consts::TAU - 1e-9 {
return self.circle(c, r);
}
self.arc_3p(self.xy(on(a0)), self.xy(mid), self.xy(on(a1)));
}
/// The arc from `p1` through `p2` to `p3`.
fn arc_3p(&mut self, p1: Vec2, p2: Vec2, p3: Vec2) {
let Some((c, r)) = circle_through(p1, p2, p3) else {
return self.polyline(vec![p1, p3], false);
};
let ang = |p: Vec2| (p.y - c.y).atan2(p.x - c.x);
let (a1, a2, a3) = (ang(p1), ang(p2), ang(p3));
let ccw = |from: f64, to: f64| (to - from).rem_euclid(std::f64::consts::TAU);
// Counter-clockwise from p1 to p3 when p2 lies on that way, else from p3 to p1.
let (start, end) = if ccw(a1, a2) <= ccw(a1, a3) { (a1, a3) } else { (a3, a1) };
self.push(EntityKind::Arc(Arc { center: c.to3(0.0), radius: r, start, end }));
}
/// A polyline, or a closed polygon: filled (a solid hatch) when ATTRIBUTE_FILL asked for it,
/// which applies to this one polygon only.
fn polyline(&mut self, pts: Vec<Vec2>, polygon: bool) {
let fill = std::mem::take(&mut self.fill);
if pts.iter().any(|p| !p.is_finite()) || pts.is_empty() {
return;
}
if polygon && fill && pts.len() >= 3 {
let vertices = pts.iter().map(|&p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect();
return self.push(EntityKind::Hatch(Hatch {
pattern: "SOLID".into(),
solid: true,
loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
style: 0,
elevation: 0.0,
gradient: None,
origin: Vec2::ZERO,
background: None,
pattern_lines: Vec::new(),
}));
}
match pts.as_slice() {
[a, b] if !polygon => self.push(EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) })),
_ => {
let vertices = pts.iter().map(|&p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect();
self.push(EntityKind::LwPolyline(LwPolyline { vertices, closed: polygon, const_width: 0.0, elevation: 0.0, plinegen: false }));
}
}
}
/// A single-line text, its style the first one whose font file the chunk names.
fn text(&mut self, t: TextChunk) {
let TextChunk { p, dir, height, width, oblique, value, font } = t;
let font = font.as_str();
let height = height * self.scale();
if !(height.is_finite() && height > 0.0) || value.is_empty() {
return;
}
let at = self.xy(p);
if !at.is_finite() {
return;
}
let towards = self.xy(p + dir) - at;
let rotation = if towards.len() > 1e-12 { towards.y.atan2(towards.x) } else { 0.0 };
let stem = |f: &str| f.trim().rsplit(['/', '\\']).next().unwrap_or_default().split('.').next().unwrap_or_default().to_ascii_lowercase();
let style = self
.tables
.styles
.iter()
.find(|(_, f)| !font.is_empty() && stem(f) == stem(font))
.map(|(n, _)| n.clone())
.unwrap_or_else(|| "Standard".into());
self.push(EntityKind::Text(Text {
insert: at.to3(0.0),
align_pt: None,
height,
value,
rotation,
width_factor: if width.is_finite() && width > 0.0 { width } else { 1.0 },
oblique: if oblique.is_finite() { oblique } else { 0.0 },
style,
halign: Default::default(),
valign: Default::default(),
}));
}
}
/// The first `length` characters of `s`: a text chunk may carry more text than it draws (the
/// rest of a note, drawn by the chunks after it). No length, or one past the end, keeps it all.
fn first_chars(s: String, length: Option<u32>) -> String {
match length.map(|n| n as usize) {
Some(n) if n > 0 && n < s.chars().count() => s.chars().take(n).collect(),
_ => s,
}
}
/// A text chunk: position, direction, height, width factor, oblique, string and font file.
struct TextChunk {
p: Vec3,
dir: Vec3,
height: f64,
width: f64,
oblique: f64,
value: String,
font: String,
}
/// The circle through three points (centre, radius), if they aren't on one line.
fn circle_through(a: Vec2, b: Vec2, c: Vec2) -> Option<(Vec2, f64)> {
let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));
if !d.is_finite() || d.abs() < 1e-12 {
return None;
}
let (a2, b2, c2) = (a.x * a.x + a.y * a.y, b.x * b.x + b.y * b.y, c.x * c.x + c.y * c.y);
let center =
Vec2::new((a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d, (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d);
let r = (a - center).len();
(center.is_finite() && r.is_finite() && r > 0.0).then_some((center, r))
}
/// The little-endian u32 at `at`, if `bytes` holds one there.
fn u32_at(bytes: &[u8], at: usize) -> Option<u32> {
bytes.get(at..at.checked_add(4)?).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)
}
/// A reader over one chunk's data. Strings are padded to four bytes.
struct Bytes<'a> {
data: &'a [u8],
at: usize,
}
impl Bytes<'_> {
/// The next `n` bytes, if there are that many.
fn take(&mut self, n: usize) -> Option<&[u8]> {
let s = self.data.get(self.at..self.at.checked_add(n)?)?;
self.at += n;
Some(s)
}
/// Pass over `n` bytes (reads after the end then find nothing).
fn skip(&mut self, n: usize) {
self.at = self.at.saturating_add(n);
}
/// A little-endian u32.
fn u32(&mut self) -> Option<u32> {
self.take(4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)
}
/// A little-endian double.
fn f64(&mut self) -> Option<f64> {
self.take(8).and_then(|b| b.try_into().ok()).map(f64::from_le_bytes)
}
/// Three doubles, if all are finite.
fn point(&mut self) -> Option<Vec3> {
let p = Vec3::new(self.f64()?, self.f64()?, self.f64()?);
(p.x.is_finite() && p.y.is_finite() && p.z.is_finite()).then_some(p)
}
/// Move on to the next multiple of four bytes, where padded strings end.
fn align(&mut self) {
self.at = self.at.saturating_add((4 - self.at % 4) % 4);
}
/// A zero-terminated string in the drawing's code page; bytes above 0x7F as Latin-1.
fn string(&mut self) -> String {
let rest = self.data.get(self.at..).unwrap_or_default();
let end = rest.iter().position(|&c| c == 0).unwrap_or(rest.len());
let s: String = rest.iter().take(end).map(|&c| c as char).collect();
self.at += end + 1;
self.align();
s
}
/// A UTF-16 string ended by a zero code unit.
fn unicode(&mut self) -> String {
let rest = self.data.get(self.at..).unwrap_or_default();
let (pairs, _) = rest.as_chunks::<2>();
let units: Vec<u16> = pairs.iter().map(|&p| u16::from_le_bytes(p)).take_while(|&u| u != 0).collect();
self.at += units.len() * 2 + 2;
self.align();
String::from_utf16_lossy(&units)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::RawTag;
/// A chunk of type `kind`, its data padded to four bytes.
fn chunk(kind: u32, data: &[u8]) -> Vec<u8> {
let mut d = data.to_vec();
d.resize(d.len().div_ceil(4) * 4, 0);
let mut out = ((8 + d.len()) as u32).to_le_bytes().to_vec();
out.extend(kind.to_le_bytes());
out.extend(d);
out
}
/// Proxy graphics: the header (total size, chunk count), then the chunks.
fn graphics(chunks: &[Vec<u8>]) -> Vec<u8> {
let body: Vec<u8> = chunks.concat();
let mut out = ((8 + body.len()) as u32).to_le_bytes().to_vec();
out.extend((chunks.len() as u32).to_le_bytes());
out.extend(body);
out
}
/// A point in the XY plane as three doubles.
fn pt(x: f64, y: f64) -> Vec<u8> {
[x, y, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect()
}
/// Two layers, two linetypes and two text styles.
fn tables() -> ProxyTables {
ProxyTables {
layers: vec!["0".into(), "BALLOONS".into()],
linetypes: vec!["Continuous".into(), "DASHED".into()],
styles: vec![("Standard".into(), "txt".into()), ("ISO".into(), "isocp.shx".into())],
}
}
/// A balloon as AutoCAD Mechanical stores one: layer, colour, a circle, the leader and the
/// number as TEXT2.
#[test]
fn a_balloon_becomes_circle_line_and_text() {
let mut text2 = pt(173.0, 112.0);
text2.extend(pt(0.0, 0.0).iter().take(16).chain(1.0f64.to_le_bytes().iter()));
text2.extend(pt(1.0, 0.0));
text2.extend(b"12\0\0");
text2.extend(2i32.to_le_bytes());
text2.extend(0i32.to_le_bytes());
for v in [6.0f64, 1.0, 0.0, 0.0] {
text2.extend(v.to_le_bytes());
}
text2.extend([0u8; 20]);
text2.extend(b"ISOCP.SHX\0\0\0\0\0");
let mut circle = pt(175.0, 115.0);
circle.extend(6.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0).iter().take(16).chain(1.0f64.to_le_bytes().iter()));
let mut leader = 2u32.to_le_bytes().to_vec();
leader.extend(pt(170.0, 111.0));
leader.extend(pt(150.0, 90.0));
let g = graphics(&[chunk(16, &1u32.to_le_bytes()), chunk(14, &1u32.to_le_bytes()), chunk(2, &circle), chunk(6, &leader), chunk(11, &text2)]);
let es = proxy_entities(&g, &tables(), Handle(0x35));
assert_eq!(es.len(), 3);
assert!(es.iter().all(|e| e.handle == Handle(0x35) && e.common.layer == "BALLOONS" && e.common.color == Color::Index(1)));
assert!(matches!(&es[0].kind, EntityKind::Circle(c) if c.center == Vec3::new(175.0, 115.0, 0.0) && c.radius == 6.0));
assert!(matches!(&es[1].kind, EntityKind::Line(l) if l.b == Vec3::new(150.0, 90.0, 0.0)));
assert!(matches!(&es[2].kind, EntityKind::Text(t) if t.value == "12" && t.height == 6.0 && t.style == "ISO" && t.rotation == 0.0));
}
/// A TEXT2 chunk draws only as many characters as its length says.
#[test]
fn text2_draws_its_length() {
let text2 = |value: &[u8], length: i32| {
let mut t = pt(0.0, 0.0);
t.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
t.extend(pt(1.0, 0.0));
t.extend(value);
t.extend(vec![0u8; 4 - value.len() % 4]);
t.extend(length.to_le_bytes());
t.extend(1i32.to_le_bytes());
for v in [2.5f64, 1.0, 0.0, 0.0] {
t.extend(v.to_le_bytes());
}
t.extend([0u8; 20]);
t.extend(b"txt\0");
let es = proxy_entities(&graphics(&[chunk(11, &t)]), &tables(), Handle(1));
match es.first().map(|e| &e.kind) {
Some(EntityKind::Text(t)) => t.value.clone(),
other => panic!("{other:?}"),
}
};
assert_eq!(text2(b"two lines\\Pof text", 9), "two lines");
assert_eq!(text2(b"whole", 0), "whole");
assert_eq!(text2(b"whole", 99), "whole");
}
/// Without layer and colour chunks the picture takes the proxy's own (layer 0, ByBlock).
#[test]
fn unset_traits_are_the_proxys() {
let mut leader = 3u32.to_le_bytes().to_vec();
for (x, y) in [(0.0, 0.0), (10.0, 0.0), (10.0, 5.0)] {
leader.extend(pt(x, y));
}
let es = proxy_entities(
&graphics(&[chunk(6, &leader), chunk(16, &u32::MAX.to_le_bytes()), chunk(18, &32766u32.to_le_bytes())]),
&tables(),
Handle(1),
);
let e = es.first().expect("polyline");
assert_eq!(
(e.common.layer.as_str(), e.common.color, e.common.linetype.as_str(), e.common.lineweight),
("0", Color::ByBlock, "ByBlock", Lineweight::ByBlock)
);
assert!(matches!(&e.kind, EntityKind::LwPolyline(p) if p.vertices.len() == 3 && !p.closed));
}
#[test]
fn a_filled_polygon_is_a_solid_hatch_and_fill_applies_once() {
let mut tri = 3u32.to_le_bytes().to_vec();
for (x, y) in [(0.0, 0.0), (4.0, 0.0), (2.0, 3.0)] {
tri.extend(pt(x, y));
}
let es = proxy_entities(&graphics(&[chunk(20, &1u32.to_le_bytes()), chunk(7, &tri), chunk(7, &tri)]), &tables(), Handle(1));
assert!(matches!(&es[0].kind, EntityKind::Hatch(h) if h.solid && h.loops[0].vertices.len() == 3));
assert!(matches!(&es[1].kind, EntityKind::LwPolyline(p) if p.closed));
}
/// A quarter arc counter-clockwise from 0°, and the same sweep around a downward normal,
/// which runs clockwise in plan (from 0° to -90°).
#[test]
fn arcs_follow_their_normal() {
let arc = |nz: f64| {
let mut a = pt(0.0, 0.0);
a.extend(2.0f64.to_le_bytes());
a.extend([0.0f64, 0.0, nz].iter().flat_map(|v| v.to_le_bytes()));
a.extend(pt(1.0, 0.0));
a.extend(std::f64::consts::FRAC_PI_2.to_le_bytes());
a.extend(0u32.to_le_bytes());
match proxy_entities(&graphics(&[chunk(4, &a)]), &tables(), Handle(1)).first().map(|e| e.kind.clone()) {
Some(EntityKind::Arc(a)) => (a.start, a.end, a.radius),
other => panic!("{other:?}"),
}
};
let (s, e, r) = arc(1.0);
assert!(s.abs() < 1e-9 && (e - std::f64::consts::FRAC_PI_2).abs() < 1e-9 && (r - 2.0).abs() < 1e-9);
let (s, e, _) = arc(-1.0);
assert!((s + std::f64::consts::FRAC_PI_2).abs() < 1e-9 && e.abs() < 1e-9, "{s} {e}");
}
#[test]
fn a_pushed_matrix_moves_what_follows_until_popped() {
let mut m = [0.0f64; 16];
(m[0], m[5], m[10], m[15], m[3], m[7]) = (2.0, 2.0, 1.0, 1.0, 100.0, 50.0);
let mut circle = pt(1.0, 1.0);
circle.extend(1.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0));
let push: Vec<u8> = m.iter().flat_map(|v| v.to_le_bytes()).collect();
let es = proxy_entities(&graphics(&[chunk(29, &push), chunk(2, &circle), chunk(31, &[]), chunk(2, &circle)]), &tables(), Handle(1));
assert!(matches!(&es[0].kind, EntityKind::Circle(c) if c.center == Vec3::new(102.0, 52.0, 0.0) && c.radius == 2.0));
assert!(matches!(&es[1].kind, EntityKind::Circle(c) if c.center == Vec3::new(1.0, 1.0, 0.0) && c.radius == 1.0));
}
/// A finite matrix can still move a point past the largest float: a circle or a text that
/// would land there is left out, as a polyline is, so no infinity reaches the extents.
#[test]
fn what_a_matrix_moves_out_of_range_is_left_out() {
let mut m = [0.0f64; 16];
(m[0], m[5], m[10], m[15], m[3]) = (1.0, 1.0, 1.0, 1.0, 1.7e308);
let push: Vec<u8> = m.iter().flat_map(|v| v.to_le_bytes()).collect();
let mut circle = pt(1e308, 0.0);
circle.extend(1.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0));
let mut text = pt(1e308, 0.0);
text.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
text.extend(pt(1.0, 0.0));
text.extend(b"far\0");
text.extend(0i32.to_le_bytes());
text.extend(1i32.to_le_bytes());
for v in [2.5f64, 1.0, 0.0, 0.0] {
text.extend(v.to_le_bytes());
}
text.extend([0u8; 20]);
text.extend(b"txt\0");
let es = proxy_entities(&graphics(&[chunk(29, &push), chunk(2, &circle), chunk(11, &text)]), &tables(), Handle(1));
assert!(es.is_empty(), "{es:?}");
// The same text without the matrix is drawn: the chunk itself is sound.
assert_eq!(proxy_entities(&graphics(&[chunk(11, &text)]), &tables(), Handle(1)).len(), 1);
}
#[test]
fn the_bytes_come_from_the_310_groups_after_the_size() {
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let u = Unknown {
dxf_type: "ACAD_PROXY_ENTITY".into(),
tags: vec![tag(90, "498"), tag(92, "5"), tag(310, "0102"), tag(310, "030405FF"), tag(93, "0")],
graphics: Vec::new(),
};
assert_eq!(u.proxy_graphics_bytes(), [1, 2, 3, 4, 5]);
let other = Unknown { dxf_type: "ACAD_PROXY_OBJECT".into(), ..u.clone() };
assert!(other.proxy_graphics_bytes().is_empty());
let bad = Unknown { tags: vec![tag(92, "4"), tag(310, "01zz")], ..u };
assert!(bad.proxy_graphics_bytes().is_empty());
}
/// Truncated chunks, sizes past the end, huge counts and garbage draw what they can and
/// never panic.
#[test]
fn hostile_graphics_do_not_panic() {
let mut huge = u32::MAX.to_le_bytes().to_vec();
huge.extend(pt(1.0, 1.0));
let mut nan = pt(f64::NAN, 0.0);
nan.extend(1.0f64.to_le_bytes());
let cases: Vec<Vec<u8>> = vec![
Vec::new(),
vec![0; 7],
graphics(&[chunk(6, &huge)]),
graphics(&[chunk(2, &nan)]),
graphics(&[chunk(11, &[0xFF; 30])]),
graphics(&[chunk(38, &[0x41; 77])]),
graphics(&[chunk(29, &[1; 40])]),
graphics(&[chunk(31, &[]), chunk(31, &[])]),
[graphics(&[chunk(2, &pt(0.0, 0.0))]), vec![0xFF; 9]].concat(),
{
let mut g = graphics(&[]);
g.extend(4u32.to_le_bytes());
g.extend(2u32.to_le_bytes());
g
},
{
let mut g = graphics(&[]);
g.extend(1_000u32.to_le_bytes());
g.extend(2u32.to_le_bytes());
g
},
];
for g in cases {
let _ = proxy_entities(&g, &tables(), Handle(1));
}
}
}
+2 -2
View File
@@ -37,7 +37,7 @@ pub struct RegionProps {
impl Region {
/// A region bounded by one closed loop.
pub fn from_loop(vertices: Vec<PolyVertex>) -> Region {
Region { loops: vec![HatchLoop { vertices, outer: true, sources: Vec::new() }] }
Region { loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }] }
}
pub fn polylines(&self) -> Vec<Polyline> {
@@ -170,7 +170,7 @@ mod tests {
let mut vertices: Vec<PolyVertex> =
(0..n).map(|k| PolyVertex::new(Vec2::new(c - half + 2.0 * half * k as f64 / n as f64, c - half))).collect();
vertices.extend([Vec2::new(c + half, c - half), Vec2::new(c + half, c + half), Vec2::new(c - half, c + half)].map(PolyVertex::new));
HatchLoop { vertices, outer, sources: Vec::new() }
HatchLoop { vertices, outer, boundary_flags: None, sources: Vec::new() }
}
#[test]
+30 -4
View File
@@ -371,6 +371,28 @@ fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blo
bounds_in(d, e, depth, blocks, off_counts)
}
/// The bounds of a record kept as read that draws something: a proxy as its proxy graphics draw
/// (layer 0 in them is the proxy's layer), each at the next depth as a block's contents are, and an
/// OLE2FRAME as its frame.
fn unknown_bounds<'a>(
d: &'a Drawing,
u: &crate::Unknown,
depth: usize,
blocks: &mut HashMap<(&'a str, usize), Bounds2>,
off_counts: bool,
) -> Bounds2 {
if u.graphics.is_empty() {
return ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points);
}
if depth >= MAX_BLOCK_DEPTH {
return Bounds2::EMPTY;
}
u.graphics
.iter()
.filter(|g| in_block_visible(d, g, off_counts))
.fold(Bounds2::EMPTY, |b, g| b.union(&bounds_in(d, g, depth + 1, blocks, off_counts)))
}
/// [`entity_bounds`] with the bounds of block contents (in block coordinates) already computed,
/// by block name and depth: every further reference to a block at that depth reuses them instead of
/// expanding the block again, so nested or self-referencing blocks cost at most one pass over each
@@ -516,8 +538,9 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
Bounds2::from_points([o, o + u, o + v, o + u + v])
}
EntityKind::LwPolyline(p) => lwpolyline_bounds(p),
// An OLE object's content is not drawn, but its frame is, so the frame counts (#2422).
EntityKind::Unknown(u) if u.is_ole_frame() => ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points),
// A proxy measures as its proxy graphics draw. An OLE object's content is not drawn, but its
// frame is, so the frame counts (#2422).
EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => unknown_bounds(d, u, depth, blocks, off_counts),
kind => {
let mut b = Bounds2::EMPTY;
for p in kind.prims() {
@@ -718,12 +741,15 @@ mod tests {
#[test]
fn ole_frame_counts_in_extents() {
let tag = |code: i32, value: &str| crate::RawTag { code, value: value.into() };
let frame = |tags: Vec<crate::RawTag>| EntityKind::Unknown(crate::Unknown { dxf_type: "OLE2FRAME".into(), tags });
let frame = |tags: Vec<crate::RawTag>| EntityKind::Unknown(crate::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() });
let b = bounds(frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")]));
assert_eq!((b.min, b.max), (Vec2::new(30.0, -22.0), Vec2::new(35.0, -19.0)));
assert!(bounds(frame(vec![tag(10, "1"), tag(20, "2")])).is_empty(), "one corner is not a frame");
assert!(bounds(frame(vec![tag(10, "NaN"), tag(20, "0"), tag(11, "1"), tag(21, "inf")])).is_empty());
assert!(bounds(EntityKind::Unknown(crate::Unknown { dxf_type: "OTHER".into(), tags: vec![tag(10, "5"), tag(20, "5")] })).is_empty());
assert!(
bounds(EntityKind::Unknown(crate::Unknown { dxf_type: "OTHER".into(), tags: vec![tag(10, "5"), tag(20, "5")], graphics: Vec::new() }))
.is_empty()
);
}
/// Groups 10/20 inside an application-defined `102 {...}` group belong to the application, not
+4
View File
@@ -53,6 +53,10 @@ impl ForeignExtra {
/// Everything of a file CADCraft keeps without modelling it.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Foreign {
/// Original two-point text and style, by entity handle and attribute position.
/// Kept with imported metadata so new entities never inherit another entity's fitting.
pub text_fits: BTreeMap<Handle, Vec<(crate::Text, crate::TextStyle)>>,
/// CLASS records (groups after `0 CLASS`) of the kept objects' and entities' types.
pub classes: Vec<Vec<RawTag>>,
/// Classes retain every source position, including duplicate names.
+1 -1
View File
@@ -39,7 +39,7 @@ pub use header::{HVal, Header};
pub use plotstyle::*;
pub use plotter::*;
pub use raster::{Raster, Rasters};
pub use refedit::{RefEdit, WorkItem, XrefSource};
pub use refedit::{RefEdit, WorkItem};
pub use store::EntityStore;
pub use tables::*;
pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES};
-30
View File
@@ -42,36 +42,6 @@ pub struct RefEdit {
/// Block objects taken out of the working set with their edits (block coordinates, the block
/// object's handle).
pub released: Vec<Entity>,
/// The nested references picked through to reach the edited block: block references inside
/// block definitions, outermost first. Empty when the picked reference's own block is edited.
pub path: Vec<Handle>,
/// Set when the edited block comes from an external reference: REFCLOSE Save writes it back
/// into its source drawing.
pub xref: Option<XrefSource>,
}
/// Where an xref edited in place is written back to.
#[derive(Clone, Debug, PartialEq)]
pub struct XrefSource {
/// The xref (its block name in this drawing).
pub xref: String,
/// The source drawing file.
pub file: String,
/// `file` with every symbolic link resolved when the edit began: the file that is written.
/// The save is refused when `file` leads somewhere else by then.
pub real: String,
/// The version the file was in when the edit began, as its `$ACADVER` code ("AC1015"): it
/// is written back in that version (`None`: in the drawing's own).
pub version: Option<String>,
/// Whether the file is a binary DXF (written back as one).
pub binary: bool,
/// The block of the source drawing being edited; `None` for its model space.
pub block: Option<String>,
/// The file's size and modification time when the edit began.
pub stamp: Option<(u64, std::time::SystemTime)>,
/// Edited block objects (their handles in this drawing) and the objects of the source
/// drawing they were loaded from.
pub sources: Vec<(Handle, Handle)>,
}
impl RefEdit {
+5
View File
@@ -57,6 +57,10 @@ impl EntityStore {
pub fn iter(&self) -> impl Iterator<Item = &Arc<Entity>> + '_ {
self.chunks.iter().flat_map(|c| c.items.iter())
}
/// Iterate from the top of the draw order down.
pub fn iter_rev(&self) -> impl Iterator<Item = &Arc<Entity>> + '_ {
self.chunks.iter().rev().flat_map(|c| c.items.iter().rev())
}
pub fn handles(&self) -> Vec<Handle> {
self.iter().map(|e| e.handle).collect()
}
@@ -346,6 +350,7 @@ mod tests {
}
assert!(s.move_next_to(Handle(1), Handle(3), true));
assert_eq!(order(&s), [2, 3, 1, 4, 5]);
assert_eq!(s.iter_rev().map(|e| e.handle.0).collect::<Vec<_>>(), [5, 4, 1, 3, 2], "top down");
assert!(s.move_next_to(Handle(5), Handle(2), false));
assert_eq!(order(&s), [5, 2, 3, 1, 4]);
assert!(!s.move_next_to(Handle(5), Handle(5), true));
-6
View File
@@ -728,11 +728,6 @@ pub struct Block {
/// The parameters of an associative array when this is an array block.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub array: Option<crate::ArrayParams>,
/// An xref's file as its loaded objects were read from it: size and modification time (as the
/// system gives it, so a time before 1970 is kept too). Kept per drawing, so an edit in place (REFEDIT) can tell whether
/// the file changed since this drawing loaded it (session state; not saved).
#[serde(skip)]
pub xref_stamp: Option<(u64, std::time::SystemTime)>,
}
/// The load state of an external reference.
@@ -779,7 +774,6 @@ impl Block {
explodable: true,
units: 0,
array: None,
xref_stamp: None,
}
}
}
+85
View File
@@ -60,6 +60,9 @@ pub fn specs() -> Vec<CommandSpec> {
attedit::dash_attedit_spec(),
wblock::wblock_spec(),
wblock::dash_wblock_spec(),
CommandSpec::new("wblockpick", "Write Block Pick", run_wblockpick)
.params("{mode: \"objects\"|\"base\"}")
.interactive(|_| Ok(Box::new(WblockPickM::default()))),
CommandSpec::new("base", "Base", run_base).menu(&["Draw", "Block", "Base"]).params("{at: [x,y]}"),
CommandSpec::new("blocks.dynamic", "Dynamic Block Data", run_dynamic)
.params("{name (a block, or \"*Model_Space\" for a drawing that is a dynamic block's own)} → {parameters, actions, other} | null (not a dynamic block)")
@@ -713,6 +716,88 @@ impl BlockM {
}
}
// ── WBLOCKPICK ────────────────────────────────────────────────────────────────
/// The result kept for the Write Block dialog after a WBLOCKPICK session ends.
pub struct WblockPicks {
/// Selected handles (mode "objects") — empty for a "base" pick.
pub handles: Vec<Handle>,
/// Base point picked (mode "base") — `None` for an "objects" pick.
pub base: Option<Vec2>,
}
fn run_wblockpick(_s: &mut Session, _p: &Value) -> Result<Value> {
ok()
}
/// Which pick session WBLOCKPICK is running.
#[derive(Default)]
enum WblockPickMode {
/// Waiting for the mode keyword ("objects" or "base").
#[default]
Waiting,
Objects(SelectPhase),
Base,
}
#[derive(Default)]
struct WblockPickM {
mode: WblockPickMode,
}
impl Interactive for WblockPickM {
fn name(&self) -> &'static str {
"WBLOCKPICK"
}
fn prompt(&self, _s: &Session) -> Prompt {
match &self.mode {
WblockPickMode::Waiting => Prompt::new("Enter pick mode", Accept::TEXT).kw(&["Objects", "Base"]),
WblockPickMode::Objects(sel) => sel.prompt(),
WblockPickMode::Base => Prompt::new("Specify insertion base point", Accept::POINT),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match &mut self.mode {
WblockPickMode::Waiting => {
match &i {
Input::Keyword(k) | Input::Text(k) => {
let k = k.to_ascii_lowercase();
if k.starts_with('o') {
self.mode = WblockPickMode::Objects(SelectPhase::default());
} else {
self.mode = WblockPickMode::Base;
}
}
Input::Cancel | Input::Enter => return Ok(Step::Cancel),
_ => {}
}
Ok(Step::Continue)
}
WblockPickMode::Objects(sel) => {
if matches!(i, Input::Cancel) {
return Ok(Step::Cancel);
}
match sel.feed(s, &i)? {
SelOutcome::More => Ok(Step::Continue),
SelOutcome::Empty => Ok(Step::Cancel),
SelOutcome::Done(hs) => {
s.wblock_picks = Some(WblockPicks { handles: hs, base: None });
Ok(Step::Done)
}
}
}
WblockPickMode::Base => match i {
Input::Cancel => Ok(Step::Cancel),
Input::Point(p) => {
s.wblock_picks = Some(WblockPicks { handles: Vec::new(), base: Some(p) });
Ok(Step::Done)
}
_ => Ok(Step::Continue),
},
}
}
}
mod insert_file;
pub(crate) mod library;
pub(crate) mod xref;
File diff suppressed because it is too large Load Diff
+4 -1
View File
@@ -16,7 +16,9 @@ use super::insert_file::stem;
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
pub(super) fn wblock_spec() -> CommandSpec {
CommandSpec::new("wblock", "Write Block", run_wblock).alias(&["w"]).params("{path, name? | handles?, base?}")
CommandSpec::new("wblock", "Write Block", run_wblock)
.alias(&["w"])
.params("{path, name? (a block, or \"*\" for the whole drawing) | handles?, base?}")
}
/// -WBLOCK erases the objects it writes, whatever its mOde option says: AutoCAD 2024 does, and
@@ -45,6 +47,7 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let base = point_param(p, "base");
let folder = new_folder(&path);
let (entities, bytes, lost, version) = match str_param(p, "name") {
Some("*") => write(s, "wblock", &path, Source::Whole)?,
Some(name) => write(s, "wblock", &path, Source::Block(name, base))?,
None => write(s, "wblock", &path, Source::Objects(&targets(s, p)?, base.unwrap_or(Vec2::ZERO)))?,
};
+11 -69
View File
@@ -134,7 +134,7 @@ struct Ctx {
}
/// The folder of the host drawing at `host` (a file path).
pub(crate) fn folder(host: Option<&Path>) -> Option<PathBuf> {
fn folder(host: Option<&Path>) -> Option<PathBuf> {
let p = host?.parent()?;
Some(if p.as_os_str().is_empty() { PathBuf::from(".") } else { p.to_path_buf() })
}
@@ -293,17 +293,8 @@ fn case_insensitive(p: &Path) -> Result<Option<PathBuf>, ()> {
Ok(out.is_file().then_some(out))
}
/// The first bytes of a file [`read`] keeps with the drawing (enough for a DWG's version and the
/// binary DXF sentinel).
const HEAD_BYTES: usize = 4096;
/// Read a drawing file through the host's io hooks, counting its bytes against the load's total.
/// Also returns the [`Stamp`] of the bytes read: taken from the opened file, so it describes them
/// even when the path is pointed at another file meanwhile; `None` when the file changed while it
/// was read (or the system can't tell its time), so an edit in place refuses until it is reloaded.
/// And the first [`HEAD_BYTES`] of those bytes, so what is told from them (a DWG's version, a
/// binary DXF) describes the same read.
fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>), String> {
fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
let hooks = super::super::super::file::io().ok_or("file formats are not available in this build")?;
#[cfg(not(target_arch = "wasm32"))]
{
@@ -312,9 +303,7 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>),
let left = MAX_XREF_TOTAL_BYTES.saturating_sub(cx.bytes);
let limit = MAX_XREF_BYTES.min(left);
let mut f = std::fs::File::open(file).map_err(|e| e.to_string())?;
let meta = f.metadata().map_err(|e| e.to_string())?;
let len = meta.len();
let before = stamp_of(&meta);
let len = f.metadata().map_err(|e| e.to_string())?.len();
let too_big = || {
if limit < MAX_XREF_BYTES {
format!("the referenced files are larger than {} MB together", MAX_XREF_TOTAL_BYTES >> 20)
@@ -332,10 +321,7 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>),
return Err(too_big());
}
cx.bytes = cx.bytes.saturating_add(n);
let after = f.metadata().ok().as_ref().and_then(stamp_of);
let read_as = before.filter(|b| Some(*b) == after);
let head = bytes.get(..HEAD_BYTES).unwrap_or(&bytes).to_vec();
Ok(((hooks.read)(&bytes, &file.to_string_lossy())?, read_as, head))
(hooks.read)(&bytes, &file.to_string_lossy())
}
#[cfg(target_arch = "wasm32")]
{
@@ -344,33 +330,6 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>),
}
}
/// A file's size and modification time: how an edit in place (REFEDIT) tells whether an xref's
/// file changed since it was read ([`cadcraft_doc::Block::xref_stamp`]). The time is kept as the
/// system gives it: counted from 1970, a file dated before then would have none and always look
/// changed.
pub(crate) type Stamp = (u64, std::time::SystemTime);
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
fn stamp_of(m: &std::fs::Metadata) -> Option<Stamp> {
Some((m.len(), m.modified().ok()?))
}
/// The [`Stamp`] of the file at `file` now.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn stamp(file: &Path) -> Option<Stamp> {
stamp_of(&std::fs::metadata(file).ok()?)
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn stamp(_file: &Path) -> Option<Stamp> {
None
}
/// Read the drawing file `file` (with the size limits of xref loading), with the [`Stamp`] and the
/// first bytes of the bytes read (see [`read`]).
pub(crate) fn read_file(file: &Path) -> Result<(Drawing, Option<Stamp>, Vec<u8>), String> {
read(file, &mut Ctx::new(None))
}
/// Load every xref of `d` that isn't unloaded from the paths saved in it; `host` is the drawing's
/// own path.
pub(crate) fn load_all(d: &mut Drawing, host: Option<&str>) -> Vec<Outcome> {
@@ -434,14 +393,8 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: &
let Some(path) = b.xref_path.clone() else { return (XrefStatus::Unresolved, "not an xref".into()) };
clear(d, &key);
let (status, detail) = match fetch(&path, host, chosen, cx, depth) {
Ok((x, file, read_as)) => match import(d, &key, &x, cx) {
Ok(()) => {
// This drawing's own baseline: another drawing loading the file later doesn't move it.
if let Some(b) = d.blocks.get_mut(&key) {
Arc::make_mut(b).xref_stamp = read_as;
}
(XrefStatus::Loaded, file.to_string_lossy().into_owned())
}
Ok((x, file)) => match import(d, &key, &x, cx) {
Ok(()) => (XrefStatus::Loaded, file.to_string_lossy().into_owned()),
Err(e) => {
// Whatever made it in before the failure goes again. A fetch that failed imported
// nothing, so it doesn't pay for a second scan of the block table.
@@ -456,13 +409,7 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: &
}
/// Read the drawing referenced as `path` and load its own attached xrefs into it.
fn fetch(
path: &str,
host: Option<&Path>,
chosen: bool,
cx: &mut Ctx,
depth: usize,
) -> Result<(Drawing, PathBuf, Option<Stamp>), (XrefStatus, String)> {
fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usize) -> Result<(Drawing, PathBuf), (XrefStatus, String)> {
let unresolved = |m: &str| (XrefStatus::Unresolved, m.to_string());
if depth >= MAX_BLOCK_DEPTH {
return Err(unresolved("xrefs are nested too deeply"));
@@ -476,7 +423,7 @@ fn fetch(
return Err(unresolved("too many referenced files"));
}
cx.files += 1;
let (mut x, read_as, _) = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?;
let mut x = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?;
cx.chain.push(canon);
let nested: Vec<String> =
x.blocks.values().filter(|b| b.xref_path.is_some() && !b.xref_overlay && !b.name.contains('|')).map(|b| b.name.clone()).collect();
@@ -487,20 +434,15 @@ fn fetch(
}
}
cx.chain.pop();
Ok((x, file, read_as))
}
/// The objects loading drawing `x` as an xref counts against [`MAX_XREF_OBJECTS`]: its model
/// space and every block's.
pub(crate) fn object_count(x: &Drawing) -> usize {
x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len()))
Ok((x, file))
}
/// Bring referenced drawing `x` into xref `key`: its model space becomes the block's objects, its
/// symbols and blocks are added as `key|name` (dependent symbols the host already has keep the
/// host's settings, so layer changes survive a reload).
fn import(d: &mut Drawing, key: &str, x: &Drawing, cx: &mut Ctx) -> Result<(), String> {
cx.objects = cx.objects.saturating_add(object_count(x));
let count = x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len()));
cx.objects = cx.objects.saturating_add(count);
if cx.objects > MAX_XREF_OBJECTS {
return Err(format!("more than {MAX_XREF_OBJECTS} objects"));
}
+11
View File
@@ -39,6 +39,10 @@ fn vertex_value(v: &Value) -> Option<PolyVertex> {
Some(PolyVertex { p, bulge: f64_or(v, "bulge", 0.0), start_width: f64_or(v, "startWidth", 0.0), end_width: f64_or(v, "endWidth", 0.0) })
}
fn current_elevation(s: &Session) -> Result<f64> {
Ok(s.doc()?.header.f64("ELEVATION", 0.0))
}
pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
let raw = p.get("vertices").or_else(|| p.get("points")).and_then(Value::as_array);
for v in raw.into_iter().flatten() {
@@ -53,6 +57,7 @@ pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
let mut k = lwpoly(vs, bool_or(p, "closed", false));
if let EntityKind::LwPolyline(pl) = &mut k {
pl.const_width = width;
pl.elevation = current_elevation(s)?;
}
added(s.add_entity(k)?)
}
@@ -174,6 +179,7 @@ impl Interactive for LineM {
#[derive(Default)]
pub(super) struct PlineM {
verts: Vec<PolyVertex>,
elevation: f64,
arc_mode: bool,
/// Total width at the start and end of the next segment (Width / Halfwidth answers).
start_w: f64,
@@ -191,6 +197,7 @@ impl PlineM {
fn entity(&self, closed: bool) -> EntityKind {
let mut k = lwpoly(self.verts.clone(), closed);
if let EntityKind::LwPolyline(pl) = &mut k {
pl.elevation = self.elevation;
// Every segment the same uniform width: store it as the constant width, as before.
let segs = if closed { pl.vertices.len() } else { pl.vertices.len().saturating_sub(1) };
let w = pl.vertices.first().map_or(0.0, |v| v.start_width);
@@ -259,6 +266,10 @@ impl Interactive for PlineM {
fn name(&self) -> &'static str {
"PLINE"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.elevation = current_elevation(s)?;
Ok(Step::Continue)
}
fn prompt(&self, s: &Session) -> Prompt {
if self.asking_width > 0 {
let unit = if self.half { "half-width" } else { "width" };
+1 -1
View File
@@ -232,7 +232,7 @@ impl Interactive for MTextM {
None => Prompt::new("Specify first corner", Accept::POINT),
Some(a) if !self.boxed() => Prompt::new("Specify opposite corner", Accept::POINT)
.kw(&["Height", "Justify", "Line spacing", "Rotation", "Style", "Width", "Columns"])
.base(a),
.corner(a),
_ if self.lines.is_empty() => Prompt::new("Enter text (use \\P for new paragraphs)", Accept::TEXT),
_ => Prompt::new("Enter next line of text (empty line to finish)", Accept::TEXT),
}
+3 -1
View File
@@ -593,7 +593,9 @@ fn run_select(s: &mut Session, p: &Value) -> Result<Value> {
} else if let Some(f) = points_param(p, "fence") {
crate::select::select_fence_in(s.doc()?, &space, s.viewport_frozen(), &f)
} else if ["handles", "handle"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
targets(s, p)?
// Handles named outright, less the proxies: no selection takes one in.
let d = s.doc()?;
targets(s, p)?.into_iter().filter(|h| !d.entity(*h).is_some_and(|e| crate::select::kept_as_read(&e.kind))).collect()
} else {
// Nothing to select with: the selection stays, also what the active viewport does not draw.
s.stored_selection()
+20 -7
View File
@@ -95,6 +95,15 @@ pub fn set_proxies_lost(f: ProxiesLost) {
let _ = PROXIES_LOST.set(f);
}
/// Version-specific DWG compatibility omissions, counted by the host's actual writer.
pub type DwgCompatLost = fn(&Drawing, Version) -> std::collections::BTreeMap<String, usize>;
static DWG_COMPAT_LOST: OnceLock<DwgCompatLost> = OnceLock::new();
pub fn set_dwg_compat_lost(f: DwgCompatLost) {
let _ = DWG_COMPAT_LOST.set(f);
}
/// What a DXF of `version` leaves out of `d` for its proxies' string streams (#3229): empty from
/// 2007 on. `d` is written as committed (a reference edit's working copies are not in the file).
fn proxies_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
@@ -721,13 +730,12 @@ fn adopt_source_group(out: &std::fs::File, src: &std::fs::Metadata) -> std::io::
/// ([`crate::atomic_write::write_atomic_with`]). Nothing
/// to keep when there is no file yet. A file that doesn't look like a drawing
/// ([`looks_like_drawing`]) is not backed up, and the `.bak` already there is left alone.
/// Returns whether the backup was written. Also used for an xref REFEDIT writes back.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn backup(path: &std::path::Path) -> std::io::Result<bool> {
fn backup(path: &std::path::Path) -> std::io::Result<()> {
let mut src = match std::fs::File::open(path) {
Ok(f) if f.metadata()?.is_file() => f,
Ok(_) => return Ok(false),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Ok(_) => return Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(e) => return Err(e),
};
let (head, tail, len) = ends(&mut src)?;
@@ -736,7 +744,7 @@ pub(crate) fn backup(path: &std::path::Path) -> std::io::Result<bool> {
// the roots (or to another computer) isn't looked at.
if !backup_replaced(&head, &tail, len, std::fs::symlink_metadata(&bak).is_ok()) {
log::warn!("save: {} doesn't look like a whole drawing; its backup is left as it was", path.display());
return Ok(false);
return Ok(());
}
// The backup is no more readable than the drawing, nor than the .bak it replaces (a private
// 0600 drawing or .bak stays private). The mode is set as the new file is created, so a
@@ -762,8 +770,7 @@ pub(crate) fn backup(path: &std::path::Path) -> std::io::Result<bool> {
}
std::io::Write::write_all(out, &head)?;
std::io::copy(&mut src, out).map(|_| ())
})?;
Ok(true)
})
}
/// Store the bytes, then mark the drawing saved under `path`. If storing fails the drawing keeps
@@ -925,6 +932,12 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap
*n = n.saturating_add(1);
}
}
if let Some(compatibility) = DWG_COMPAT_LOST.get() {
for (kind, count) in compatibility(d, version) {
let total = out.entry(kind).or_default();
*total = total.saturating_add(count);
}
}
out
}
+9 -4
View File
@@ -232,7 +232,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
let outer = found.outer;
let ob = Bounds2::from_points(outer.iter().copied());
let sources = handles_of(&owners, &found.outer_sources);
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, sources }];
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, boundary_flags: None, sources }];
// Islands: closed objects entirely inside the outer loop that don't contain the pick point.
if let Some(store) = d.space(&space) {
for e in store.iter() {
@@ -248,7 +248,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
let inside = pts.iter().all(|q| point_in_polygon(&outer, *q) || outer.iter().any(|o| o.near(*q, tol * 10.0)));
let same_as_outer = (cadcraft_geom::shoelace(&pts).abs() - cadcraft_geom::shoelace(&outer).abs()).abs() < tol.max(1e-6) * 1000.0;
if inside && !same_as_outer && !point_in_polygon(&pts, p) {
loops.push(HatchLoop { vertices: vs, outer: false, sources: vec![e.handle] });
loops.push(HatchLoop { vertices: vs, outer: false, boundary_flags: None, sources: vec![e.handle] });
}
}
}
@@ -260,7 +260,12 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
&& island.sources.iter().all(|&i| owners.get(i).and_then(|h| d.entity(*h)).is_some_and(|e| island_curve(d, e)));
if open_curves {
let sources = handles_of(&owners, &island.sources);
loops.push(HatchLoop { vertices: island.outline.into_iter().map(PolyVertex::new).collect(), outer: false, sources });
loops.push(HatchLoop {
vertices: island.outline.into_iter().map(PolyVertex::new).collect(),
outer: false,
boundary_flags: None,
sources,
});
}
}
Ok(loops)
@@ -271,7 +276,7 @@ pub(crate) fn loops_from_handles(s: &Session, hs: &[Handle]) -> Result<Vec<Hatch
let mut loops = Vec::new();
for h in hs {
if let Some(vs) = d.entity(*h).and_then(|e| closed_loop(d, e)) {
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), sources: vec![*h] });
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), boundary_flags: None, sources: vec![*h] });
}
}
if loops.is_empty() {
+1 -1
View File
@@ -197,7 +197,7 @@ fn follow(before: &Drawing, after: &Drawing, handle: Handle, h: &Hatch, checked:
match refill(from, after, l) {
Refill::Loop(vertices) => {
let sources = l.sources.iter().copied().filter(|s| exists(after, *s)).take(MAX_SOURCES).collect();
loops.push(HatchLoop { vertices, outer: l.outer, sources });
loops.push(HatchLoop { vertices, outer: l.outer, boundary_flags: l.boundary_flags, sources });
}
// An erased island: the hatch fills its area.
Refill::Erased if !l.outer => {}
+6 -2
View File
@@ -219,14 +219,18 @@ fn type_matches(e: &Entity, ty: Option<&str>) -> bool {
}
}
/// The candidate objects: the whole edit space, or the current selection.
/// The candidate objects: the whole edit space (without proxies, which no selection takes in), or
/// the current selection.
fn candidates(s: &Session, p: &Value) -> Result<Vec<Handle>> {
let apply = str_param(p, "applyTo").unwrap_or("drawing").to_ascii_lowercase();
if apply.starts_with("sel") || apply == "current" {
return Ok(s.selection());
}
let space = s.space();
Ok(s.doc()?.space(&space).map(|st| st.iter().take(MAX_SCAN).map(|e| e.handle).collect()).unwrap_or_default())
Ok(s.doc()?
.space(&space)
.map(|st| st.iter().take(MAX_SCAN).filter(|e| !crate::select::kept_as_read(&e.kind)).map(|e| e.handle).collect())
.unwrap_or_default())
}
fn run_qselect(s: &mut Session, p: &Value) -> Result<Value> {
+6 -6
View File
@@ -48,8 +48,6 @@ pub const FILES: &[&str] = &[
"publish",
"qsave",
"recover",
"refclose",
"refedit",
"reinit",
"saveas",
"script",
@@ -239,6 +237,7 @@ pub const NO_FILES: &[&str] = &[
"hatchedit",
"hatchgenerateboundary",
"hatchpick",
"wblockpick",
"overkill",
"block",
"-block",
@@ -262,8 +261,9 @@ pub const NO_FILES: &[&str] = &[
"attdisp.normal",
"attdisp.on",
"attdisp.off",
"refedit.levels",
"refedit",
"refset",
"refclose",
"bedit",
"bsave",
"bsaveas",
@@ -515,9 +515,9 @@ mod tests {
use std::collections::BTreeSet;
/// Words in a command's parameter doc that usually name a file. In these commands they don't:
/// `array` and `arraypath` follow a path of objects, `refedit.levels` reports paths of nested
/// references, and `blocks.reference.grips` reports a direction.
const NOT_FILES: &[&str] = &["array", "arraypath", "refedit.levels", "blocks.reference.grips"];
/// `array` and `arraypath` follow a path of objects, and `blocks.reference.grips` reports a
/// direction.
const NOT_FILES: &[&str] = &["array", "arraypath", "blocks.reference.grips"];
/// The words of a command's documentation, lower case.
fn words(doc: &str) -> BTreeSet<String> {
+4
View File
@@ -52,6 +52,7 @@ pub use cadcraft_doc as doc;
pub use cadcraft_fonts as fonts;
pub use cadcraft_geom as geom;
pub use cadcraft_render as render;
pub use cmd::blocks::WblockPicks;
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices};
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use prompt::{Accept, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
@@ -158,6 +159,8 @@ pub struct Session {
lisp_last: Option<std::result::Result<lisp::value::Value, String>>,
/// What the last HATCHPICK kept (the Hatch and Gradient dialog's picks).
pub hatch_picks: Option<cmd::hatch::HatchPicks>,
/// What the last WBLOCKPICK kept (the Write Block dialog's picks).
pub wblock_picks: Option<cmd::blocks::WblockPicks>,
/// The window's menu bar and tool bar as the UI shows them (it reports them every frame).
pub bars_shown: cmd::interface::InterfaceBars,
/// The bars MENUBAR or TOOLBAR asked to change, for the UI to apply.
@@ -221,6 +224,7 @@ impl Session {
lisp: lisp::LispState::default(),
lisp_last: None,
hatch_picks: None,
wblock_picks: None,
bars_shown: Default::default(),
bars_request: Default::default(),
pick_hint: None,
+13
View File
@@ -454,6 +454,19 @@ fn printing_many_lines_is_linear() {
assert_eq!(s.log.last().map(String::as_str), Some("a"));
}
#[test]
fn lisp_pline_keeps_current_elevation() {
let mut s = session();
ok(&mut s, r#"(setvar "ELEVATION" 800.0)"#);
ok(&mut s, r#"(command "_PLINE" '(0 0) '(1000 0) '(1000 100) "")"#);
assert_eq!(ok(&mut s, "(cdr (assoc 38 (entget (entlast))))"), "800.0");
ok(&mut s, r#"(setvar "ELEVATION" -2.5)"#);
s.execute("pline", &serde_json::json!({"vertices": [[0, 0], [10, 0]], "width": 2})).unwrap();
assert_eq!(ok(&mut s, "(cdr (assoc 38 (entget (entlast))))"), "-2.5");
assert_eq!(ok(&mut s, "(cdr (assoc 43 (entget (entlast))))"), "2.0");
}
#[test]
fn command_draws_and_one_routine_is_one_undo_step() {
let mut s = session();
+4 -13
View File
@@ -126,23 +126,14 @@ pub fn snap_name(m: u32) -> &'static str {
mode::ALL.iter().find(|(b, _)| *b == m).map_or("None", |(_, n)| *n)
}
/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
/// first, then the closest snap of each other mode in `osmode`, nearest first, without repeats.
/// The candidate snaps near `cursor` for Tab cycling: every object snap within the aperture, the
/// one [`crate::snap::osnap`] picks first and the rest in its order (specific snaps nearest
/// first, then deferred snaps, then Nearest), without repeats.
pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 {
return Vec::new();
}
let osnap = |m: u32| crate::snap::osnap(d, space, cursor, aperture, m, base, deferred);
let extra = osmode & mode::HATCH;
let mut per_mode: Vec<SnapHit> = mode::ALL.iter().filter(|(b, _)| osmode & b != 0).filter_map(|(b, _)| osnap(*b | extra)).collect();
per_mode.sort_by(|a, b| a.point.dist(cursor).total_cmp(&b.point.dist(cursor)));
let mut out: Vec<SnapHit> = osnap(osmode).into_iter().collect();
for h in per_mode {
if !out.iter().any(|o| o.mode == h.mode && o.point.near(h.point, aperture * 1e-6)) {
out.push(h);
}
}
out
crate::snap::osnap_all(d, space, cursor, aperture, osmode, base, deferred)
}
/// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with.
+1 -1
View File
@@ -79,7 +79,7 @@ pub struct Prompt {
/// pick arrives as the plain point it was picked at.
pub deferred: bool,
/// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit
/// cell): ortho does not bend the opposite corner, so the rectangle keeps its area.
/// cell, MTEXT): ortho does not bend the opposite corner, so the rectangle keeps its area.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub corner: bool,
/// The grip this prompt stretches (one hot grip at the STRETCH prompt), as (object, grip
+1 -1
View File
@@ -139,7 +139,7 @@ pub fn bracket() -> Drawing {
EntityKind::Hatch(Hatch {
pattern: "ANSI31".into(),
solid: false,
loops: vec![HatchLoop { vertices: rect_vertices(a, bb), outer: true, sources: Vec::new() }],
loops: vec![HatchLoop { vertices: rect_vertices(a, bb), outer: true, boundary_flags: None, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
+18 -10
View File
@@ -161,19 +161,25 @@ pub(crate) fn on_frozen_layer(frozen: &[String], e: &Entity) -> bool {
/// The last object of `store`, in draw order, that is not on one of the layers in `frozen`, the
/// layers frozen in the layout viewport the selection is made through: what the Last option
/// takes there. With no such layers it is the last object, whether the drawing shows it or not.
/// A proxy is passed over: no selection takes one in ([`kept_as_read`]).
pub(crate) fn last_in(store: &cadcraft_doc::EntityStore, frozen: &[String]) -> Option<Handle> {
if frozen.is_empty() {
return store.last().map(|e| e.handle);
}
store.iter().filter(|e| !on_frozen_layer(frozen, e)).last().map(|e| e.handle)
store.iter_rev().find(|e| !kept_as_read(&e.kind) && !on_frozen_layer(frozen, e)).map(|e| e.handle)
}
/// Whether a selection can take `e`: the drawing shows it ([`Drawing::is_visible`]) and it is not
/// Whether a selection can take `e`: the drawing shows it ([`Drawing::is_visible`]), it is not
/// on one of the layers in `frozen`, the layers frozen in the layout viewport the selection is
/// made through ([`crate::DocState::viewport_frozen`]; empty anywhere else). A viewport shows
/// model space, so `frozen` goes with a selection in model space only.
/// made through ([`crate::DocState::viewport_frozen`]; empty anywhere else), and commands can
/// edit it. A viewport shows model space, so `frozen` goes with a selection in model space only.
/// A proxy (or another record CADCraft keeps as it was read) is drawn and snapped to, but never
/// selected: commands can't edit it, and saving writes its record as it was read.
pub(crate) fn selectable(d: &Drawing, e: &Entity, frozen: &[String]) -> bool {
d.is_visible(e) && !on_frozen_layer(frozen, e)
d.is_visible(e) && !on_frozen_layer(frozen, e) && !kept_as_read(&e.kind)
}
/// Whether `k` is a record CADCraft keeps as it was read and commands can't edit: every
/// [`EntityKind::Unknown`] but an OLE2FRAME, which moves and scales with its frame.
pub(crate) fn kept_as_read(k: &EntityKind) -> bool {
matches!(k, EntityKind::Unknown(u) if !u.is_ole_frame())
}
/// Entities to test, in the order to test them, each with its bounds when already known.
@@ -599,7 +605,8 @@ mod tests {
#[test]
fn clicking_an_ole_frame_edge_selects_it() {
let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() };
let frame = |tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags });
let frame =
|tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() });
let mut d = Drawing::new_metric();
let h = d.add(&Space::Model, Common::default(), frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])).unwrap();
d.add(&Space::Model, Common::default(), frame(vec![tag(10, "80"), tag(20, "80")])).unwrap();
@@ -722,7 +729,7 @@ mod hatch_pattern_pick_tests {
fn square(lo: f64, hi: f64, outer: bool) -> HatchLoop {
let vertices = [(lo, lo), (hi, lo), (hi, hi), (lo, hi)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect();
HatchLoop { vertices, outer, sources: Vec::new() }
HatchLoop { vertices, outer, boundary_flags: None, sources: Vec::new() }
}
fn ansi31_hatch(loops: Vec<HatchLoop>) -> Drawing {
@@ -788,6 +795,7 @@ mod hatch_pattern_pick_tests {
let tri = HatchLoop {
vertices: [(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(),
outer: true,
boundary_flags: None,
sources: Vec::new(),
};
let d = solid_hatch(vec![tri], 0);
+1
View File
@@ -192,6 +192,7 @@ impl Session {
}
fn script_lines(&mut self, text: &str) -> Result<()> {
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
for line in text.lines() {
// Trailing spaces are inputs (Enter); other trailing whitespace (`\r`) is not.
let line = line.trim_end_matches(|c: char| c.is_whitespace() && c != ' ');
-3
View File
@@ -108,9 +108,6 @@ impl Session {
return Ok(Some(label));
}
let st = self.state_mut()?;
if let Some(why) = st.undo.last().and_then(|snap| cmd::blocks::refedit::undo_barrier(&st.doc, &snap.doc)) {
return Err(EngineError::Other(why));
}
let Some(snap) = st.undo.pop() else { return Ok(None) };
let cur = st.swap_in(snap);
let label = cur.label.clone();
+143 -59
View File
@@ -72,6 +72,33 @@ impl SnapHit {
None => crate::Input::Point(self.point),
}
}
fn plain(mode: u32, point: Vec2) -> SnapHit {
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None }
}
/// Where this hit sorts among the candidates near a cursor: specific snaps by distance
/// (Endpoint and Intersection favoured a little), then deferred snaps, then Nearest.
fn rank(&self, cursor: Vec2, aperture: f64) -> (u8, f64) {
let class = if self.deferred.is_some() {
1
} else if self.mode == mode::NEA {
2
} else {
0
};
(class, snap_score(self.mode, self.point, cursor, aperture))
}
/// The same snap as `o`: mode and point, from the same source (paper space, or one
/// viewport). Overlapping viewports can show different model points at one paper point;
/// each stays a candidate, since DIST measures in the model units of the viewport picked.
fn same(&self, o: &SnapHit) -> bool {
self.mode == o.mode
&& self.deferred.is_some() == o.deferred.is_some()
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
&& self.point.near(o.point, 1e-9 * (1.0 + self.point.len()))
}
}
/// The curve a deferred snap refers to.
@@ -211,6 +238,14 @@ pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u3
osnap_with(d, space, &ix, cursor, aperture, osmode, base, deferred)
}
/// Every object snap within `aperture` of `cursor`, the one [`osnap`] picks first and the rest
/// in the order Tab cycles them: specific snaps nearest first, then deferred snaps, then Nearest.
/// Snaps seen through layout viewports are included.
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
let ix = crate::spatial::index(d, space);
osnap_all_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred).0
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn osnap_with(
d: &Drawing,
@@ -237,19 +272,39 @@ pub(crate) fn osnap_with_neighborhood(
base: Option<Vec2>,
deferred: bool,
) -> (Option<SnapHit>, Option<Vec<Prim>>) {
let (all, prims) = osnap_all_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred);
(all.into_iter().next(), prims)
}
/// Every object snap near the cursor ([`osnap_all`]) and the local-space primitives gathered.
#[allow(clippy::too_many_arguments)]
fn osnap_all_with_neighborhood(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
) -> (Vec<SnapHit>, Option<Vec<Prim>>) {
if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) {
return (None, None);
return (Vec::new(), None);
}
let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
Some((hit, prims)) => (hit, Some(prims)),
None => (None, None),
let (mut all, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
Some((hits, prims)) => (hits, Some(prims)),
None => (Vec::new(), None),
};
let views = viewport::near(d, space, cursor, aperture);
if views.is_empty() {
return (best, near_prims);
return (all, near_prims);
}
let model = Space::Model;
let model_ix = crate::spatial::index(d, &model);
// What a click picks across spaces stays as it was: each space's best snap, and a viewport's
// replaces the best so far only when it scores closer. A paper-space Nearest can therefore
// beat an Endpoint seen through a viewport, which `ranked` alone would put first.
let mut pick = all.first().copied();
for view in views {
let model_cursor = view.to_model(cursor);
let model_aperture = aperture / view.scale;
@@ -257,7 +312,7 @@ pub(crate) fn osnap_with_neighborhood(
if !model_cursor.is_finite() || !(model_aperture.is_finite() && model_aperture > 0.0) || model_base.is_some_and(|p| !p.is_finite()) {
continue;
}
let hit = osnap_in(
let hits = osnap_in(
d,
&model,
&model_ix,
@@ -268,15 +323,36 @@ pub(crate) fn osnap_with_neighborhood(
deferred,
&view.viewport.frozen_layers,
Some(view.model_clip),
)
.and_then(|h| view.hit(h));
if let Some(hit) = hit
&& best.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
);
if let Some(hit) = hits.first().and_then(|h| view.hit(*h))
&& pick.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
{
best = Some(hit);
pick = Some(hit);
}
all.extend(hits.into_iter().filter_map(|h| view.hit(h)));
}
let mut out = ranked(all, cursor, aperture);
if let Some(pick) = pick {
out.retain(|h| !h.same(&pick));
out.insert(0, pick);
}
(out, near_prims)
}
/// `hits` best first ([`SnapHit::rank`]), without repeats.
fn ranked(mut hits: Vec<SnapHit>, cursor: Vec2, aperture: f64) -> Vec<SnapHit> {
hits.sort_by(|a, b| {
let (ca, sa) = a.rank(cursor, aperture);
let (cb, sb) = b.rank(cursor, aperture);
ca.cmp(&cb).then(sa.total_cmp(&sb))
});
let mut out: Vec<SnapHit> = Vec::with_capacity(hits.len());
for h in hits {
if !out.iter().any(|o| o.same(&h)) {
out.push(h);
}
}
(best, near_prims)
out
}
#[allow(clippy::too_many_arguments)]
@@ -291,10 +367,11 @@ fn osnap_in(
deferred: bool,
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<SnapHit> {
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).and_then(|(hit, _)| hit)
) -> Vec<SnapHit> {
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).map(|(hits, _)| hits).unwrap_or_default()
}
/// The snaps near the cursor in one space, best first, and the primitives gathered there.
#[allow(clippy::too_many_arguments)]
fn osnap_in_with_prims(
d: &Drawing,
@@ -307,7 +384,7 @@ fn osnap_in_with_prims(
deferred: bool,
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<(Option<SnapHit>, Vec<Prim>)> {
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?;
// Intersections between nearby primitives; Apparent Intersection also where their extensions
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
@@ -345,8 +422,8 @@ fn osnap_in_with_prims(
}
}
}
let hit = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
Some((hit, near_prims))
let hits = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
Some((hits, near_prims))
}
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
@@ -458,7 +535,8 @@ fn gather_in(
Some((cands, near_prims))
}
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps.
/// Ranks the gathered candidates within the aperture ([`ranked`]), adding the base-dependent
/// snaps, the deferred snaps and Nearest.
#[allow(clippy::too_many_arguments)]
fn finish(
mut cands: Vec<(u32, Vec2)>,
@@ -469,7 +547,7 @@ fn finish(
base: Option<Vec2>,
deferred: bool,
clip: Option<Bounds2>,
) -> Option<SnapHit> {
) -> Vec<SnapHit> {
// Perpendicular / tangent from the base point.
if let Some(bp) = base {
for p in near_prims {
@@ -507,20 +585,10 @@ fn finish(
}
}
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
let best = cands.iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).min_by(|a, b| {
// Prefer more specific modes when nearly equidistant.
let da = snap_score(a.0, a.1, cursor, aperture);
let db = snap_score(b.0, b.1, cursor, aperture);
da.total_cmp(&db)
});
if let Some((m, p)) = best {
return Some(SnapHit { point: *p, mode: *m, name: name_of(*m), viewport: None, deferred: None });
}
if base.is_none()
&& deferred
&& let Some(h) = deferred_hit(near_prims, cursor, aperture, osmode, clip)
{
return Some(h);
let mut hits: Vec<SnapHit> =
cands.into_iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).map(|(m, p)| SnapHit::plain(m, p)).collect();
if base.is_none() && deferred {
hits.extend(deferred_hits(near_prims, cursor, aperture, osmode, clip));
}
if osmode & mode::NEA != 0 {
// The closest point of all nearby objects, whatever their drawing order.
@@ -540,12 +608,13 @@ fn finish(
}
}
if let Some((_, p)) = nb {
return Some(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
hits.push(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
}
}
None
ranked(hits, cursor, aperture)
}
/// Prefer more specific modes when nearly equidistant.
fn snap_score(mode: u32, point: Vec2, cursor: Vec2, aperture: f64) -> f64 {
point.dist(cursor) - if mode == mode::INT || mode == mode::END { aperture * 0.15 } else { 0.0 }
}
@@ -848,9 +917,11 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
}
}
/// The nearest deferred tangent/perpendicular within `aperture` of `cursor`.
fn deferred_hit(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Option<SnapHit> {
let mut best: Option<(f64, SnapHit)> = None;
/// Every deferred tangent and perpendicular within `aperture` of `cursor`: one per curve and
/// mode, in drawing order (the caller ranks them), so Tab can cycle from the tangent to the
/// perpendicular on the same circle.
fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
let mut hits = Vec::new();
for p in prims {
let curve = match p {
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
@@ -859,32 +930,28 @@ fn deferred_hit(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip:
Prim::Infinite { base, dir, .. } => SnapCurve::Line { a: *base, b: *base + *dir },
_ => continue,
};
let (m, name, at) = match curve {
SnapCurve::Circle { center, radius } if osmode & mode::TAN != 0 => {
(mode::TAN, "Deferred Tangent", Circle::new(center, radius).closest(cursor))
}
SnapCurve::Circle { center, radius } if osmode & mode::PER != 0 => {
(mode::PER, "Deferred Perpendicular", Circle::new(center, radius).closest(cursor))
}
SnapCurve::Arc { center, radius, start, end } if osmode & mode::TAN != 0 => {
(mode::TAN, "Deferred Tangent", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
}
SnapCurve::Arc { center, radius, start, end } if osmode & mode::PER != 0 => {
(mode::PER, "Deferred Perpendicular", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
}
SnapCurve::Line { a, b } if osmode & mode::PER != 0 => {
// Pick on the drawn extent: a segment's own span, an xline/ray anywhere.
// Where the curve was picked: a circle's, an arc's or a segment's own span, an xline/ray
// anywhere.
let at = match curve {
SnapCurve::Circle { center, radius } => Circle::new(center, radius).closest(cursor),
SnapCurve::Arc { center, radius, start, end } => cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor),
SnapCurve::Line { a, b } => {
let l = cadcraft_geom::Line::new(a, b);
(mode::PER, "Deferred Perpendicular", if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) })
if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) }
}
_ => continue,
};
let dd = at.dist(cursor);
if at.is_finite() && clip.is_none_or(|c| c.contains(at)) && dd <= aperture && best.is_none_or(|(bd, _)| dd < bd) {
best = Some((dd, SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) }));
if !(at.is_finite() && clip.is_none_or(|c| c.contains(at)) && at.dist(cursor) <= aperture) {
continue;
}
let modes: &[(u32, &'static str)] = match curve {
SnapCurve::Circle { .. } | SnapCurve::Arc { .. } => &[(mode::TAN, "Deferred Tangent"), (mode::PER, "Deferred Perpendicular")],
SnapCurve::Line { .. } => &[(mode::PER, "Deferred Perpendicular")],
};
for &(m, name) in modes.iter().filter(|(m, _)| osmode & m != 0) {
hits.push(SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) });
}
}
best.map(|(_, h)| h)
hits
}
/// Solve a line whose ends may be deferred tangent/perpendicular snaps: returns its two
@@ -1121,6 +1188,23 @@ mod tests {
assert_eq!(h.name, "Intersection");
}
/// Tab cycling sees every snap within the aperture: specific snaps nearest first (Intersection
/// favoured), then deferred snaps, then Nearest, and no snap twice; the first is what `osnap`
/// picks.
#[test]
fn osnap_all_ranks_every_candidate() {
let d = drawing();
let modes = mode::END | mode::MID | mode::INT | mode::NEA;
let all = osnap_all(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false);
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA], "{all:?}");
assert_eq!(all[0].point, osnap(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false).unwrap().point);
// On the circle: its quadrant, then the deferred tangent and perpendicular at the same spot.
let all = osnap_all(&d, &Space::Model, Vec2::new(22.1, 0.1), 0.5, mode::QUA | mode::TAN | mode::PER, None, true);
let kinds: Vec<(u32, bool)> = all.iter().map(|h| (h.mode, h.deferred.is_some())).collect();
assert_eq!(kinds, [(mode::QUA, false), (mode::TAN, true), (mode::PER, true)], "{all:?}");
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, modes, None, false).is_empty());
}
#[test]
fn center_quadrant_tangent() {
let d = drawing();
-1
View File
@@ -311,7 +311,6 @@ mod tests {
explodable: true,
units: 0,
array: None,
xref_stamp: None,
};
blk.entities
.push(Entity::new(cadcraft_doc::Handle(1_000_000), EntityKind::Circle(cadcraft_doc::Circle { center: v3(0.0, 0.0), radius: 1.0 })));
-2
View File
@@ -81,8 +81,6 @@ const HEADER: &[(&str, Kind, Def)] = &[
("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
// XCLIP boundaries: 0 hidden, 1 shown and plotted, 2 shown but not plotted.
("XCLIPFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(2)),
// How much objects outside the working set fade while a reference is edited in place (REFEDIT).
("XFADECTL", Kind::Int(0, 90), Def::Int(50)),
];
/// The standard lineweights in hundredths of a millimetre.
+53
View File
@@ -746,6 +746,15 @@ fn script_runs_commands() {
assert!(matches!(&t.kind, EntityKind::Text(t) if t.value == "Hello world"));
}
#[test]
fn scripts_allow_one_leading_utf8_bom() {
for text in ["\u{feff}LINE 0,0 10,10\n\n", "\u{feff}; first comment\r\nLINE 0,0 10,10\r\n\r\n"] {
let mut s = Session::new();
s.script(text).unwrap();
assert_eq!(kinds(&s), vec!["Line"]);
}
}
#[test]
fn script_splits_line_at_keyword_prompt() {
let mut s = Session::new();
@@ -1552,6 +1561,50 @@ fn setvar_rejects_non_finite_text_for_real_variables() {
}
}
#[test]
fn a_proxy_is_drawn_but_no_selection_takes_it_in() {
// A proxy's graphics are drawn and measured, but saving writes its record unchanged: an edit
// could not hold. So a window round a line and a proxy, ALL, SELECTALL and a pick on the
// proxy's graphics leave the proxy out, and MOVE moves the line alone.
use cadcraft_doc::{Common, Entity, Handle, Line, Space, Unknown, entity_bounds};
use cadcraft_geom::Vec3;
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
let line = s.doc().unwrap().model.last().unwrap().handle;
let drawn = Entity::new(Handle(0), EntityKind::Line(Line { a: Vec3::new(0.0, 5.0, 0.0), b: Vec3::new(10.0, 5.0, 0.0) }));
let unknown = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: vec![drawn] };
let proxy = s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Unknown(unknown)).unwrap();
let bounds = |s: &Session| entity_bounds(s.doc().unwrap(), s.doc().unwrap().entity(proxy).unwrap(), 0);
let before = bounds(&s);
assert!(!before.is_empty(), "the proxy measures as its graphics");
s.idle_click(Vec2::new(5.0, 5.0), false).unwrap();
assert_eq!(s.selection(), Vec::<Handle>::new(), "a pick on the proxy's graphics");
s.idle_click(Vec2::new(-1.0, -1.0), false).unwrap();
s.idle_click(Vec2::new(11.0, 6.0), false).unwrap();
assert_eq!(s.selection(), vec![line], "a window round both");
s.execute("selectall", &json!({})).unwrap();
assert_eq!(s.selection(), vec![line], "SELECTALL");
s.execute("move", &json!({"delta": [0, 20]})).unwrap();
let d = s.doc().unwrap();
assert!(matches!(&d.entity(line).unwrap().kind, EntityKind::Line(l) if l.a.y == 20.0), "the line moved");
assert_eq!(bounds(&s), before, "the proxy stayed where its record puts it");
// Handles named outright leave the proxy out too.
s.execute("select", &json!({"handles": [proxy.hex(), line.hex()]})).unwrap();
assert_eq!(s.selection(), vec![line], "SELECT by handles");
// Last passes over the proxy drawn last: it takes the line.
s.set_selection(Vec::new());
s.start("erase").unwrap();
s.input(Input::Text("L".into())).unwrap();
s.input(Input::Enter).unwrap();
let d = s.doc().unwrap();
assert!(d.entity(line).is_none(), "Last took the line");
assert!(d.entity(proxy).is_some(), "the proxy is kept");
}
#[test]
fn additional_tools_keeps_compatible_command_ids() {
assert_eq!(crate::cmd::resolve_alias("-blockreplace"), "blockreplace");
+24 -1
View File
@@ -144,6 +144,26 @@ fn moving_or_copying_the_hatch_alone_ends_the_link() {
assert!(!hatch(&s, &h).associative);
}
#[test]
fn imported_boundary_flags_survive_refill_and_copy() {
let mut session = Session::new();
let boundary = handle(&session.execute("rectang", &json!({ "p1": [0, 0], "p2": [4, 2] })).unwrap());
let hatch_handle = handle(&session.execute("hatch", &json!({ "handles": [boundary.clone()] })).unwrap());
session.doc_mut().unwrap().model.modify(Handle::parse_hex(&hatch_handle).unwrap(), |entity| {
if let EntityKind::Hatch(hatch) = &mut entity.kind {
hatch.loops[0].boundary_flags = Some(7);
}
});
let expected = hatch(&session, &hatch_handle).loops[0].boundary_flags;
session.execute("move", &json!({ "handles": [boundary], "delta": [10, 0] })).unwrap();
assert_eq!(hatch(&session, &hatch_handle).loops[0].boundary_flags, expected);
let count = session.doc().unwrap().model.len();
session.execute("copy", &json!({ "handles": [hatch_handle], "delta": [30, 0] })).unwrap();
let copy = session.doc().unwrap().model.iter().skip(count).find(|entity| matches!(entity.kind, EntityKind::Hatch(_))).unwrap();
let EntityKind::Hatch(copied) = &copy.kind else { panic!("not a hatch") };
assert_eq!(copied.loops[0].boundary_flags, expected);
}
#[test]
fn non_associative_hatch_keeps_no_sources() {
let mut s = Session::new();
@@ -166,7 +186,10 @@ fn hostile_sources_never_panic() {
let k = EntityKind::Hatch(Hatch {
pattern: "ANSI31".into(),
solid: false,
loops: vec![HatchLoop { vertices: sq, outer: true, sources: sources.clone() }, HatchLoop { vertices: nan, outer: false, sources }],
loops: vec![
HatchLoop { vertices: sq, outer: true, boundary_flags: None, sources: sources.clone() },
HatchLoop { vertices: nan, outer: false, boundary_flags: None, sources },
],
scale: 1.0,
angle: 0.0,
associative: true,
+1 -1
View File
@@ -106,6 +106,7 @@ mod mocoro;
mod modify_curves;
mod mtext_columns;
mod mtext_options;
mod mtext_ortho;
mod multiline_attributes;
mod named_viewports;
mod named_views;
@@ -143,7 +144,6 @@ mod recent_commands;
mod rectang_ortho;
mod rectang_polygon_order;
mod refedit;
mod refedit_xref;
mod region;
mod rename_cmdline;
mod rotate_reference;
@@ -2,7 +2,7 @@
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
use cadcraft_engine::geom::{Vec2, Vec3};
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap};
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
use cadcraft_engine::{Input, Session};
use serde_json::json;
@@ -278,6 +278,46 @@ fn clipped_endpoints_do_not_hide_a_visible_candidate() {
assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none());
}
/// Across spaces a click keeps the snap it had before Tab cycling: a viewport's best snap
/// replaces paper space's only when it scores closer. Tab still reaches the other one.
#[test]
fn a_closer_paper_space_nearest_keeps_the_click_over_a_viewport_endpoint() {
let (mut d, paper) = drawing();
// A paper-space line 0.3 left of the model endpoint (0, 0), which the viewport shows at (95, 50).
d.add(&paper, Common::default(), EntityKind::Line(Line { a: Vec3::new(94.7, 48.0, 0.0), b: Vec3::new(94.7, 52.0, 0.0) })).unwrap();
let (cursor, modes) = (Vec2::new(94.8, 50.0), mode::END | mode::NEA);
let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap();
assert_eq!((hit.mode, hit.viewport), (mode::NEA, None), "{hit:?}");
assert!(hit.point.near(Vec2::new(94.7, 50.0), 1e-9), "{hit:?}");
let all = osnap_all(&d, &paper, cursor, 0.5, modes, None, false);
assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap");
assert!(
all.iter().any(|h| h.mode == mode::END && h.viewport.is_some() && h.point.near(Vec2::new(95.0, 50.0), 1e-9)),
"Tab reaches the viewport's endpoint: {all:?}"
);
}
/// Overlapping viewports can show different model points at one paper point; Tab offers each,
/// since DIST measures in the model units of the viewport picked.
#[test]
fn overlapping_viewports_each_offer_their_model_point() {
let (mut d, paper) = drawing();
// This viewport shows the model endpoint (20, 0) at paper (100, 50), a second one over it (0, 0).
edit_viewport(&mut d, &paper, |vp| vp.view_center = Vec2::new(20.0, 0.0));
let mut vp = match &d.entity(viewport(&d, &paper)).unwrap().kind {
EntityKind::Viewport(vp) => vp.clone(),
_ => panic!("viewport fixture"),
};
vp.view_center = Vec2::new(0.0, 0.0);
vp.id = 3;
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
let all = osnap_all(&d, &paper, Vec2::new(100.05, 50.04), 0.5, mode::END, None, false);
let mut models: Vec<Vec2> =
all.iter().filter(|h| h.point.near(Vec2::new(100.0, 50.0), 1e-9)).filter_map(|h| h.viewport).map(|v| v.point).collect();
models.sort_by(|a, b| a.x.total_cmp(&b.x));
assert_eq!(models, [Vec2::new(0.0, 0.0), Vec2::new(20.0, 0.0)], "{all:?}");
}
#[test]
fn viewport_frozen_layers_do_not_hide_paper_space_geometry() {
let (mut d, paper) = drawing();
+157
View File
@@ -0,0 +1,157 @@
//! MTEXT's opposite corner ignores ortho: the text box keeps its width and proportion (#3388).
use cadcraft_doc::{EntityKind, MText};
use cadcraft_engine::snap::tracking::CursorQuery;
use cadcraft_engine::{Input, Session};
use cadcraft_geom::{Bounds2, Vec2};
use serde_json::json;
/// Move the cursor to `raw` at the current prompt, as the canvas does.
fn hover(s: &mut Session, raw: Vec2) -> Vec2 {
let p = s.current_prompt().unwrap();
let q = CursorQuery { base: p.base, deferred: p.deferred, corner: p.corner, aperture: 1e-6, tol: 1e-6, now: 0.0, shift: false };
let c = s.snap_cursor(raw, &q).point;
s.cursor = c;
c
}
fn session(ortho: bool) -> Session {
let mut s = Session::new();
s.execute("setvar", &json!({ "name": "OSMODE", "value": 0 })).unwrap();
s.execute("setvar", &json!({ "name": "ORTHOMODE", "value": i32::from(ortho) })).unwrap();
s
}
fn last_mtext(s: &Session) -> MText {
match s.doc().unwrap().model.last().map(|e| e.kind.clone()) {
Some(EntityKind::MText(t)) => t,
k => panic!("no mtext: {k:?}"),
}
}
/// Place an MTEXT from `first` to a cursor click at `second`, returning the preview bounds,
/// in-place editor box `(insert, width)` and created entity `(insert, width)`.
fn click_mtext(ortho: bool, first: Vec2, second: Vec2) -> ((Vec2, Vec2), (Vec2, f64), (Vec2, f64)) {
let mut s = session(ortho);
s.cmdline(&format!("mtext {},{}", first.x, first.y)).unwrap();
let p = s.current_prompt().unwrap();
assert_eq!(p.message, "Specify opposite corner");
assert!(p.corner, "MTEXT opposite corner ignores ortho");
let c = hover(&mut s, second);
assert!(c.near(second, 1e-9), "opposite corner stays under the cursor: {c:?}");
let mut pv = Bounds2::EMPTY;
for e in s.preview(c) {
pv = pv.union(&cadcraft_doc::entity_bounds(s.doc().unwrap(), &e, 0));
}
s.input(Input::Point(c)).unwrap();
let ed = s.editing_mtext().unwrap();
s.input(Input::Text("Hello".to_string())).unwrap();
s.input(Input::Enter).unwrap();
assert!(s.current_prompt().is_none(), "MTEXT is done, still at {:?}", s.current_prompt().map(|p| p.message));
let t = last_mtext(&s);
assert_eq!(t.contents, "Hello");
((pv.min, pv.max), (ed.insert.xy(), ed.width), (t.insert.xy(), t.width))
}
#[test]
fn mtext_opposite_corner_ignores_ortho() {
let cases = [
// Wide box (dx > dy)
(Vec2::ZERO, Vec2::new(10.0, 3.0), Vec2::ZERO, Vec2::new(10.0, 3.0), Vec2::new(0.0, 3.0), 10.0),
// Tall box (dy > dx)
(Vec2::ZERO, Vec2::new(3.0, 10.0), Vec2::ZERO, Vec2::new(3.0, 10.0), Vec2::new(0.0, 10.0), 3.0),
// Opposite quadrant (negative dx and dy)
(Vec2::new(10.0, 10.0), Vec2::new(2.0, 4.0), Vec2::new(2.0, 4.0), Vec2::new(10.0, 10.0), Vec2::new(2.0, 10.0), 8.0),
];
for (first, second, min, max, insert, width) in cases {
let on = click_mtext(true, first, second);
assert!(on.0.0.near(min, 1e-9) && on.0.1.near(max, 1e-9), "preview bounds with ortho on: {:?}", on.0);
assert!(on.1.0.near(insert, 1e-9) && (on.1.1 - width).abs() < 1e-9, "editor box with ortho on: {:?}", on.1);
assert!(on.2.0.near(insert, 1e-9) && (on.2.1 - width).abs() < 1e-9, "entity box with ortho on: {:?}", on.2);
let off = click_mtext(false, first, second);
assert_eq!(off, on, "ortho changes nothing");
}
}
#[test]
fn mtext_coordinate_and_direct_distance_input_with_ortho() {
let mut s = session(true);
// Absolute coordinate input for the opposite corner.
s.cmdline("mtext 0,0").unwrap();
s.cmdline("10,3").unwrap();
let ed = s.editing_mtext().unwrap();
assert!(ed.insert.xy().near(Vec2::new(0.0, 3.0), 1e-9));
assert!((ed.width - 10.0).abs() < 1e-9);
s.input(Input::Text("Abs".to_string())).unwrap();
s.input(Input::Enter).unwrap();
let t = last_mtext(&s);
assert!(t.insert.xy().near(Vec2::new(0.0, 3.0), 1e-9));
assert!((t.width - 10.0).abs() < 1e-9);
// Relative coordinate input for the opposite corner.
s.cmdline("mtext 2,3").unwrap();
s.cmdline("@4,9").unwrap();
let ed = s.editing_mtext().unwrap();
assert!(ed.insert.xy().near(Vec2::new(2.0, 12.0), 1e-9));
assert!((ed.width - 4.0).abs() < 1e-9);
s.input(Input::Text("Rel".to_string())).unwrap();
s.input(Input::Enter).unwrap();
let t = last_mtext(&s);
assert!(t.insert.xy().near(Vec2::new(2.0, 12.0), 1e-9));
assert!((t.width - 4.0).abs() < 1e-9);
// Direct distance entry goes toward the cursor rather than along an axis.
s.cmdline("mtext 0,0").unwrap();
let c = hover(&mut s, Vec2::new(3.0, 4.0));
assert!(c.near(Vec2::new(3.0, 4.0), 1e-9));
s.cmdline("5").unwrap();
let ed = s.editing_mtext().unwrap();
assert!(ed.insert.xy().near(Vec2::new(0.0, 4.0), 1e-9));
assert!((ed.width - 3.0).abs() < 1e-9);
s.input(Input::Text("Dir".to_string())).unwrap();
s.input(Input::Enter).unwrap();
let t = last_mtext(&s);
assert!(t.insert.xy().near(Vec2::new(0.0, 4.0), 1e-9));
assert!((t.width - 3.0).abs() < 1e-9);
}
#[test]
fn mtext_escape_cancels_cleanly_with_ortho() {
let mut s = session(true);
// Cancel at the opposite-corner prompt.
s.cmdline("mtext 0,0").unwrap();
let c = hover(&mut s, Vec2::new(10.0, 3.0));
assert!(c.near(Vec2::new(10.0, 3.0), 1e-9));
s.cancel();
assert!(s.current_prompt().is_none());
assert!(s.editing_mtext().is_none());
assert!(s.doc().unwrap().model.is_empty());
// Cancel after picking the opposite corner (at the text prompt).
s.cmdline("mtext 0,0").unwrap();
let c = hover(&mut s, Vec2::new(10.0, 3.0));
s.input(Input::Point(c)).unwrap();
assert!(s.editing_mtext().is_some());
s.cancel();
assert!(s.current_prompt().is_none());
assert!(s.editing_mtext().is_none());
assert!(s.doc().unwrap().model.is_empty());
}
#[test]
fn line_and_pline_still_obey_ortho() {
let mut s = session(true);
s.cmdline("line 0,0").unwrap();
let p = s.current_prompt().unwrap();
assert!(!p.corner, "LINE next point is constrained by ortho");
let c = hover(&mut s, Vec2::new(10.0, 3.0));
assert!(c.near(Vec2::new(10.0, 0.0), 1e-9), "ortho keeps LINE horizontal: {c:?}");
s.cancel();
s.cmdline("pline 0,0").unwrap();
let p = s.current_prompt().unwrap();
assert!(!p.corner, "PLINE next point is constrained by ortho");
let c = hover(&mut s, Vec2::new(3.0, 10.0));
assert!(c.near(Vec2::new(0.0, 10.0), 1e-9), "ortho keeps PLINE vertical: {c:?}");
s.cancel();
}
+23
View File
@@ -1,7 +1,9 @@
//! OFFSET Erase/Layer/Multiple/Undo and the MOVE/COPY Displacement option at the command line.
use cadcraft_engine::Input;
use cadcraft_engine::Session;
use cadcraft_engine::doc::EntityKind;
use cadcraft_engine::geom::Vec2;
use serde_json::json;
/// Every line as ((ax, ay), (bx, by), layer), sorted by the first y.
@@ -62,6 +64,27 @@ fn offset_multiple_and_undo() {
assert_eq!(lines(&s), vec![l((0.0, 0.0), (10.0, 0.0), "0"), l((0.0, 2.0), (10.0, 2.0), "0"), l((0.0, 4.0), (10.0, 4.0), "0")]);
}
// Regression test for #618: OFFSET's distance prompt took only a typed number; clicking two points
// (the distance between them) was rejected, and the second click had no distance guide.
#[test]
fn offset_distance_from_two_clicked_points() {
let mut s = one_line();
s.start("offset").unwrap();
s.input(Input::Point(Vec2::new(20.0, 20.0))).unwrap();
let p = s.current_prompt().unwrap();
assert!(p.message.contains("second point"), "{}", s.prompt_text());
assert!(p.base.is_some_and(|b| b.near(Vec2::new(20.0, 20.0), 1e-9)), "the second click is measured from the first");
// The guide from the first click to the cursor is the previewed distance.
let guide = s.preview(Vec2::new(20.0, 22.5));
assert!(matches!(guide.first().map(|e| &e.kind), Some(EntityKind::Line(g)) if g.a.xy().near(Vec2::new(20.0, 20.0), 1e-9)), "{guide:?}");
s.input(Input::Point(Vec2::new(20.0, 22.5))).unwrap();
assert!(s.current_prompt().unwrap().message.contains("Select object"), "{}", s.prompt_text());
assert_eq!(s.doc().unwrap().header.f64("OFFSETDIST", -1.0), 2.5);
s.script("5,0 5,1\n\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s), vec![l((0.0, 0.0), (10.0, 0.0), "0"), l((0.0, 2.5), (10.0, 2.5), "0")]);
}
#[test]
fn offset_json_erase_and_layer() {
let mut s = one_line();
-1
View File
@@ -104,7 +104,6 @@ fn a_dimension_drawn_from_its_block_is_picked_on_the_block_text() {
explodable: true,
units: 0,
array: None,
xref_stamp: None,
};
d.blocks.insert("*D1".into(), std::sync::Arc::new(block));
d.model.modify(dim, |e| {
+2 -3
View File
@@ -279,7 +279,7 @@ fn interactive_refedit_refset_and_refclose() {
}
#[test]
fn an_xref_that_is_not_loaded_is_refused_with_a_message() {
fn xrefs_are_refused_with_a_message() {
let mut s = Session::new();
s.doc_mut().unwrap().blocks.insert(
"X".into(),
@@ -291,6 +291,5 @@ fn an_xref_that_is_not_loaded_is_refused_with_a_message() {
);
let x = insert(&mut s, "X", (0.0, 0.0), 1.0, 0.0);
let e = s.execute("refedit", &json!({ "handle": x })).unwrap_err();
// Xrefs are edited in place and written back (refedit_xref.rs); one not loaded can't be.
assert!(e.to_string().contains("not loaded"), "{e}");
assert!(e.to_string().contains("external reference"), "{e}");
}
File diff suppressed because it is too large Load Diff
+12 -5
View File
@@ -9,8 +9,11 @@ use serde_json::json;
fn session() -> (Session, String) {
let tag = |code: i32, v: &str| RawTag { code, value: v.into() };
let mut d = Drawing::new_imperial();
let kind =
EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")] });
let kind = EntityKind::Unknown(Unknown {
dxf_type: "OLE2FRAME".into(),
tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")],
graphics: Vec::new(),
});
let h = d.add(&Space::Model, Common::default(), kind).unwrap();
let mut s = Session::empty();
s.open_drawing(d, "ole.dxf", None);
@@ -75,7 +78,8 @@ fn data_session(chunks: &[usize], hex_override: Option<&str>) -> (Session, Strin
tags.push(tag(310, &hex[at..]));
}
let mut d = Drawing::new_imperial();
let h = d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags })).unwrap();
let h =
d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() })).unwrap();
let mut s = Session::empty();
s.open_drawing(d, "ole.dxf", None);
(s, h.hex())
@@ -160,8 +164,11 @@ fn a_locked_ole_frame_does_not_block_an_in_place_rotation() {
let mut d = Drawing::new_imperial();
d.ensure_layer("L");
let common = Common { layer: "L".into(), ..Common::default() };
let kind =
EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")] });
let kind = EntityKind::Unknown(Unknown {
dxf_type: "OLE2FRAME".into(),
tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")],
graphics: Vec::new(),
});
let ole = d.add(&Space::Model, common, kind).unwrap();
if let Some(l) = d.layer_mut("L") {
l.locked = true;
@@ -22,6 +22,7 @@ fn install() {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
});
set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
}
/// A proxy entity of class 500 (WIDGETX) in `owner`, with a string stream of `strings` bytes.
@@ -87,6 +88,35 @@ fn not_saved(r: &Value) -> Value {
r.get("notSaved").cloned().unwrap_or(Value::Null)
}
#[test]
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
fn legacy_visualstyles_warn_only_for_2007_dwg() {
install();
cadcraft_io::dwg_worker::allow_in_process();
let source = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1021\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n30\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n0\n20\n0\n30\n0\n11\n10\n21\n5\n31\n0\n0\nENDSEC\n\
0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_VISUALSTYLE\n350\n20\n\
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nSynthetic\n350\n21\n\
0\nVISUALSTYLE\n5\n21\n330\n20\n100\nAcDbVisualStyle\n2\nSynthetic\n70\n0\n71\n1\n72\n1\n73\n1\n90\n0\n40\n1.0\n41\n0.5\n63\n7\n\
74\n2\n91\n0\n64\n7\n65\n7\n75\n1\n175\n1\n42\n30.0\n92\n0\n66\n7\n43\n1.0\n76\n1\n77\n0\n78\n0\n67\n7\n79\n1\n\
170\n0\n171\n0\n290\n0\n174\n0\n93\n0\n44\n0.0\n173\n0\n291\n0\n0\nENDSEC\n0\nEOF\n";
let drawing = cadcraft_io::read_dxf(source.as_bytes()).unwrap();
let mut session = Session::empty();
session.open_drawing(drawing, "styles.dxf", None);
assert_eq!(cadcraft_engine::cmd::file::loss_on_save(&session, "styles.dwg").get("VISUALSTYLE"), Some(&1));
for (format, version) in [("dwg", 2007), ("dwg", 2013), ("dxf", 2007)] {
let start = session.log.len();
let result = session.execute("document.bytes", &json!({"format": format, "version": version})).unwrap();
if format == "dwg" && version == 2007 {
assert_eq!(not_saved(&result), json!({"VISUALSTYLE": 1}));
assert!(session.log[start..].iter().any(|message| message.contains("VISUALSTYLE")));
} else {
assert_eq!(not_saved(&result), Value::Null);
assert!(!session.log[start..].iter().any(|message| message.contains("VISUALSTYLE")));
}
}
}
#[test]
fn a_proxy_no_version_writes_is_not_reported() {
install();
-33
View File
@@ -305,36 +305,3 @@ fn drawings_sharing_a_name_keep_their_own_backups() {
assert_eq!(name("x/plan.dxf"), "x/plan.dxf.bak");
assert_eq!(name("x/plan.dwt"), "x/plan.dwt.bak");
}
/// REFCLOSE Save writes an xref back the way SAVE writes a drawing: with ISAVEBAK off it keeps
/// no `.bak` (and reports none), with it on it keeps the previous file.
#[test]
fn an_xref_written_back_by_refclose_keeps_a_backup_as_save_does() {
let _g = saving();
hooks();
let dir = temp_dir("refclose");
let site = dir.join("site.dxf");
let mut x = Session::new();
add_circle(&mut x, 0.0);
x.execute("saveas", &json!({ "path": site.to_string_lossy() })).unwrap();
let host = dir.join("host.dxf");
let mut s = Session::new();
s.execute("saveas", &json!({ "path": host.to_string_lossy() })).unwrap();
let insert = s.execute("xattach", &json!({ "path": "site.dxf", "at": [100, 0] })).unwrap()["handle"].as_str().unwrap().to_string();
let bak = backup_path(&site);
cadcraft_engine::autosave::set_isavebak(false);
s.execute("refedit", &json!({ "handle": insert })).unwrap();
add_circle(&mut s, 110.0);
let out = s.execute("refclose", &json!({ "option": "save" })).unwrap();
assert_eq!(circles(&site), 2, "the edit is written");
assert!(out["backup"].is_null() && !bak.exists(), "ISAVEBAK off keeps no backup: {out}");
cadcraft_engine::autosave::set_isavebak(true);
s.execute("refedit", &json!({ "handle": insert })).unwrap();
add_circle(&mut s, 120.0);
let out = s.execute("refclose", &json!({ "option": "save" })).unwrap();
assert_eq!((circles(&site), circles(&bak)), (3, 2), "{out}");
assert_eq!(files(&dir), ["host.dxf", "site.dxf", "site.dxf.bak"], "no staging files are left");
let _ = std::fs::remove_dir_all(&dir);
}
@@ -8,7 +8,7 @@ use cadcraft_engine::doc::{Block, Common, Drawing, EntityKind, RawTag, Space, Un
use serde_json::json;
fn unknown(kind: &str) -> EntityKind {
EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }] })
EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }], graphics: Vec::new() })
}
#[test]
@@ -129,6 +129,7 @@ fn proxy_entities_are_reported_only_before_2013() {
RawTag { code: 90, value: "498".into() },
RawTag { code: 91, value: class.to_string() },
],
graphics: Vec::new(),
})
};
let mut d = Drawing::new_imperial();
@@ -190,6 +191,7 @@ fn saving_sat_text_solids_as_dxf_2013_reports_them() {
RawTag { code: 1, value: "400 1 1 0".into() },
RawTag { code: 3, value: "End-of-ACIS-data".into() },
],
graphics: Vec::new(),
});
d.add(&Space::Model, Common::default(), sat).unwrap();
let mut s = Session::empty();
@@ -219,7 +221,7 @@ fn a_dxf_2013_loss_is_known_before_saving() {
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
let sat = |d: &mut Drawing| {
let tags = vec![RawTag { code: 8, value: "0".into() }, RawTag { code: 1, value: "400 1 1 0".into() }];
d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "REGION".into(), tags })).unwrap();
d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "REGION".into(), tags, graphics: Vec::new() })).unwrap();
};
let mut modern = Drawing::new_imperial();
modern.header.set_str("ACADVER", "AC1032");
@@ -255,6 +257,7 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() {
RawTag { code: 1, value: "400 1 1 0".into() },
RawTag { code: 3, value: "End-of-ACIS-data".into() },
],
graphics: Vec::new(),
});
d.add(&Space::Model, Common::default(), sat).unwrap();
d.blocks.insert("Door".into(), std::sync::Arc::new(Block::new("Door")));
@@ -276,7 +279,7 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() {
fn a_dwg_keeps_sat_text_solids_only_before_2013() {
use cadcraft_engine::cmd::file::{Version, not_saved_as};
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let solid = |tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags });
let solid = |tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags, graphics: Vec::new() });
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "700 0 1 0")])).unwrap();
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(70, "1")])).unwrap();
@@ -352,6 +355,7 @@ fn proxy_entity(strings: &str) -> EntityKind {
EntityKind::Unknown(Unknown {
dxf_type: "ACAD_PROXY_ENTITY".into(),
tags: tags.iter().map(|(code, value)| RawTag { code: *code, value: (*value).into() }).collect(),
graphics: Vec::new(),
})
}
+60
View File
@@ -0,0 +1,60 @@
//! WBLOCKPICK: the Write Block dialog's canvas picks (objects, base point) and their cancel.
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::{Input, Session};
use serde_json::json;
fn session_with_line() -> (Session, cadcraft_engine::doc::Handle) {
let mut s = Session::new();
let r = s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap();
let h = cadcraft_engine::doc::Handle::parse_hex(r["handles"][0].as_str().unwrap()).unwrap();
s.set_selection(Vec::new());
(s, h)
}
#[test]
fn objects_keeps_the_selection() {
let (mut s, h) = session_with_line();
s.start("wblockpick").unwrap();
s.input(Input::Keyword("Objects".into())).unwrap();
s.input(Input::Pick(vec![h])).unwrap();
s.input(Input::Enter).unwrap();
assert!(s.running.is_none());
let p = s.wblock_picks.take().unwrap();
assert_eq!((p.handles, p.base), (vec![h], None));
}
#[test]
fn base_keeps_the_point() {
let (mut s, _) = session_with_line();
s.start("wblockpick").unwrap();
s.input(Input::Keyword("Base".into())).unwrap();
s.input(Input::Point(Vec2::new(3.0, 4.0))).unwrap();
assert!(s.running.is_none());
let p = s.wblock_picks.take().unwrap();
assert_eq!((p.handles.len(), p.base), (0, Some(Vec2::new(3.0, 4.0))));
}
#[test]
fn escape_keeps_nothing() {
let (mut s, h) = session_with_line();
s.start("wblockpick").unwrap();
s.input(Input::Keyword("Objects".into())).unwrap();
s.input(Input::Pick(vec![h])).unwrap();
s.input(Input::Cancel).unwrap();
assert!(s.running.is_none());
assert!(s.wblock_picks.is_none());
}
#[test]
fn preexisting_selection_still_prompts() {
// Even if there is a pickfirst selection, WBLOCKPICK Objects must keep prompting
// so the dialog drives picking explicitly — it never bypasses the "Select objects" step.
let (mut s, h) = session_with_line();
s.set_selection(vec![h]);
s.start("wblockpick").unwrap();
s.input(Input::Keyword("Objects".into())).unwrap();
// Must still be running — "Select objects" prompt expected.
assert!(s.running.is_some());
assert!(s.wblock_picks.is_none());
}
+40 -21
View File
@@ -649,31 +649,41 @@ fn frame(font: &TextFont, s: &str, p: &TextParams) -> (Vec2, Vec2, f64, Vec2) {
(origin, justify_offset(font, &sh, height, p.h, p.v), rot, mirror)
}
/// Resolve Aligned/Fit dimensions with the same shaping direction as [`place`].
/// Missing, coincident or nonfinite points leave the parameters unchanged.
pub fn fit_params(font: &TextFont, s: &str, p: &TextParams) -> TextParams {
let mut fitted = *p;
if !matches!(p.h, Align::Aligned | Align::Fit) {
return fitted;
}
let Some(second) = p.align_pt else { return fitted };
let distance = p.insert.dist(second);
if !distance.is_finite() || distance <= 1e-12 {
return fitted;
}
fitted.rotation = p.insert.angle_to(second);
let height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 };
let width = shape_line_dir(font, s, height, p.width_factor, p.oblique, TEXT_BASE_RTL).width;
if width.is_finite() && width > 1e-12 {
let scale = distance / width;
if p.h == Align::Aligned {
fitted.height = height * scale;
} else {
fitted.width_factor *= scale;
}
}
fitted
}
/// Place a single-line TEXT in world coordinates with any font. Returns the shaped text and its
/// bounding box.
pub fn place(font: &TextFont, s: &str, p: &TextParams) -> (Shaped, Bounds2) {
let mut height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 };
let mut wf = p.width_factor;
let mut rot = if p.rotation.is_finite() { p.rotation } else { 0.0 };
let fitted = fit_params(font, s, p);
let p = &fitted;
let height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 };
let rot = if p.rotation.is_finite() { p.rotation } else { 0.0 };
let insert = p.insert;
if matches!(p.h, Align::Aligned | Align::Fit)
&& let Some(p2) = p.align_pt
{
let len = insert.dist(p2);
rot = insert.angle_to(p2);
// Measured as it is placed, left to right: the stroke font's trailing gap follows the
// glyph that ends the line.
let w = shape_line_dir(font, s, height, wf, p.oblique, TEXT_BASE_RTL).width;
if w > 1e-12 && len > 1e-12 {
let k = len / w;
if p.h == Align::Aligned {
height *= k;
} else {
wf *= k;
}
}
}
let mut sh = shape_line_dir(font, s, height, wf, p.oblique, TEXT_BASE_RTL);
let mut sh = shape_line_dir(font, s, height, p.width_factor, p.oblique, TEXT_BASE_RTL);
let width = sh.width;
// Every justification but baseline-left (and aligned/fit, which span both points) is placed by
// its alignment point (DXF group 11); the insertion point (group 10) is then a computed point.
@@ -740,6 +750,15 @@ mod tests {
assert!((text.width - 10.0).abs() < 1e-9, "{}", text.width);
}
#[test]
fn two_point_middle_vertical_spans_points() {
for h in [Align::Aligned, Align::Fit] {
let p = TextParams { h, v: VAlign::Middle, align_pt: Some(Vec2::new(12.0, 5.0)), ..TextParams::new(Vec2::ZERO, 2.0) };
let (shaped, _) = place(&TextFont::Stroke, "SYNTHETIC", &p);
assert!((shaped.width - p.insert.dist(p.align_pt.unwrap())).abs() < 1e-9);
}
}
#[test]
fn every_ascii_printable_has_a_glyph() {
for c in ' '..='~' {
+4
View File
@@ -102,6 +102,9 @@ pub struct MTextLayout {
/// Geometry by colour run (strokes plus fillable glyph outlines).
pub pieces: Vec<MTextPiece>,
pub bounds: Bounds2,
/// The box of each column, in the order the text flows through them, measured like `bounds`
/// but without the gutters and to each column's own height. One column: `bounds`.
pub column_bounds: Vec<Bounds2>,
/// Plain text of each laid-out line.
pub lines: Vec<String>,
/// Whether the geometry stops short: the layout reached its allowance of retained points
@@ -731,6 +734,7 @@ pub fn layout_mtext_with(contents: &str, p: &MTextParams) -> MTextLayout {
out.bounds = Bounds2::from_points(
[Vec2::new(x0, top), Vec2::new(x0 + block_w, top), Vec2::new(x0 + block_w, top - block_h), Vec2::new(x0, top - block_h)].map(xf),
);
out.column_bounds = vec![out.bounds];
out
}
+8
View File
@@ -700,6 +700,14 @@ pub(super) fn layout(contents: &str, params: &MTextParams, base: &Fmt) -> MTextL
[Vec2::new(box_x0, top), Vec2::new(box_x0 + total_w, top), Vec2::new(box_x0 + total_w, top - block_h), Vec2::new(box_x0, top - block_h)]
.map(xf),
);
out.column_bounds = (0..n_cols)
.map(|column| {
let h = col_bottom.get(column).copied().unwrap_or(0.0).max(col_height(column));
let slot = if reversed { n_cols.saturating_sub(1).saturating_sub(column) } else { column };
let x0 = box_x0 + slot as f64 * (col_w + gutter);
Bounds2::from_points([Vec2::new(x0, top), Vec2::new(x0 + col_w, top), Vec2::new(x0 + col_w, top - h), Vec2::new(x0, top - h)].map(xf))
})
.collect();
out
}
+60
View File
@@ -109,6 +109,66 @@ fn reversed_columns_run_right_to_left() {
assert!(first > 0 && second > 0 && min_x(&l) >= 0.0);
}
/// The geometry points inside `b`.
fn points_in(l: &MTextLayout, b: &cadcraft_geom::Bounds2) -> usize {
l.strokes.iter().flatten().filter(|p| b.contains(**p)).count()
}
#[test]
fn each_column_has_its_own_box_without_the_gutter() {
let two = lay(&"word ".repeat(12), 10.0, Some(MTextColumnSpec { count: 2, gutter: 2.0, height: 6.0, ..Default::default() }));
let [a, b] = two.column_bounds.as_slice() else { panic!("{:?}", two.column_bounds) };
assert!(two.bounds.contains_box(a) && two.bounds.contains_box(b));
assert!(a.max.x < b.min.x, "the gutter lies between the columns: {a:?} {b:?}");
assert!(a.width() + b.width() < two.bounds.width());
let total = two.strokes.iter().map(Vec::len).sum::<usize>();
assert!(points_in(&two, a) > 0 && points_in(&two, b) > 0);
assert_eq!(points_in(&two, a) + points_in(&two, b), total, "every point is in its column's box");
// Three static columns, the text filling two and a half: the half-full column keeps the
// column height; text past the last column lengthens only that one.
let spec = MTextColumnSpec { count: 3, gutter: 2.0, height: 6.0, ..Default::default() };
let three = lay(&"word ".repeat(20), 10.0, Some(spec.clone()));
assert_eq!(three.column_bounds.len(), 3);
assert!(three.column_bounds.windows(2).all(|w| w[0].max.x < w[1].min.x && (w[0].height() - w[1].height()).abs() < 1e-9));
let over = lay(&"word ".repeat(40), 10.0, Some(spec));
let [first, .., last] = over.column_bounds.as_slice() else { panic!("{:?}", over.column_bounds) };
assert!(last.height() > first.height() && (last.height() - over.bounds.height()).abs() < 1e-9);
// Manual heights: each column as tall as its own height.
let manual = lay("one\\Ntwo", 5.0, Some(MTextColumnSpec { dynamic: true, heights: vec![3.0, 5.0], ..Default::default() }));
let [a, b] = manual.column_bounds.as_slice() else { panic!("{:?}", manual.column_bounds) };
assert!(a.height() < b.height());
}
#[test]
fn an_empty_column_keeps_its_place() {
let l = lay("first\\Nsecond", 10.0, Some(MTextColumnSpec { count: 3, gutter: 1.0, height: 4.0, ..Default::default() }));
let [a, b, c] = l.column_bounds.as_slice() else { panic!("{:?}", l.column_bounds) };
assert!(a.max.x < b.min.x && b.max.x < c.min.x);
assert!(points_in(&l, a) > 0 && points_in(&l, b) > 0 && points_in(&l, c) == 0);
assert!((c.max.x - l.bounds.max.x).abs() < 1e-9 && (c.height() - a.height()).abs() < 1e-9);
// Reversed: the column the text starts in is the rightmost.
let r = lay("first\\Nsecond", 10.0, Some(MTextColumnSpec { count: 2, height: 1.0, reversed: true, ..Default::default() }));
let [a, b] = r.column_bounds.as_slice() else { panic!("{:?}", r.column_bounds) };
assert!(a.min.x > b.max.x - 1e-9);
}
#[test]
fn one_column_is_the_whole_box() {
let rotated = |p: MTextParams| MTextParams { rotation: 0.4, attach: 5, insert: Vec2::new(3.0, -2.0), ..p };
for (s, width, columns) in [
("plain text that wraps a few times", 6.0, None),
("\\pxl1;paragraph text that wraps\\Pagain", 6.0, None),
("no width\\Pat all", 0.0, None),
(&*"word ".repeat(30), 10.0, Some(MTextColumnSpec { count: 1, gutter: 5.0, height: 3.0, ..Default::default() })),
("one\\Ptwo", 10.0, Some(MTextColumnSpec { dynamic: true, gutter: 5.0, height: 30.0, ..Default::default() })),
] {
let l = layout_mtext_with(s, &rotated(MTextParams { width, columns, ..MTextParams::new(Vec2::ZERO, 1.0) }));
assert_eq!(l.column_bounds, vec![l.bounds], "{s}");
}
}
#[test]
fn hostile_paragraph_codes_do_not_panic() {
let huge_tabs = format!("\\pt{};a\tb", (0..100_000).map(|i| i.to_string()).collect::<Vec<_>>().join(","));
+196
View File
@@ -0,0 +1,196 @@
//! A synthetic TrueType (sfnt) font file, built in code for tests that need a real font without a
//! font file in the repository or one installed on the machine: `head`, `hhea`, `maxp`, `hmtx`,
//! `glyf`, `loca`, a format-4 `cmap` and `OS/2`, laid out in a sorted table directory.
//!
//! Test-only, and shared: `crates/render/src/tests.rs` (the level-of-detail fixture) and
//! `crates/io/tests/pdf_text.rs` (the PDF writer's embedding fixtures) build their fonts with it,
//! each including this file with `#[path]`, so neither needs a published API, a dependency or a
//! copy of the other's tables. `crates/fonts` is the layer that reads those tables
//! (`crates/fonts/src/ttf.rs`), which is why the skeleton lives beside its tests; the glyph shapes,
//! the character map ranges and the metrics a font records stay at the caller that needs them.
fn be16(v: &mut Vec<u8>, x: u16) {
v.extend_from_slice(&x.to_be_bytes());
}
fn be32(v: &mut Vec<u8>, x: u32) {
v.extend_from_slice(&x.to_be_bytes());
}
/// A simple glyph, with the point and contour counts `maxp` records for the font.
pub struct Glyph {
bytes: Vec<u8>,
points: usize,
contours: usize,
}
/// `.notdef`: no contours, no bytes.
pub fn notdef() -> Glyph {
Glyph { bytes: Vec::new(), points: 0, contours: 0 }
}
/// One simple glyph: closed contours of on-curve points, with the box the file records for it.
pub fn glyph(contours: &[Vec<(i16, i16)>]) -> Glyph {
let points: Vec<(i16, i16)> = contours.iter().flatten().copied().collect();
let mut g = Vec::new();
be16(&mut g, contours.len() as u16);
let box_ = points.iter().fold((i16::MAX, i16::MAX, i16::MIN, i16::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)));
for v in [box_.0, box_.1, box_.2, box_.3] {
be16(&mut g, v as u16);
}
let mut end = 0u16;
for c in contours {
end = end.saturating_add(c.len() as u16);
be16(&mut g, end.saturating_sub(1));
}
be16(&mut g, 0);
g.extend(std::iter::repeat_n(1u8, points.len()));
let (mut px, mut py) = (0i16, 0i16);
for (x, _) in &points {
be16(&mut g, x.wrapping_sub(px) as u16);
px = *x;
}
for (_, y) in &points {
be16(&mut g, y.wrapping_sub(py) as u16);
py = *y;
}
while g.len() % 4 != 0 {
g.push(0);
}
Glyph { bytes: g, points: points.len(), contours: contours.len() }
}
/// What the callers differ in; every other table field is the same in each font this builds.
pub struct Sfnt<'a> {
/// `glyf` entries, `.notdef` first.
pub glyphs: &'a [Glyph],
/// `cmap` format-4 segments: first character code, last character code, and glyph id minus
/// code. The `0xFFFF` segment that ends the map is added here.
pub cmap: &'a [(u16, u16, i16)],
/// The advance width every glyph shares, in em units.
pub advance: u16,
/// The left side bearing every glyph shares.
pub lsb: i16,
/// `hmtx` entries written. Fewer than the glyphs `hhea` declares is a deliberately short
/// table: that font is malformed on purpose, and a reader must cope with it, not repair it.
pub metrics: usize,
/// `OS/2` `fsType`: the embedding permissions, `0` for any use.
pub fs_type: u16,
/// `head`'s ink box: xMin, yMin, xMax, yMax.
pub ink_box: [i16; 4],
}
/// Em units per em: with a 700-unit cap height, one em is 1000 units, so a text height of one unit
/// is a cap height of one unit.
const UNITS_PER_EM: u16 = 1000;
/// The font file `f` describes, as a TrueType file.
pub fn bytes(f: &Sfnt<'_>) -> Vec<u8> {
let mut glyf = Vec::new();
let mut loca = Vec::new();
for g in f.glyphs {
be32(&mut loca, glyf.len() as u32);
glyf.extend_from_slice(&g.bytes);
}
be32(&mut loca, glyf.len() as u32);
let mut head = Vec::new();
be32(&mut head, 0x0001_0000); // version
be32(&mut head, 0x0001_0000); // fontRevision
be32(&mut head, 0); // checkSumAdjustment
be32(&mut head, 0x5F0F_3CF5); // magic
be16(&mut head, 0); // flags
be16(&mut head, UNITS_PER_EM);
head.extend_from_slice(&[0; 16]); // created, modified
for v in f.ink_box {
be16(&mut head, v as u16);
}
// macStyle, lowestRecPPEM, fontDirectionHint, indexToLocFormat 1 = long offsets (`loca` holds
// `u32`), glyphDataFormat.
for v in [0u16, 8, 2, 1, 0] {
be16(&mut head, v);
}
let mut hhea = Vec::new();
be32(&mut hhea, 0x0001_0000);
// ascender, descender, lineGap, advanceWidthMax, minLeftSideBearing, minRightSideBearing,
// xMaxExtent, caretSlopeRise, caretSlopeRun, caretOffset, four reserved, metricDataFormat.
for v in [800i16, -200, 0, f.advance as i16, 0, 0, f.advance as i16, 1, 0, 0, 0, 0, 0, 0, 0] {
be16(&mut hhea, v as u16);
}
be16(&mut hhea, f.glyphs.len() as u16); // numberOfHMetrics
let max_points = f.glyphs.iter().map(|g| g.points).max().unwrap_or(0);
let max_contours = f.glyphs.iter().map(|g| g.contours).max().unwrap_or(0);
let mut maxp = Vec::new();
be32(&mut maxp, 0x0001_0000);
// numGlyphs, maxPoints, maxContours, maxCompositePoints, maxCompositeContours, maxZones, and
// the composite and instruction maxima after them.
for v in [f.glyphs.len() as u16, max_points as u16, max_contours as u16, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] {
be16(&mut maxp, v);
}
let mut hmtx = Vec::new();
for _ in 0..f.metrics {
be16(&mut hmtx, f.advance);
be16(&mut hmtx, f.lsb as u16);
}
// cmap: version 0 with one encoding record (Windows, Unicode BMP), a format-4 subtable over
// the caller's segments and the `0xFFFF` one that ends it.
let segs: Vec<(u16, u16, i16)> = f.cmap.iter().copied().chain([(0xFFFF, 0xFFFF, 1)]).collect();
let seg_count = segs.len() as u32;
let seg_selector = seg_count.ilog2();
let seg_search_range = 2 * (1 << seg_selector);
let mut sub = Vec::new();
be16(&mut sub, 4); // format
be16(&mut sub, (16 + segs.len() * 8) as u16); // length
be16(&mut sub, 0); // language
be16(&mut sub, (segs.len() * 2) as u16); // segCountX2
for v in [seg_search_range as u16, seg_selector as u16, (2 * seg_count - seg_search_range) as u16] {
be16(&mut sub, v);
}
for s in &segs {
be16(&mut sub, s.1);
}
be16(&mut sub, 0); // reservedPad
for s in &segs {
be16(&mut sub, s.0);
}
for s in &segs {
be16(&mut sub, s.2 as u16);
}
for _ in &segs {
be16(&mut sub, 0); // idRangeOffset
}
let mut cmap = Vec::new();
for v in [0u16, 1, 3, 1] {
be16(&mut cmap, v);
}
be32(&mut cmap, 12); // the subtable, straight after the records
cmap.extend_from_slice(&sub);
let mut os2 = vec![0u8; 78];
os2[8..10].copy_from_slice(&f.fs_type.to_be_bytes());
let mut tables: Vec<(&[u8; 4], Vec<u8>)> =
vec![(b"OS/2", os2), (b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)];
tables.sort_by_key(|t| *t.0);
let mut out = Vec::new();
be32(&mut out, 0x0001_0000); // sfnt version 1.0
let num_tables = tables.len() as u32;
let table_selector = num_tables.ilog2();
let dir_search_range = 16 * (1 << table_selector);
// numTables, searchRange, entrySelector, rangeShift: 16-byte records, largest power of two first.
for v in [num_tables as u16, dir_search_range as u16, table_selector as u16, (16 * num_tables - dir_search_range) as u16] {
be16(&mut out, v);
}
let mut off = 12 + 16 * tables.len();
for (t, d) in &tables {
out.extend_from_slice(*t);
be32(&mut out, 0); // checkSum: the readers here do not verify it
be32(&mut out, off as u32);
be32(&mut out, d.len() as u32);
off += d.len().div_ceil(4) * 4;
}
for (_, d) in &tables {
out.extend_from_slice(d);
while out.len() % 4 != 0 {
out.push(0);
}
}
out
}
+48
View File
@@ -62,6 +62,9 @@ struct Rx {
block_arrays: HashMap<String, cadcraft_doc::ArrayParams>,
/// LAYER record handle (upper case) → layer name (VIEWPORT group 331/341 frozen layers).
layers: HashMap<String, String>,
/// Layer, linetype and text style names in the order of the file's tables, which proxy
/// graphics refer to by index (the drawing's own tables are ordered differently).
proxy_tables: cadcraft_doc::ProxyTables,
/// UCS record handle (upper case) → UCS name (a layout's named UCS, group 345).
ucss: HashMap<String, String>,
/// Owner handle, paper flag and enclosing block (upper case) of each generated sheet viewport
@@ -75,6 +78,26 @@ struct Rx {
image_defs: HashMap<Handle, String>,
}
/// Order `items` as the file's table lists them (`order`, names in any case), after the `pinned`
/// names: records the file doesn't have keep their order after the file's own. A file without
/// that table changes nothing.
fn keep_file_order<T>(items: &mut [T], name: impl Fn(&T) -> &str, order: &[String], pinned: &[&str]) {
if order.is_empty() {
return;
}
let mut place: HashMap<String, usize> = HashMap::new();
for (i, n) in order.iter().enumerate() {
place.entry(n.to_ascii_lowercase()).or_insert(i);
}
items.sort_by_key(|it| {
let n = name(it);
match pinned.iter().position(|p| p.eq_ignore_ascii_case(n)) {
Some(i) => (0, i),
None => place.get(&n.to_ascii_lowercase()).map_or((2, 0), |&i| (1, i)),
}
});
}
/// 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)
@@ -179,6 +202,13 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
_ => {}
}
}
// Proxy graphics name layers and linetypes by their place in the file's tables, and saving
// writes them unchanged: the tables keep the file's order, with what CADCraft adds after it.
keep_file_order(&mut d.layers, |l| &l.name, &rx.proxy_tables.layers, &[]);
keep_file_order(&mut d.linetypes, |l| &l.name, &rx.proxy_tables.linetypes, &["ByBlock", "ByLayer"]);
// A proxy text takes the first style on its font, so the styles keep the file's order too.
let styles: Vec<String> = rx.proxy_tables.styles.iter().map(|(n, _)| n.clone()).collect();
keep_file_order(&mut d.text_styles, |s| &s.name, &styles, &[]);
// A file CADCraft wrote names its own next handle (#495): its table records and objects
// are numbered above it and rebuilt on save, so following $HANDSEED would drift every save.
let own_seed = objs.xrecord_text(crate::dxf_ext::HANDSEED_KEY).and_then(|t| Handle::parse_hex(t.trim()));
@@ -212,6 +242,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
// Every record is placed now, and an object holding a reserved handle keeps it from new
// objects by itself. Kept, the set would be copied with every undo step of the drawing.
d.reserved_handles.clear();
remember_text_fits(&mut d);
Ok(d)
}
@@ -244,6 +275,23 @@ fn number_unknown_viewport_ids(d: &mut Drawing, sheet_dropped: &std::collections
}
}
/// Capture after all tables and entity fixups, including files whose tables follow entities.
fn remember_text_fits(d: &mut Drawing) {
let mut fits = std::collections::BTreeMap::new();
for e in d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter())) {
let texts: Vec<&Text> = match &e.kind {
EntityKind::Text(t) => vec![t],
EntityKind::AttDef(a) => vec![&a.text],
EntityKind::Insert(i) => i.attribs.iter().map(|a| &a.text).collect(),
_ => continue,
};
if texts.iter().any(|t| matches!(t.halign, HAlign::Aligned | HAlign::Fit)) {
fits.insert(e.handle, texts.into_iter().map(|t| (t.clone(), d.text_style(&t.style).cloned().unwrap_or_default())).collect());
}
}
std::sync::Arc::make_mut(&mut d.foreign).text_fits = fits;
}
/// An entity from the groups of a DXF record of type `kind` (without its `0` group), as the
/// reader makes it, with plain strings as [`crate::entity_groups`] gives them (not the file's
/// `^ ` escapes). AutoLISP's `entmake` and `entmod` are built on it.
+5
View File
@@ -329,6 +329,7 @@ pub(super) fn entity_with_table_budget(
other => EntityKind::Unknown(Unknown {
dxf_type: other.to_string(),
tags: tags.iter().map(|tg| RawTag { code: tg.code, value: tg.str() }).collect(),
graphics: Vec::new(),
}),
};
Some((c, k))
@@ -488,6 +489,10 @@ pub(super) fn entity_plot_style(tags: &[Tag], rx: &Rx) -> Option<String> {
/// needs the file's handle maps.
pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityKind, rx: &mut Rx) {
match (kind, k) {
// Its proxy graphics, with the table indices resolved while the file's order is known.
("ACAD_PROXY_ENTITY", EntityKind::Unknown(u)) => {
u.graphics = cadcraft_doc::proxy_entities(&u.proxy_graphics_bytes(), &rx.proxy_tables, h);
}
("DIMENSION", EntityKind::Dimension(dm)) => {
dm.overrides = crate::dxf_ext::read_dstyle(tags, &rx.styles, &rx.brs, &rx.ltypes);
dm.assoc = crate::dxf_ext::read_assoc(tags);
+1 -1
View File
@@ -73,7 +73,7 @@ pub(super) fn hatch(tags: &[Tag], t: &T, curves: &mut CurvePoints) -> Option<Ent
verts.pop();
}
let sources = boundary_sources(tags, &mut i);
loops.push(HatchLoop { vertices: verts, outer, sources });
loops.push(HatchLoop { vertices: verts, outer, boundary_flags: Some(flags), sources });
}
curves.left = curves.left.saturating_sub(start_left.saturating_sub(budget.left));
if budget.cut {
+5
View File
@@ -299,6 +299,7 @@ fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) {
let (Some(handle), Some(name)) = (table.s(5), table.s(2)) else { continue };
match kind.as_str() {
"STYLE" => {
rx.proxy_tables.styles.push((name.clone(), table.s(3).unwrap_or_default()));
rx.styles.insert(handle.trim().to_ascii_uppercase(), name);
}
"BLOCK_RECORD" => {
@@ -310,9 +311,13 @@ fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) {
rx.brs.insert(handle.trim().to_ascii_uppercase(), name);
}
"LTYPE" => {
if !name.eq_ignore_ascii_case("ByBlock") && !name.eq_ignore_ascii_case("ByLayer") {
rx.proxy_tables.linetypes.push(name.clone());
}
rx.ltypes.insert(handle.trim().to_ascii_uppercase(), name);
}
"LAYER" => {
rx.proxy_tables.layers.push(name.clone());
rx.layers.insert(handle.trim().to_ascii_uppercase(), name);
}
"UCS" => {
+3 -2
View File
@@ -70,7 +70,8 @@ pub(crate) fn from_polyline(tags: &[Tag], pl: LwPolyline) -> Option<EntityKind>
let list = xdata_list(x, "REGION");
let fin = |v: &PolyVertex| v.p.is_finite() && v.bulge.is_finite();
let first_outer = list.iter().find(|t| t.code == 1070).is_none_or(|t| t.i64() != 0);
let mut loops = vec![HatchLoop { vertices: pl.vertices.into_iter().filter(fin).collect(), outer: first_outer, sources: Vec::new() }];
let mut loops =
vec![HatchLoop { vertices: pl.vertices.into_iter().filter(fin).collect(), outer: first_outer, boundary_flags: None, sources: Vec::new() }];
let mut total = 0usize;
let mut cur: Option<HatchLoop> = None;
let mut expect_flag = false;
@@ -81,7 +82,7 @@ pub(crate) fn from_polyline(tags: &[Tag], pl: LwPolyline) -> Option<EntityKind>
if loops.len() >= MAX_REGION_LOOPS {
break;
}
cur = Some(HatchLoop { vertices: Vec::new(), outer: false, sources: Vec::new() });
cur = Some(HatchLoop { vertices: Vec::new(), outer: false, boundary_flags: None, sources: Vec::new() });
expect_flag = true;
}
1070 if expect_flag => {
+49 -3
View File
@@ -165,10 +165,56 @@ fn tags_kept(d: &Drawing, version: Version) -> (Vec<Tag>, std::collections::Hash
/// The R2000 DXF the DWG bridge converts to a `dwg` version DWG: its entity types are the DWG
/// version's (MULTILEADER from 2007).
pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> String {
let mut tags = tags_for(d, Version::R2000, dwg, false);
pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> (String, craft_dwg::Unwritten) {
let (mut tags, kept) = sections::tags_kept_for(d, Version::R2000, dwg, false, true);
let mut unwritten = craft_dwg::Unwritten::new();
if dwg == Version::R2007 {
let omitted = legacy_visualstyles_kept(d, &kept);
if omitted != 0 {
let mut source = d.clone();
std::sync::Arc::make_mut(&mut source.foreign).objects.retain(|object| !legacy_visual_style(object));
tags = tags_for(&source, Version::R2000, dwg, false);
unwritten.insert("VISUALSTYLE".into(), omitted);
}
}
bridge_markers(&mut tags);
craft_dxf::write_ascii(&tags)
(craft_dxf::write_ascii(&tags), unwritten)
}
/// Version-specific DWG compatibility omissions, counted from the actual saved view.
/// Hosts use this before saving and when reporting saves through their byte-only I/O hooks.
pub fn dwg_compat_lost(d: &Drawing, version: Version) -> craft_dwg::Unwritten {
let mut lost = craft_dwg::Unwritten::new();
if version == Version::R2007 && d.foreign.objects.iter().any(legacy_visual_style) {
let (_, kept) = sections::tags_kept_for(d, Version::R2000, version, false, true);
let omitted = legacy_visualstyles_kept(d, &kept);
if omitted != 0 {
lost.insert("VISUALSTYLE".into(), omitted);
}
}
lost
}
fn legacy_visualstyles_kept(d: &Drawing, kept: &HashSet<cadcraft_doc::Handle>) -> usize {
d.foreign.objects.iter().filter(|object| kept.contains(&object.handle) && legacy_visual_style(object)).count()
}
/// The fixed-property VISUALSTYLE layout in the 2007/2010 DXF Reference has no 176/177
/// property pairs. The bridge cannot faithfully save this layout as a 2007 DWG.
fn legacy_visual_style(object: &cadcraft_doc::foreign::ForeignObject) -> bool {
if !object.kind.trim().eq_ignore_ascii_case("VISUALSTYLE") {
return false;
}
let mut properties = object.tags.iter().skip_while(|tag| tag.code != 100 || tag.value.trim() != "AcDbVisualStyle");
properties.next();
let mut fixed = false;
for tag in properties.take_while(|tag| tag.code != 100 && tag.code < 1000) {
if matches!(tag.code, 176 | 177) {
return false;
}
fixed |= matches!(tag.code, 40 | 71);
}
fixed
}
/// Proxy type names and lookup-parameter subclass names must match the bridge reader's spelling.
+62 -1
View File
@@ -254,8 +254,69 @@ fn computed_text_insert(d: &Drawing, t: &Text) -> Vec3 {
if q.is_finite() { Vec3::new(q.x, q.y, t.insert.z) } else { t.insert }
}
fn relative_match(a: f64, b: f64) -> bool {
a.is_finite() && b.is_finite() && (a - b).abs() <= 1e-9 * a.abs().max(b.abs())
}
// A fitted dimension depends on the point distance, independently of position and direction.
fn imported_fit_scale(original: &Text, current: &Text) -> Option<f64> {
let (Some(first), Some(second)) = (original.align_pt, current.align_pt) else {
return None;
};
let before = original.insert.xy().dist(first.xy());
let after = current.insert.xy().dist(second.xy());
if !before.is_finite() || !after.is_finite() || before <= 0.0 || after <= 0.0 {
return None;
}
if relative_match(before, after) {
return Some(1.0);
}
let scale = after / before;
(scale.is_finite() && scale > 0.0).then_some(scale)
}
/// `attdef_prompt` is `Some` for an ATTDEF (its prompt, which may be empty) and `None` for an ATTRIB.
pub(super) fn text_tags(w: &mut W, d: &Drawing, t: &Text, attrib: Option<(&Attrib, Version)>, attdef_prompt: Option<&str>) {
pub(super) fn text_tags(
w: &mut W,
d: &Drawing,
t: &Text,
attrib: Option<(&Attrib, Version)>,
attdef_prompt: Option<&str>,
source: (cadcraft_doc::Handle, usize),
) {
let fitted;
let t = if matches!(t.halign, HAlign::Aligned | HAlign::Fit) {
let mut resolved = t.clone();
// Imported dimensions use the originating font's measurements. A substituted font
// must not replace them while the fitting inputs still match the read-time snapshot.
if let Some((original, style)) = d.foreign.text_fits.get(&source.0).and_then(|texts| texts.get(source.1))
&& original.value == t.value
&& let Some(scale) = imported_fit_scale(original, t)
&& original.style == t.style
&& *style == d.text_style(&t.style).cloned().unwrap_or_default()
&& original.halign == t.halign
&& original.valign == t.valign
&& original.oblique == t.oblique
&& original.width_factor == t.width_factor
&& (t.halign != HAlign::Fit || relative_match(t.height, original.height * scale))
{
if t.halign == HAlign::Aligned && !t.value.is_empty() {
resolved.height = original.height * scale;
}
if let Some(second) = t.align_pt {
let distance = t.insert.xy().dist(second.xy());
if distance.is_finite() && distance > 1e-12 {
resolved.rotation = t.insert.xy().angle_to(second.xy());
}
}
} else {
resolved = cadcraft_render::fitted_text_entity(d, t, &t.value);
}
fitted = resolved;
&fitted
} else {
t
};
let attdef = attdef_prompt.is_some();
// An attribute definition with no default value is drawn as its tag, whatever its prompt: the
// baseline start AutoCAD stored is judged against the tag's width too. A stored point that is
+5 -5
View File
@@ -292,7 +292,7 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo
w.s(0, "TEXT");
common(w, e, owner, paper, "AcDbText");
thickness(w, e);
text_tags(w, d, t, None, None);
text_tags(w, d, t, None, None, (e.handle, 0));
}
// Closed polylines, one per loop (`dxf_region`): REGION's own data is ACIS.
EntityKind::Region(r) => {
@@ -312,7 +312,7 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo
EntityKind::AttDef(a) => {
w.s(0, "ATTDEF");
common(w, e, owner, paper, "AcDbText");
text_tags(w, d, &a.text, Some((a, cx.target)), Some(&a.prompt));
text_tags(w, d, &a.text, Some((a, cx.target)), Some(&a.prompt), (e.handle, 0));
if cx.target >= Version::R2007 {
multiline_tags(w, a, true);
}
@@ -372,7 +372,7 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b
w.f(45, i.row_spacing);
}
if !i.attribs.is_empty() {
for a in &i.attribs {
for (index, a) in i.attribs.iter().enumerate() {
let ah = w.h();
w.s(0, "ATTRIB");
w.s(5, ah);
@@ -385,7 +385,7 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b
w.i(60, 1);
}
w.s(100, "AcDbText");
text_tags(w, d, &a.text, Some((a, cx.target)), None);
text_tags(w, d, &a.text, Some((a, cx.target)), None, (e.handle, index));
if cx.target >= Version::R2007 {
multiline_tags(w, a, false);
}
@@ -627,7 +627,7 @@ fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
w.i(71, i64::from(h.associative));
w.i(91, h.loops.len() as i64);
for l in &h.loops {
w.i(92, 2 | if l.outer { 1 } else { 0 });
w.i(92, 2 | i64::from(l.outer) | (l.boundary_flags.unwrap_or(0) & (4 | 8 | 16)));
let has_bulge = l.vertices.iter().any(|v| v.bulge != 0.0);
w.i(72, i64::from(has_bulge));
w.i(73, 1);
+3 -1
View File
@@ -26,6 +26,7 @@ const HEADER_VARS: &[(&str, i32)] = &[
("CELTSCALE", 40),
("DIMSCALE", 40),
("DIMSTYLE", 2),
("DIMASSOC", 280),
("LUNITS", 70),
("LUPREC", 70),
("AUNITS", 70),
@@ -124,6 +125,7 @@ fn dim_header_vars(w: &mut W, d: &Drawing) {
}
}
/// Write modelled HEADER variables with their declared DXF group types, then dimension style variables.
pub(super) fn header_vars(w: &mut W, d: &Drawing) {
for (name, code) in HEADER_VARS {
let Some(v) = d.header.get(name) else { continue };
@@ -153,7 +155,7 @@ pub(super) fn header_vars(w: &mut W, d: &Drawing) {
w.f(c, f);
}
}
(c @ (62 | 70 | 290 | 370), v) => {
(c @ (62 | 70 | 280 | 290 | 370), v) => {
if let Some(i) = v.as_i64() {
w.s(9, format!("${name}"));
w.i(c, i);
+11 -3
View File
@@ -411,22 +411,28 @@ struct LayoutWriteData<'a> {
ucs: Option<&'a Ucs>,
/// The layout's limits as read (`None`: the default 0,0 to 12,9).
limits: Option<(Vec2, Vec2)>,
/// Whether this is the Model layout (block record *Model_Space).
model: bool,
}
/// The plot layout flags (AcDbPlotSettings group 70) for `page`. The bits CADCraft models come
/// from the page: 2 display plot styles, 4 centred, 128 lineweights, and 16 standard scale where
/// the scale decides it (scaled to fit: set; a custom scale: clear). The rest are kept as the file
/// had them (#3227); a page CADCraft made gets 512 (plot paper space last) and 32 (plot with plot
/// styles), and 16 when its scale is standard.
fn plot_layout_flags(page: &PageSetup, standard: bool) -> i64 {
/// styles), and 16 when its scale is standard. 1024 ("ModelType", DXF Reference, PLOTSETTINGS
/// group 70) follows the layout: set for the Model layout, cleared for a paper-space layout even
/// when the file had it, since it would mark that layout as model space.
fn plot_layout_flags(page: &PageSetup, standard: bool, model: bool) -> i64 {
const MODELED: i64 = 2 | 4 | 128;
const STANDARD_SCALE: i64 = 16;
const MODEL_TYPE: i64 = 1024;
let kept = match page.file_plot_flags {
Some(f) if page.scale_to_fit => (f & !MODELED) | STANDARD_SCALE,
Some(f) if !standard => f & !MODELED & !STANDARD_SCALE,
Some(f) => f & !MODELED,
None => 512 | 32 | if standard { STANDARD_SCALE } else { 0 },
};
let kept = if model { kept | MODEL_TYPE } else { kept & !MODEL_TYPE };
kept | if page.lineweights { 128 } else { 0 } | if page.center { 4 } else { 0 } | if page.show_plot_styles { 2 } else { 0 }
}
@@ -446,7 +452,7 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
// The file's standard scale (such as 1:50) while the scale is still the one read with it.
let file_standard = page.file_standard_scale.filter(|&(_, s)| !page.scale_to_fit && s == scale).map(|(code, _)| code);
let standard = page.scale_to_fit || scale == 1.0 || file_standard.is_some();
let plot_flags = plot_layout_flags(page, standard);
let plot_flags = plot_layout_flags(page, standard, data.model);
let plot_type = match page.plot_area.as_str() {
"display" => 0,
"extents" => 1,
@@ -610,6 +616,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
view: None,
ucs: None,
limits: None,
model: true,
},
);
for (i, (_, brh, l)) in ps_brs.iter().enumerate() {
@@ -627,6 +634,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
view: l.view,
ucs: l.ucs.as_ref(),
limits: l.limits,
model: false,
},
);
}
+8 -3
View File
@@ -37,7 +37,7 @@ pub use cadcraft_doc::Format;
pub use craft_dxf::Version;
pub use dxf_raw::{ObjectRecord, object_records};
pub use dxf_read::entity_from_groups;
pub use dxf_write::{entity_groups, proxies_lost};
pub use dxf_write::{dwg_compat_lost, entity_groups, proxies_lost};
pub use pdf::{PdfOptions, pdf, plot};
/// How a drawing is saved as DXF or DWG.
@@ -164,8 +164,13 @@ pub fn write_noted(d: &Drawing, name: impl AsRef<Path>, opts: &SaveOptions) -> R
/// file they came from (`Foreign::version`, not `$ACADVER`, which SAVEAS changes), and the bridge
/// reads them as that version.
fn write_dwg(d: &Drawing, version: Version) -> Result<(Vec<u8>, craft_dwg::Unwritten)> {
let bridge = dxf_write::dwg_bridge(d, version);
craft_dwg::encode_kept_noted(bridge.as_bytes(), version.code(), d.foreign.version.as_deref()).map_err(dwg_error)
let (bridge, omitted) = dxf_write::dwg_bridge(d, version);
let (bytes, mut unwritten) = craft_dwg::encode_kept_noted(bridge.as_bytes(), version.code(), d.foreign.version.as_deref()).map_err(dwg_error)?;
for (kind, omitted) in omitted {
let count = unwritten.entry(kind).or_default();
*count = count.saturating_add(omitted);
}
Ok((bytes, unwritten))
}
/// Like [`write`], but image formats (PNG, SVG, PDF) show `window` (a model-space rectangle in
+6 -2
View File
@@ -39,7 +39,11 @@ fn drawing() -> Drawing {
d.add(
&Space::Model,
Common::default(),
EntityKind::Unknown(Unknown { dxf_type: "ACME_WIDGET".into(), tags: vec![tag(100, "AcDbEntity"), tag(10, "1.0"), tag(20, "2.0")] }),
EntityKind::Unknown(Unknown {
dxf_type: "ACME_WIDGET".into(),
tags: vec![tag(100, "AcDbEntity"), tag(10, "1.0"), tag(20, "2.0")],
graphics: Vec::new(),
}),
)
.unwrap();
d.add(&Space::Paper("Layout1".into()), Common::default(), line((1.0, 1.0), (2.0, 2.0))).unwrap();
@@ -521,7 +525,7 @@ fn corpus_round_trip_report() {
fn types_the_dwg_writer_cannot_write_are_reported_lost() {
use corpus::{CorpusReport, FileReport, Format, round_trip};
crate::dwg_worker::allow_in_process();
let unknown = |t: &str, tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: t.into(), tags });
let unknown = |t: &str, tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: t.into(), tags, graphics: Vec::new() });
let mut d = Drawing::new_metric();
let widget = vec![tag(100, "AcDbEntity"), tag(100, "AcmeWidget"), tag(10, "1.0"), tag(20, "2.0"), tag(30, "0.0")];
d.add(&Space::Model, Common::default(), unknown("ACME_WIDGET", widget.clone())).unwrap();
+534 -1
View File
@@ -111,6 +111,7 @@ fn sample() -> Drawing {
loops: vec![HatchLoop {
vertices: vec![PolyVertex::new(Vec2::ZERO), PolyVertex::new(Vec2::new(2.0, 0.0)), PolyVertex::new(Vec2::new(2.0, 2.0))],
outer: true,
boundary_flags: Some(3),
sources: Vec::new(),
}],
scale: 1.0,
@@ -422,6 +423,30 @@ fn hostile_dxf_does_not_panic() {
}
}
// Regression test for #1336: the LAYER table of a DXF had no record cap, so a hostile file could
// grow the layer list without bound (its VIEW/UCS/VPORT peers stop at one million records).
#[test]
fn dxf_layer_table_stops_at_the_record_cap() {
use std::fmt::Write as _;
let records = 1_000_100;
let mut text = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLAYER\n");
for i in 0..records {
let _ = write!(text, "0\nLAYER\n2\nL{i}\n");
}
text.push_str("0\nENDTAB\n0\nENDSEC\n0\nEOF\n");
let d = read(text.as_bytes(), "layers.dxf").unwrap();
// The exact total, not a range: the layer list stops at 1,000,000 layers, the drawing's own
// default layers counted among them, so a cap that truncates early or late fails as loudly as
// none at all. The count is a literal on purpose -- if the constant changes, this test must fail
// rather than follow it.
assert_eq!(
d.layers.len(),
1_000_000,
"the LAYER table must stop at exactly 1,000,000 layers in total, defaults included, reading {records} records, but kept {}",
d.layers.len()
);
}
#[test]
fn svg_and_png_export() {
let d = sample();
@@ -2005,6 +2030,514 @@ fn intl_text(value: &str) -> Text {
}
}
fn two_point_text_sample() -> Drawing {
let mut drawing = Drawing::new_metric();
let mut block = Block::new("Labels");
let mut attribs = Vec::new();
for (index, halign) in [HAlign::Aligned, HAlign::Fit].into_iter().enumerate() {
for multiplier in [1.0, 2.0] {
let text =
Text { insert: Vec3::ZERO, align_pt: Some(Vec3::new(30.0 * multiplier, 4.0 * multiplier, 0.0)), halign, ..intl_text("SYNTHETIC") };
drawing.add(&Space::Model, Common::default(), EntityKind::Text(text.clone())).unwrap();
let attribute = Attrib {
tag: format!("LABEL{index}_{multiplier}"),
text,
invisible: false,
constant: false,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
};
block.entities.push(Entity::new(Handle(0x500 + attribs.len() as u64), EntityKind::AttDef(attribute.clone())));
attribs.push(attribute);
}
}
drawing.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
drawing
.add(
&Space::Model,
Common::default(),
EntityKind::Insert(Insert {
block: "Labels".into(),
insert: Vec3::ZERO,
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs,
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}),
)
.unwrap();
drawing
}
fn two_point_texts(drawing: &Drawing) -> Vec<&Text> {
let mut texts = Vec::new();
for entity in drawing.model.iter() {
match &entity.kind {
EntityKind::Text(text) => texts.push(text),
EntityKind::Insert(insert) => texts.extend(insert.attribs.iter().map(|attribute| &attribute.text)),
_ => {}
}
}
texts.extend(
drawing
.block("Labels")
.unwrap()
.entities
.iter()
.filter_map(|entity| if let EntityKind::AttDef(attribute) = &entity.kind { Some(&attribute.text) } else { None }),
);
texts
}
fn edit_two_point_texts(d: &mut Drawing, edit: impl Fn(&mut Text)) {
fn store(store: &mut EntityStore, edit: &impl Fn(&mut Text)) {
for handle in store.handles() {
store.modify(handle, |e| match &mut e.kind {
EntityKind::Text(t) => edit(t),
EntityKind::AttDef(a) => edit(&mut a.text),
EntityKind::Insert(i) => i.attribs.iter_mut().for_each(|a| edit(&mut a.text)),
_ => {}
});
}
}
store(&mut d.model, &edit);
for block in d.blocks.values_mut() {
store(&mut std::sync::Arc::make_mut(block).entities, &edit);
}
}
// Original synthetic DXF records with measurements deliberately different from our stroke font.
fn imported_two_point_text_sample() -> Drawing {
let tags = craft_dxf::parse(write_dxf(&two_point_text_sample()).as_bytes()).unwrap();
let mut altered = tags.clone();
// Work on complete records, including their leading group 0.
let starts: Vec<usize> = tags.iter().enumerate().filter_map(|(i, t)| (t.code == 0).then_some(i)).chain([tags.len()]).collect();
for pair in starts.windows(2) {
let record = &tags[pair[0]..pair[1]];
if !matches!(record[0].str().as_ref(), "TEXT" | "ATTDEF" | "ATTRIB") {
continue;
}
let number = |code| record.iter().find(|t| t.code == code).map(|t| t.str().parse::<f64>().unwrap()).unwrap_or(0.0);
let distance = Vec2::new(number(10), number(20)).dist(Vec2::new(number(11), number(21)));
let width = cadcraft_fonts::shape_stroke("SYNTHETIC", 2.5, 1.0, 0.0).width;
let aligned = number(72) == 3.0;
let code = if aligned { 40 } else { 41 };
let dimension = if aligned { 2.5 } else { 1.0 } * distance / width * 1.15;
for tag in &mut altered[pair[0]..pair[1]] {
if tag.code == code {
*tag = craft_dxf::Tag::new(code, craft_dxf::Value::Real(dimension));
}
if tag.code == 50 {
*tag = craft_dxf::Tag::new(50, craft_dxf::Value::Real(0.0));
}
}
}
read_dxf(craft_dxf::write_ascii(&altered).as_bytes()).unwrap()
}
fn check_two_point_save(d: &Drawing, name: &str, recompute: bool, rotation: bool) {
let saved = read(&write(d, name).unwrap(), name).unwrap();
let before = two_point_texts(d);
let after = two_point_texts(&saved);
assert_eq!(after.len(), before.len());
for (original, text) in before.into_iter().zip(&after) {
if rotation {
assert!((text.rotation - text.insert.xy().angle_to(text.align_pt.unwrap().xy())).abs() < 1e-10, "{name}: {text:?}");
}
if recompute {
let width =
cadcraft_fonts::shape_stroke_dir(&original.value, original.height, original.width_factor, original.oblique, Some(false)).width;
let scale = original.insert.xy().dist(original.align_pt.unwrap().xy()) / width;
let (height, factor) = if original.halign == HAlign::Aligned {
(original.height * scale, original.width_factor)
} else {
(original.height, original.width_factor * scale)
};
assert!((text.height / height - 1.0).abs() < 1e-12, "height: {name}");
assert!((text.width_factor / factor - 1.0).abs() < 1e-12, "width factor: {name}");
} else {
assert!((text.height - original.height).abs() < 1e-10, "{name}");
assert!((text.width_factor - original.width_factor).abs() < 1e-10, "{name}");
}
}
let again = read(&write(&saved, name).unwrap(), name).unwrap();
for (first, second) in after.into_iter().zip(two_point_texts(&again)) {
assert!((first.rotation - second.rotation).abs() < 1e-10, "{name}");
assert!((first.height - second.height).abs() < 1e-10, "{name}");
assert!((first.width_factor - second.width_factor).abs() < 1e-10, "{name}");
}
}
fn two_point_formats() -> [&'static str; 2] {
crate::dwg_worker::allow_in_process();
["fit.dxf", "fit.dwg"]
}
#[test]
fn two_point_imported_measurements_survive_save() {
for name in two_point_formats() {
check_two_point_save(&imported_two_point_text_sample(), name, false, false);
}
}
#[test]
fn two_point_imported_rotation_follows_points() {
for name in two_point_formats() {
check_two_point_save(&imported_two_point_text_sample(), name, false, true);
}
}
fn transform_two_point_sample(d: &mut Drawing, matrix: cadcraft_geom::Mat3) {
// Transform the reference itself so attached attributes follow the production path.
for handle in d.model.handles() {
d.model.modify(handle, |entity| entity.kind.transform(&matrix));
}
}
#[test]
fn two_point_imported_measurements_survive_move() {
let mut d = imported_two_point_text_sample();
transform_two_point_sample(&mut d, cadcraft_geom::Mat3::translate(Vec2::new(47.0, -19.0)));
for name in two_point_formats() {
check_two_point_save(&d, name, false, true);
}
}
#[test]
fn two_point_imported_measurements_survive_rotate() {
let mut d = imported_two_point_text_sample();
transform_two_point_sample(&mut d, cadcraft_geom::Mat3::rotate_about(Vec2::new(7.0, -3.0), 0.73));
for name in two_point_formats() {
check_two_point_save(&d, name, false, true);
}
}
#[test]
fn two_point_imported_measurements_follow_uniform_scale() {
let mut d = imported_two_point_text_sample();
let imported = d.clone();
transform_two_point_sample(&mut d, cadcraft_geom::Mat3::scale_about(Vec2::new(7.0, -3.0), 2.0));
for (before, scaled) in two_point_texts(&imported).into_iter().zip(two_point_texts(&d)).take(8) {
assert!((scaled.height - before.height * 2.0).abs() < 1e-10);
assert!((scaled.width_factor - before.width_factor).abs() < 1e-10);
}
for name in two_point_formats() {
check_two_point_save(&d, name, false, true);
}
}
#[test]
fn two_point_changed_fit_height_recomputes_measurements() {
let mut d = imported_two_point_text_sample();
edit_two_point_texts(&mut d, |t| t.height *= 1.4);
for name in two_point_formats() {
// Aligned height is derived from distance, so editing it alone preserves the import.
let saved = read(&write(&d, name).unwrap(), name).unwrap();
for (before, after) in two_point_texts(&d).into_iter().zip(two_point_texts(&saved)) {
if before.halign == HAlign::Fit {
let expected = cadcraft_render::fitted_text_entity(&d, before, &before.value);
assert!((after.width_factor / expected.width_factor - 1.0).abs() < 1e-12);
}
}
}
}
#[test]
fn two_point_imported_distance_uses_relative_tolerance() {
let mut d = imported_two_point_text_sample();
edit_two_point_texts(&mut d, |t| {
let point = t.align_pt.as_mut().unwrap();
point.x *= 1.0 + 0.5e-9;
point.y *= 1.0 + 0.5e-9;
});
for name in two_point_formats() {
check_two_point_save(&d, name, false, true);
}
}
#[test]
fn two_point_changed_fitting_inputs_recompute_measurements() {
for input in ["style", "oblique", "width factor"] {
let mut d = imported_two_point_text_sample();
edit_two_point_texts(&mut d, |t| match input {
"style" => t.style = "Replacement".into(),
"oblique" => t.oblique += 0.2,
_ => t.width_factor *= 1.2,
});
for name in two_point_formats() {
check_two_point_save(&d, name, true, true);
}
}
}
#[test]
fn two_point_changed_string_recomputes_measurements() {
let mut d = imported_two_point_text_sample();
edit_two_point_texts(&mut d, |t| t.value.push_str(" EDITED"));
for name in two_point_formats() {
check_two_point_save(&d, name, true, false);
}
}
#[test]
fn two_point_changed_distance_scales_aligned_and_recomputes_fit() {
let mut d = imported_two_point_text_sample();
let imported = d.clone();
edit_two_point_texts(&mut d, |t| t.align_pt.as_mut().unwrap().x *= 1.8);
for name in two_point_formats() {
let saved = read(&write(&d, name).unwrap(), name).unwrap();
for ((before, edited), after) in two_point_texts(&imported).into_iter().zip(two_point_texts(&d)).zip(two_point_texts(&saved)) {
if before.halign == HAlign::Aligned {
let ratio = edited.insert.xy().dist(edited.align_pt.unwrap().xy()) / before.insert.xy().dist(before.align_pt.unwrap().xy());
assert!((after.height / (before.height * ratio) - 1.0).abs() < 1e-12, "{name}");
} else {
let expected = cadcraft_render::fitted_text_entity(&d, edited, &edited.value);
assert!((after.width_factor / expected.width_factor - 1.0).abs() < 1e-12, "{name}");
}
}
check_two_point_save(&saved, name, false, true);
}
}
#[test]
fn two_point_authored_text_recomputes_measurements() {
for name in two_point_formats() {
check_two_point_save(&two_point_text_sample(), name, true, false);
}
}
#[test]
fn two_point_text_save_keeps_degenerate_and_unrelated_values() {
for halign in [HAlign::Left, HAlign::Center, HAlign::Right, HAlign::Middle, HAlign::Aligned, HAlign::Fit] {
for valign in [VAlign::Baseline, VAlign::Bottom] {
for align_pt in [None, Some(Vec3::ZERO), Some(Vec3::new(30.0, 4.0, 0.0))] {
if matches!(halign, HAlign::Aligned | HAlign::Fit) && align_pt.is_some_and(|point| point != Vec3::ZERO) {
continue;
}
let text = Text { insert: Vec3::ZERO, align_pt, halign, valign, rotation: 0.7, width_factor: 0.8, ..intl_text("SYNTHETIC") };
let mut drawing = Drawing::new_metric();
drawing.add(&Space::Model, Common::default(), EntityKind::Text(text.clone())).unwrap();
let saved = read(&write(&drawing, "edge.dxf").unwrap(), "edge.dxf").unwrap();
let back = first(&saved, |kind| if let EntityKind::Text(text) = kind { Some(text.clone()) } else { None });
assert!((text.rotation - back.rotation).abs() < 1e-12);
assert!((text.height - back.height).abs() < 1e-10);
assert!((text.width_factor - back.width_factor).abs() < 1e-10);
}
}
}
}
#[test]
fn two_point_imported_degenerate_geometry_keeps_edited_height() {
for missing in [false, true] {
let mut d = imported_two_point_text_sample();
let handle = d.model.handles()[0];
d.model.modify(handle, |entity| {
if let EntityKind::Text(t) = &mut entity.kind {
t.insert = Vec3::ZERO;
t.align_pt = if missing { None } else { Some(Vec3::ZERO) };
t.height = 2.0;
}
});
let snapshot = &mut std::sync::Arc::make_mut(&mut d.foreign).text_fits.get_mut(&handle).unwrap()[0].0;
snapshot.insert = Vec3::ZERO;
snapshot.align_pt = if missing { None } else { Some(Vec3::ZERO) };
snapshot.height = 2.0;
let mut d = read(&write(&d, "edge.dxf").unwrap(), "edge.dxf").unwrap();
let handle = d.model.handles()[0];
let imported = first(&d, |kind| if let EntityKind::Text(t) = kind { Some(t.clone()) } else { None });
assert_eq!(imported.align_pt, if missing { None } else { Some(Vec3::ZERO) });
d.model.modify(handle, |entity| {
if let EntityKind::Text(t) = &mut entity.kind {
t.height = 4.0;
}
});
let saved = read(&write(&d, "edge.dxf").unwrap(), "edge.dxf").unwrap();
let text = first(&saved, |kind| if let EntityKind::Text(t) = kind { Some(t.clone()) } else { None });
assert!((text.height - 4.0).abs() < 1e-10, "missing: {missing}");
}
}
#[test]
fn two_point_imported_nonfinite_geometry_keeps_edited_height() {
let mut d = imported_two_point_text_sample();
let handle = d.model.handles()[0];
d.model.modify(handle, |entity| {
if let EntityKind::Text(t) = &mut entity.kind {
assert_eq!(t.halign, HAlign::Aligned);
t.insert = Vec3::ZERO;
t.align_pt = Some(Vec3::new(f64::INFINITY, 0.0, 0.0));
t.height = 4.0;
}
});
let snapshot = &mut std::sync::Arc::make_mut(&mut d.foreign).text_fits.get_mut(&handle).unwrap()[0].0;
snapshot.insert = Vec3::ZERO;
snapshot.align_pt = Some(Vec3::new(f64::INFINITY, 0.0, 0.0));
snapshot.height = 2.0;
let saved = read(&write(&d, "edge.dxf").unwrap(), "edge.dxf").unwrap();
let text = first(&saved, |kind| if let EntityKind::Text(t) = kind { Some(t.clone()) } else { None });
assert!((text.height - 4.0).abs() < 1e-10);
}
#[test]
fn two_point_imported_empty_attdef_keeps_dimensions_when_points_move() {
let mut d = imported_two_point_text_sample();
let block = std::sync::Arc::make_mut(d.blocks.get_mut("Labels").unwrap());
let handle = block.entities.handles()[0];
block.entities.modify(handle, |entity| {
if let EntityKind::AttDef(a) = &mut entity.kind {
a.text.value.clear();
a.text.insert = Vec3::ZERO;
a.text.align_pt = Some(Vec3::new(10.0, 0.0, 0.0));
a.text.height = 2.0;
a.text.width_factor = 0.8;
}
});
let snapshot = &mut std::sync::Arc::make_mut(&mut d.foreign).text_fits.get_mut(&handle).unwrap()[0].0;
snapshot.value.clear();
snapshot.insert = Vec3::ZERO;
snapshot.align_pt = Some(Vec3::new(10.0, 0.0, 0.0));
snapshot.height = 2.0;
snapshot.width_factor = 0.8;
let mut d = read(&write(&d, "empty.dxf").unwrap(), "empty.dxf").unwrap();
let block = std::sync::Arc::make_mut(d.blocks.get_mut("Labels").unwrap());
let handle = block.entities.handles()[0];
block.entities.modify(handle, |entity| {
if let EntityKind::AttDef(a) = &mut entity.kind {
a.text.align_pt = Some(Vec3::new(0.0, 20.0, 0.0));
}
});
let saved = read(&write(&d, "empty.dxf").unwrap(), "empty.dxf").unwrap();
let entity = saved.block("Labels").unwrap().entities.iter().next().unwrap();
let EntityKind::AttDef(a) = &entity.kind else { panic!("expected ATTDEF") };
assert!((a.text.height - 2.0).abs() < 1e-10);
assert!((a.text.width_factor - 0.8).abs() < 1e-10);
assert!((a.text.rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-10);
}
#[test]
fn two_point_changed_style_definition_recomputes_measurements() {
let mut d = imported_two_point_text_sample();
d.text_styles.iter_mut().find(|style| style.name.eq_ignore_ascii_case("Standard")).unwrap().backwards = true;
for name in two_point_formats() {
let saved = read(&write(&d, name).unwrap(), name).unwrap();
for (before, after) in two_point_texts(&d).into_iter().zip(two_point_texts(&saved)) {
let expected = cadcraft_render::fitted_text_entity(&d, before, &before.value);
assert!((after.height - expected.height).abs() < 1e-9, "{name}");
assert!((after.width_factor - expected.width_factor).abs() < 1e-9, "{name}");
}
}
}
#[test]
fn two_point_changed_justification_recomputes_measurements() {
for horizontal in [true, false] {
let mut d = imported_two_point_text_sample();
edit_two_point_texts(&mut d, |t| {
if horizontal {
t.halign = if t.halign == HAlign::Fit { HAlign::Aligned } else { HAlign::Fit };
} else {
t.valign = VAlign::Middle;
}
});
for name in two_point_formats() {
check_two_point_save(&d, name, true, true);
}
}
}
#[test]
fn two_point_dwg_source_preserves_imported_measurements() {
let imported = imported_two_point_text_sample();
crate::dwg_worker::allow_in_process();
let dwg = write(&imported, "source.dwg").unwrap();
let reopened = read(&dwg, "source.dwg").unwrap();
assert!(!reopened.foreign.text_fits.is_empty());
for name in two_point_formats() {
check_two_point_save(&reopened, name, false, true);
}
}
#[test]
fn two_point_block_layout_and_empty_default() {
let mut d = Drawing::new_metric();
let mut block = Block::new("Labels");
for (index, halign) in [HAlign::Aligned, HAlign::Fit].into_iter().enumerate() {
let text = Text { halign, valign: VAlign::Middle, align_pt: Some(Vec3::new(30.0, 4.0, 0.0)), ..intl_text("SYNTHETIC") };
block.entities.push(Entity::new(Handle(0x500 + index as u64), EntityKind::Text(text.clone())));
d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Text(text)).unwrap();
let empty = Text { halign, align_pt: Some(Vec3::new(30.0, 4.0, 0.0)), ..intl_text("") };
block.entities.push(Entity::new(
Handle(0x510 + index as u64),
EntityKind::AttDef(Attrib {
tag: "LABEL".into(),
text: empty,
invisible: false,
constant: false,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
}),
));
}
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
for name in two_point_formats() {
let saved = read(&write(&d, name).unwrap(), name).unwrap();
for (before, after) in d.block("Labels").unwrap().entities.iter().zip(saved.block("Labels").unwrap().entities.iter()) {
match (&before.kind, &after.kind) {
(EntityKind::Text(a), EntityKind::Text(b)) => {
let expected = cadcraft_render::fitted_text_entity(&d, a, &a.value);
assert!((b.height - expected.height).abs() < 1e-9);
assert!((b.width_factor - expected.width_factor).abs() < 1e-9);
}
(EntityKind::AttDef(a), EntityKind::AttDef(b)) => {
assert!((a.text.height - b.text.height).abs() < 1e-9);
assert!((a.text.width_factor - b.text.width_factor).abs() < 1e-9);
assert!((b.text.rotation - b.text.insert.xy().angle_to(b.text.align_pt.unwrap().xy())).abs() < 1e-9);
}
_ => panic!("unexpected block entity"),
}
}
let before = &d.layout("Layout1").unwrap().entities;
let after = &saved.layout("Layout1").unwrap().entities;
for (a, b) in before.iter().zip(after.iter()) {
if let (EntityKind::Text(a), EntityKind::Text(b)) = (&a.kind, &b.kind) {
let expected = cadcraft_render::fitted_text_entity(&d, a, &a.value);
assert!((b.height - expected.height).abs() < 1e-9);
assert!((b.width_factor - expected.width_factor).abs() < 1e-9);
}
}
assert_eq!(before.len(), after.len());
}
}
#[test]
fn two_point_nonuniform_insert_keeps_attribute_fit_in_its_stored_coordinates() {
let mut d = two_point_text_sample();
for h in d.model.handles() {
d.model.modify(h, |e| {
if let EntityKind::Insert(i) = &mut e.kind {
i.scale = Vec3::new(2.0, 0.5, 1.0);
}
});
}
for name in two_point_formats() {
let saved = read(&write(&d, name).unwrap(), name).unwrap();
let insert = saved.model.iter().find_map(|e| if let EntityKind::Insert(i) = &e.kind { Some(i) } else { None }).unwrap();
let fit = insert.attribs.iter().find(|a| a.text.halign == HAlign::Fit).unwrap();
let width = cadcraft_fonts::shape_stroke_dir(&fit.text.value, fit.text.height, fit.text.width_factor, fit.text.oblique, Some(false)).width;
assert!((width - fit.text.insert.xy().dist(fit.text.align_pt.unwrap().xy())).abs() < 1e-9);
assert!((insert.scale.x - 2.0).abs() < 1e-9 && (insert.scale.y - 0.5).abs() < 1e-9);
}
}
fn intl_sample() -> Drawing {
let mut d = Drawing::new_metric();
let layer = format!("层 {INTL}");
@@ -2419,7 +2952,7 @@ fn gradient_sample() -> (Drawing, Vec<Option<Gradient>>) {
let h = Hatch {
pattern: "SOLID".into(),
solid: true,
loops: vec![HatchLoop { vertices: square.clone(), outer: true, sources: Vec::new() }],
loops: vec![HatchLoop { vertices: square.clone(), outer: true, boundary_flags: Some(3), sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
+48
View File
@@ -0,0 +1,48 @@
//! DIMASSOC is a drawing variable, written as HEADER group 280, independently of DIMSTYLE.
use cadcraft_doc::Drawing;
use cadcraft_io::{SaveOptions, Version, read_dxf, write, write_with};
/// Extract every DIMASSOC HEADER entry so duplicate or mistyped values fail the assertions.
fn dimassoc_groups(bytes: &[u8]) -> Vec<(i32, i64)> {
let tags = craft_dxf::parse(bytes).unwrap();
let header = craft_dxf::sections(&tags).into_iter().find(|s| s.name == "HEADER").unwrap();
let mut found = Vec::new();
for pair in header.tags.windows(2) {
if pair[0].code == 9 && pair[0].str() == "$DIMASSOC" {
found.push((pair[1].code, pair[1].i64()));
}
}
found
}
/// All supported modes use group 280 and survive each tested DXF version and encoding.
#[test]
fn new_drawing_modes_use_group_280_in_ascii_and_binary_dxf() {
for mode in [0, 1, 2] {
let mut d = Drawing::new_metric();
d.header.set_i64("DIMASSOC", mode);
for version in [Version::R2000, Version::R2004, Version::R2007, Version::R2018] {
for binary in [false, true] {
let bytes = write_with(&d, "setting.dxf", &SaveOptions { version: Some(version), binary }).unwrap();
assert_eq!(dimassoc_groups(&bytes), [(280, mode)], "{version:?}, binary{binary}");
let back = read_dxf(&bytes).unwrap();
assert_eq!(back.header.i64("DIMASSOC", -1), mode);
}
}
}
}
/// Editing an imported mode replaces its stored value without emitting a second HEADER entry.
#[test]
fn an_imported_mode_can_be_changed_without_a_stale_or_duplicate_header() {
let source = b"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$DIMASSOC\n280\n1\n0\nENDSEC\n0\nEOF\n";
let mut d = read_dxf(source).unwrap();
assert_eq!(d.header.i64("DIMASSOC", -1), 1);
for mode in [1, 0, 2] {
d.header.set_i64("DIMASSOC", mode);
let bytes = write(&d, "edited.dxf").unwrap();
assert_eq!(dimassoc_groups(&bytes), [(280, mode)]);
d = read_dxf(&bytes).unwrap();
assert_eq!(d.header.i64("DIMASSOC", -1), mode);
}
}
+1 -1
View File
@@ -370,7 +370,7 @@ fn top_line_kept_objects_and_unknown(handle: Handle) -> Drawing {
RawTag { code: 100, value: "SyntheticWidget".into() },
RawTag { code: 1, value: "widget".into() },
];
let kind = EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags });
let kind = EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags, graphics: Vec::new() });
d.model.push(Entity { handle, common: Common::default(), kind });
d
}
+1 -1
View File
@@ -166,7 +166,7 @@ fn sat_text_is_told_by_its_subclass_and_a_geometry_record() {
use cadcraft_doc::foreign::{Foreign, sat_text_acis};
use cadcraft_doc::{Handle, RawTag, Unknown};
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let solid = |tags: Vec<RawTag>| Unknown { dxf_type: "3DSOLID".into(), tags };
let solid = |tags: Vec<RawTag>| Unknown { dxf_type: "3DSOLID".into(), tags, graphics: Vec::new() };
let none = std::collections::BTreeSet::new();
let h = Handle(0x2B);
// A stray 1 or 3 outside AcDbModelerGeometry is not SAT text.
+1 -1
View File
@@ -118,7 +118,7 @@ fn hatch(pattern: &str, gradient: Option<Gradient>) -> Hatch {
Hatch {
pattern: pattern.into(),
solid: pattern == "SOLID",
loops: vec![HatchLoop { vertices: square(10.0), outer: true, sources: Vec::new() }],
loops: vec![HatchLoop { vertices: square(10.0), outer: true, boundary_flags: None, sources: Vec::new() }],
scale: 2.0,
angle: 0.25,
associative: false,
+5 -5
View File
@@ -41,8 +41,8 @@ fn source_boundary_objects_roundtrip() {
let outer = poly(&mut d, square(0.0, 20.0));
let island = poly(&mut d, square(5.0, 5.0));
let loops = vec![
HatchLoop { vertices: square(0.0, 20.0), outer: true, sources: vec![outer] },
HatchLoop { vertices: square(5.0, 5.0), outer: false, sources: vec![island] },
HatchLoop { vertices: square(0.0, 20.0), outer: true, boundary_flags: None, sources: vec![outer] },
HatchLoop { vertices: square(5.0, 5.0), outer: false, boundary_flags: None, sources: vec![island] },
];
d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch(loops.clone(), true))).expect("add");
// A non-associative hatch writes no sources; a source that is gone isn't written.
@@ -79,7 +79,7 @@ fn join(p: &[(i32, String)]) -> String {
fn sources_after_spline_fit_data_and_hostile_counts() {
let mut d = Drawing::new_imperial();
let outer = poly(&mut d, square(0.0, 20.0));
let loops = vec![HatchLoop { vertices: square(0.0, 20.0), outer: true, sources: vec![outer] }];
let loops = vec![HatchLoop { vertices: square(0.0, 20.0), outer: true, boundary_flags: None, sources: vec![outer] }];
d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch(loops, true))).expect("add");
let p = pairs(&write_dxf(&d));
let start = p.iter().position(|(c, v)| *c == 0 && v == "HATCH").expect("HATCH");
@@ -127,11 +127,11 @@ fn a_hatch_in_a_block_keeps_its_boundary_and_the_boundary_its_reactor() {
let fill = d.new_handle();
let k = EntityKind::LwPolyline(LwPolyline { vertices: square(0.0, 10.0), closed: true, const_width: 0.0, elevation: 0.0, plinegen: false });
b.entities.push(Entity::new(outline, k));
let loops = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, sources: vec![outline] }];
let loops = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, boundary_flags: None, sources: vec![outline] }];
b.entities.push(Entity::new(fill, EntityKind::Hatch(hatch(loops, true))));
d.blocks.insert("Tag".into(), std::sync::Arc::new(b));
// A model-space hatch whose source is in the block is not linked to it.
let stray = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, sources: vec![outline] }];
let stray = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, boundary_flags: None, sources: vec![outline] }];
let other = d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch(stray, true))).expect("add");
let p = pairs(&write_dxf(&d));
let poly = record(&p, "LWPOLYLINE", outline);
+145
View File
@@ -0,0 +1,145 @@
use cadcraft_doc::{Drawing, EntityKind, HatchLoop, Region};
use cadcraft_io::{read_dxf, write_dxf};
fn boundary(points: &[(f64, f64)], flags: i64) -> String {
let mut text = format!("92\n{flags}\n");
if flags & 2 != 0 {
text.push_str(&format!("72\n0\n73\n1\n93\n{}\n", points.len()));
for (point_x, point_y) in points {
text.push_str(&format!("10\n{point_x}\n20\n{point_y}\n"));
}
} else {
text.push_str(&format!("93\n{}\n", points.len()));
for (start, end) in points.iter().zip(points.iter().cycle().skip(1)) {
text.push_str(&format!("72\n1\n10\n{}\n20\n{}\n11\n{}\n21\n{}\n", start.0, start.1, end.0, end.1));
}
}
text.push_str("97\n0\n");
text
}
fn logo(flags: [i64; 4]) -> String {
let hexagon = [(-10.0, 0.0), (-5.0, -8.0), (5.0, -8.0), (10.0, 0.0), (5.0, 8.0), (-5.0, 8.0)];
let letter = [(-3.0, -4.0), (3.0, -4.0), (3.0, -2.0), (-1.0, -2.0), (-1.0, 4.0), (-3.0, 4.0)];
let right: Vec<_> = hexagon.iter().map(|(point_x, point_y)| (point_x + 28.0, *point_y)).collect();
let hole: Vec<_> = hexagon.iter().map(|(point_x, point_y)| (point_x * 0.6 + 28.0, point_y * 0.6)).collect();
let mut text = String::from("0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n");
for (index, loops) in
[[(&hexagon[..], flags[0]), (&letter[..], flags[1])], [(&right[..], flags[2]), (&hole[..], flags[3])]].into_iter().enumerate()
{
text.push_str(&format!(
"0\nHATCH\n5\n{:X}\n100\nAcDbEntity\n8\n0\n100\nAcDbHatch\n10\n0\n20\n0\n30\n0\n210\n0\n220\n0\n230\n1\n2\nSOLID\n70\n1\n71\n0\n91\n2\n",
0x100 + index
));
for (points, flags) in loops {
text.push_str(&boundary(points, flags));
}
text.push_str("75\n1\n76\n1\n98\n0\n");
}
text.push_str("0\nENDSEC\n0\nEOF\n");
text
}
fn flags_written(drawing: &Drawing) -> Vec<i64> {
let text = write_dxf(drawing);
let lines: Vec<_> = text.lines().collect();
let mut hatch = false;
lines
.as_chunks::<2>()
.0
.iter()
.filter_map(|pair| {
let code: i32 = pair[0].trim().parse().unwrap();
if code == 0 {
hatch = pair[1].trim() == "HATCH";
}
if hatch && code == 92 { Some(pair[1].trim().parse().unwrap()) } else { None }
})
.collect()
}
#[test]
fn boundary_flags_survive_dxf_open_and_save() {
for flags in [[7, 22, 7, 6], [7, 22, 6, 20], [0, 9, 16, 31]] {
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
let expected = flags.map(|flag| flag | 2);
assert_eq!(flags_written(&drawing), expected);
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
assert_eq!(flags_written(&back), expected);
for entity in back.model.iter() {
if let EntityKind::Hatch(hatch) = &entity.kind {
let json = serde_json::to_vec(&hatch.loops).unwrap();
let restored: Vec<HatchLoop> = serde_json::from_slice(&json).unwrap();
assert_eq!(restored, hatch.loops);
}
}
}
}
#[test]
fn reclassified_loops_write_current_external_bit() {
for imported in [7, 23] {
let mut drawing = read_dxf(logo([7, imported, 7, 6]).as_bytes()).unwrap();
let handle = drawing.model.iter().next().unwrap().handle;
drawing.model.modify(handle, |entity| {
let EntityKind::Hatch(hatch) = &mut entity.kind else { panic!("expected hatch") };
assert!(hatch.loops[1].outer);
let mut region = Region { loops: hatch.loops.clone() };
assert!(region.renest());
hatch.loops = region.loops;
assert!(!hatch.loops[1].outer);
assert_eq!(hatch.loops[1].boundary_flags, Some(imported));
});
let written = flags_written(&drawing)[1];
assert_eq!(written & 1, 0);
assert_eq!(written & (4 | 16), imported & (4 | 16));
assert_ne!(written & 2, 0);
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
assert_eq!(flags_written(&back), flags_written(&drawing));
}
}
#[test]
fn undocumented_boundary_bits_are_not_written_back() {
let flags = [i64::MAX, -1, 32 | 7, i64::MIN | 22];
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
let expected = flags.map(|flag| (flag & 31) | 2);
assert_eq!(flags_written(&drawing), expected);
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
assert_eq!(flags_written(&back), expected);
}
#[test]
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
fn boundary_flags_survive_dwg_open_and_both_save_formats() {
cadcraft_io::dwg_worker::allow_in_process();
for flags in [[7, 22, 7, 6], [7, 22, 6, 20]] {
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
let bytes = cadcraft_io::write(&drawing, "logo.dwg").unwrap();
let back = cadcraft_io::read(&bytes, "logo.dwg").unwrap();
let expected = flags.map(|flag| flag | 2);
assert_eq!(flags_written(&back), expected);
let again = cadcraft_io::write(&back, "logo.dwg").unwrap();
assert_eq!(flags_written(&cadcraft_io::read(&again, "logo.dwg").unwrap()), expected);
}
}
#[test]
fn old_serialized_loops_keep_locally_created_flags() {
let mut drawing = read_dxf(logo([7, 22, 6, 20]).as_bytes()).unwrap();
let mut expected = Vec::new();
let handles: Vec<_> = drawing.model.iter().map(|entity| entity.handle).collect();
for handle in handles {
drawing.model.modify(handle, |entity| {
if let EntityKind::Hatch(hatch) = &mut entity.kind {
for boundary in &mut hatch.loops {
let mut json = serde_json::to_value(&*boundary).unwrap();
json.as_object_mut().unwrap().remove("boundary_flags");
*boundary = serde_json::from_value::<HatchLoop>(json).unwrap();
expected.push(2 | i64::from(boundary.outer));
}
}
});
}
assert_eq!(flags_written(&drawing), expected);
}
+1 -1
View File
@@ -8,7 +8,7 @@ use cadcraft_io::{read_dxf, write_dxf};
fn square() -> HatchLoop {
let v = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].into_iter().map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).collect();
HatchLoop { vertices: v, outer: true, sources: Vec::new() }
HatchLoop { vertices: v, outer: true, boundary_flags: None, sources: Vec::new() }
}
fn hatch(pattern: &str, scale: f64, angle: f64, origin: Vec2, lines: Vec<PatternLine>) -> Hatch {
+38
View File
@@ -72,3 +72,41 @@ fn the_page_still_decides_the_bits_cadcraft_models() {
d.layouts.last_mut().unwrap().page = PageSetup::default();
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(512 | 128 | 32 | 16));
}
/// Each LAYOUT object's name and plot layout flags (the AcDbLayout group 1 and the
/// AcDbPlotSettings group 70) in DXF text.
fn layout_plot_flags(text: &str) -> Vec<(String, i64)> {
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let mut out = Vec::new();
let (mut inside, mut subclass, mut name, mut flags) = (false, "", None, None);
for pair in lines.chunks(2) {
let [code, value] = pair else { break };
match *code {
"0" => {
if let (true, Some(n), Some(f)) = (inside, name.take(), flags.take()) {
out.push((n, f));
}
(inside, subclass, name, flags) = (*value == "LAYOUT", "", None, None);
}
"100" if inside => subclass = value,
"70" if inside && subclass == "AcDbPlotSettings" => flags = value.parse().ok(),
"1" if inside && subclass == "AcDbLayout" => name = Some(value.to_string()),
_ => {}
}
}
out
}
#[test]
fn only_the_model_layout_carries_the_model_type_flag() {
// 1024 is "ModelType" (DXF Reference, PLOTSETTINGS group 70): the plot settings of model space.
// The Model layout carries it; a paper layout does not, even when it was read with it.
for read in [688, 688 | 1024] {
let bytes = write(&drawing(read), "sheet.dxf").unwrap();
let layouts = layout_plot_flags(&String::from_utf8_lossy(&bytes));
let flags = |name: &str| layouts.iter().find(|(n, _)| n == name).map(|&(_, f)| f);
let (model, sheet) = (flags("Model").unwrap(), flags("SHEET").unwrap());
assert_ne!(model & 1024, 0, "Model, SHEET read with {read}: {layouts:?}");
assert_eq!(sheet & 1024, 0, "SHEET read with {read}: {layouts:?}");
}
}
+4
View File
@@ -31,6 +31,7 @@ mod exhausted_handseed;
mod followups_626;
mod groups_roundtrip;
mod hatch_assoc_roundtrip;
mod hatch_loop_flags;
mod hatch_pattern_def;
mod helix_roundtrip;
mod layer_states_acad;
@@ -68,6 +69,7 @@ mod plot_model_png_scale;
mod plot_styles;
mod polyface_roundtrip;
mod portable_fonts;
mod proxy_graphics;
mod region_roundtrip;
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod render_settings_version;
@@ -90,5 +92,7 @@ mod user_lin_pat_roundtrip;
mod view_tables_roundtrip;
mod view_target;
mod viewport_clip_roundtrip;
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod visualstyle_dwg;
mod xclip_roundtrip;
mod xref_roundtrip;
+172
View File
@@ -0,0 +1,172 @@
//! ACAD_PROXY_ENTITY draws its proxy graphics (#2646): read from DXF with the table indices of the
//! file, measured in the extents, and written back unchanged.
use cadcraft_doc::color::Color;
use cadcraft_doc::{EntityKind, Space};
use cadcraft_io::{read_dxf, write_dxf};
/// A proxy graphics chunk of type `kind`, its data padded to four bytes.
fn chunk(kind: u32, data: &[u8]) -> Vec<u8> {
let mut d = data.to_vec();
d.resize(d.len().div_ceil(4) * 4, 0);
let mut out = ((8 + d.len()) as u32).to_le_bytes().to_vec();
out.extend(kind.to_le_bytes());
out.extend(d);
out
}
/// A point in the XY plane as three doubles.
fn pt(x: f64, y: f64) -> Vec<u8> {
[x, y, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect()
}
/// A balloon: layer 1 of the file's LAYER table, colour 1, a circle, a leader and the number.
fn balloon() -> Vec<u8> {
let mut circle = pt(175.0, 115.0);
circle.extend(6.0f64.to_le_bytes());
circle.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
let mut leader = 2u32.to_le_bytes().to_vec();
leader.extend(pt(170.8, 110.8));
leader.extend(pt(150.0, 90.0));
let mut text = pt(172.9, 112.0);
text.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
text.extend(pt(1.0, 0.0));
text.extend(b"1\0\0\0");
text.extend(1i32.to_le_bytes());
text.extend(0i32.to_le_bytes());
for v in [6.0f64, 1.0, 0.0, 0.0] {
text.extend(v.to_le_bytes());
}
text.extend([0u8; 20]);
text.extend(b"isocp.shx\0\0\0\0\0\0\0");
let chunks = [chunk(16, &1u32.to_le_bytes()), chunk(14, &1u32.to_le_bytes()), chunk(2, &circle), chunk(6, &leader), chunk(11, &text)];
let body = chunks.concat();
let mut out = ((8 + body.len()) as u32).to_le_bytes().to_vec();
out.extend((chunks.len() as u32).to_le_bytes());
out.extend(body);
out
}
/// A DXF whose LAYER table holds 0 and BALLOONS only (CADCraft keeps Defpoints at index 1 of
/// its own table), a text style on isocp.shx, a line and one proxy balloon.
fn file() -> String {
let graphics = balloon();
let hex: Vec<String> = graphics.chunks(127).map(|c| c.iter().map(|b| format!("{b:02X}")).collect()).collect();
let mut tags: Vec<(i32, String)> = vec![(0, "SECTION".into()), (2, "CLASSES".into())];
for (c, v) in [(0, "CLASS"), (1, "SYNBALLOON"), (2, "SynBalloon"), (3, "SyntheticProxyApp"), (90, "0"), (280, "0"), (281, "1"), (0, "ENDSEC")] {
tags.push((c, v.into()));
}
for (c, v) in [
(0, "SECTION"),
(2, "TABLES"),
(0, "TABLE"),
(2, "LAYER"),
(0, "LAYER"),
(5, "10"),
(2, "0"),
(62, "7"),
(0, "LAYER"),
(5, "11"),
(2, "BALLOONS"),
(62, "3"),
(0, "ENDTAB"),
(0, "TABLE"),
(2, "STYLE"),
(0, "STYLE"),
(5, "12"),
(2, "ISO"),
(3, "isocp.shx"),
(0, "ENDTAB"),
(0, "ENDSEC"),
(0, "SECTION"),
(2, "ENTITIES"),
(0, "LINE"),
(5, "20"),
(8, "0"),
(10, "50"),
(20, "40"),
(11, "150"),
(21, "90"),
(0, "ACAD_PROXY_ENTITY"),
(5, "21"),
(100, "AcDbEntity"),
(8, "0"),
(100, "AcDbProxyEntity"),
(90, "498"),
(91, "500"),
(95, "0"),
(70, "0"),
] {
tags.push((c, v.into()));
}
tags.push((92, graphics.len().to_string()));
tags.extend(hex.into_iter().map(|h| (310, h)));
for (c, v) in [(93, "0"), (94, "0"), (0, "ENDSEC"), (0, "EOF")] {
tags.push((c, v.into()));
}
tags.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect()
}
#[test]
fn a_proxy_draws_its_graphics_with_the_files_table_indices() {
let d = read_dxf(file().as_bytes()).expect("read");
let proxy = d.model.iter().find(|e| matches!(e.kind, EntityKind::Unknown(_))).expect("proxy");
let EntityKind::Unknown(u) = &proxy.kind else { unreachable!() };
let kinds: Vec<(&str, &str, Color)> = u.graphics.iter().map(|g| (g.kind.dxf_name(), g.common.layer.as_str(), g.common.color)).collect();
// Layer index 1 is BALLOONS, the file's second layer, not CADCraft's Defpoints.
assert_eq!(kinds, [("CIRCLE", "BALLOONS", Color::Index(1)), ("LINE", "BALLOONS", Color::Index(1)), ("TEXT", "BALLOONS", Color::Index(1))]);
assert!(matches!(&u.graphics[2].kind, EntityKind::Text(t) if t.value == "1" && t.style == "ISO"));
// The extents reach the balloon (the line alone ends at 150, 90).
let b = d.extents(&Space::Model);
assert!(b.max.x >= 181.0 && b.max.y >= 121.0, "{b:?}");
}
#[test]
fn a_proxy_is_written_back_unchanged_and_draws_again() {
let d = read_dxf(file().as_bytes()).expect("read");
let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen");
let graphics = |d: &cadcraft_doc::Drawing| {
d.model.iter().find_map(|e| match &e.kind {
EntityKind::Unknown(u) => Some((u.proxy_graphics_bytes(), u.graphics.len())),
_ => None,
})
};
assert_eq!(graphics(&again), graphics(&d));
assert_eq!(graphics(&d).map(|g| g.1), Some(3));
// The saved LAYER table keeps the file's order, so index 1 is still BALLOONS (CADCraft's
// Defpoints comes after it) and the reopened graphics stay on that layer.
let layers = |d: &cadcraft_doc::Drawing| -> Vec<String> {
d.model
.iter()
.find_map(|e| match &e.kind {
EntityKind::Unknown(u) => Some(u.graphics.iter().map(|g| g.common.layer.clone()).collect()),
_ => None,
})
.unwrap_or_default()
};
assert_eq!(layers(&again), ["BALLOONS"; 3]);
let names: Vec<&str> = again.layers.iter().map(|l| l.name.as_str()).collect();
assert_eq!(names, ["0", "BALLOONS", "Defpoints"]);
}
/// A proxy text takes the first style on its font. With ISO and then Standard both on
/// isocp.shx, it is ISO, and stays ISO after a save: CADCraft's own Standard, which the file's
/// replaces, would otherwise come first in the saved STYLE table.
#[test]
fn a_proxy_text_keeps_its_style_after_a_save() {
let iso = "0\nSTYLE\n5\n12\n2\nISO\n3\nisocp.shx\n";
let src = file().replacen(iso, &format!("{iso}0\nSTYLE\n5\n13\n2\nStandard\n3\nisocp.shx\n"), 1);
let style = |d: &cadcraft_doc::Drawing| {
d.model.iter().find_map(|e| match &e.kind {
EntityKind::Unknown(u) => u.graphics.iter().find_map(|g| match &g.kind {
EntityKind::Text(t) => Some(t.style.clone()),
_ => None,
}),
_ => None,
})
};
let d = read_dxf(src.as_bytes()).expect("read");
assert_eq!(style(&d).as_deref(), Some("ISO"));
let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen");
assert_eq!(style(&again).as_deref(), Some("ISO"), "after a save");
}
+2 -1
View File
@@ -19,7 +19,7 @@ fn regions(d: &Drawing) -> Vec<Region> {
fn square(x: f64, y: f64, s: f64, outer: bool) -> HatchLoop {
let v = |a: f64, b: f64| PolyVertex::new(Vec2::new(a, b));
HatchLoop { vertices: vec![v(x, y), v(x + s, y), v(x + s, y + s), v(x, y + s)], outer, sources: Vec::new() }
HatchLoop { vertices: vec![v(x, y), v(x + s, y), v(x + s, y + s), v(x, y + s)], outer, boundary_flags: None, sources: Vec::new() }
}
#[test]
@@ -29,6 +29,7 @@ fn region_with_islands_survives_save_and_reopen() {
let hole = HatchLoop {
vertices: vec![PolyVertex::with_bulge(Vec2::new(3.0, 5.0), 1.0), PolyVertex::with_bulge(Vec2::new(7.0, 5.0), 1.0)],
outer: false,
boundary_flags: None,
sources: Vec::new(),
};
let r = Region { loops: vec![square(0.0, 0.0, 10.0, true), hole, square(4.5, 4.5, 1.0, true), square(20.0, 0.0, 2.0, true)] };
@@ -226,7 +226,7 @@ pub(crate) fn hatches() -> Vec<Case> {
EntityKind::Hatch(Hatch {
pattern: "SOLID".into(),
solid: true,
loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, sources: Vec::new() }],
loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, boundary_flags: Some(3), sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
+50 -2
View File
@@ -39,8 +39,6 @@ pub(super) fn model(expected: &Drawing, actual: &Drawing, context: &str) {
explodable,
units,
array,
// Session state (when an xref was read), never in a file.
xref_stamp: _,
} = block.as_ref();
equal(name, &back.name, &path, "name");
equal(annotative, &back.annotative, &path, "annotative");
@@ -375,3 +373,53 @@ fn angle_tolerance_does_not_hide_real_changes_or_nonfinite_values() {
assert!(std::panic::catch_unwind(|| angle(0.7, actual, "self-test", "angle")).is_err());
}
}
/// Authored two-point text saves the dimensions of its measured span. Expectations come from
/// shaping and geometry, independently of the save fitting helper; all field assertions remain.
pub(super) fn authored_text_dimensions(d: &Drawing) -> Drawing {
fn fit(d: &Drawing, t: &mut Text) {
use cadcraft_doc::HAlign;
if !matches!(t.halign, HAlign::Aligned | HAlign::Fit) {
return;
}
let Some(second) = t.align_pt else { return };
let distance = t.insert.xy().dist(second.xy());
if !distance.is_finite() || distance <= 1e-12 {
return;
}
t.rotation = t.insert.xy().angle_to(second.xy());
let style = d.text_style(&t.style).cloned().unwrap_or_default();
let font = cadcraft_render::style_font(&style);
let width = cadcraft_fonts::shape_line_dir(&font, &t.value, t.height, t.width_factor, t.oblique, Some(false)).width;
if width.is_finite() && width > 1e-12 {
if t.halign == HAlign::Aligned {
t.height *= distance / width;
} else {
t.width_factor *= distance / width;
}
}
}
fn store(d: &Drawing, entities: &mut EntityStore) {
for h in entities.handles() {
// Read-time measurements already have their own preservation contract.
if d.foreign.text_fits.contains_key(&h) {
continue;
}
entities.modify(h, |e| match &mut e.kind {
EntityKind::Text(t) => fit(d, t),
EntityKind::AttDef(a) => fit(d, &mut a.text),
EntityKind::Insert(i) => i.attribs.iter_mut().for_each(|a| fit(d, &mut a.text)),
_ => {}
});
}
}
let mut expected = d.clone();
store(d, &mut expected.model);
for layout in &mut expected.layouts {
store(d, &mut layout.entities);
}
for block in expected.blocks.values_mut() {
store(d, &mut std::sync::Arc::make_mut(block).entities);
}
expected
}
+2
View File
@@ -57,6 +57,8 @@ fn check_version_with(case: &str, original: &Drawing, expected: &Drawing, versio
}
fn check_version_using(case: &str, original: &Drawing, expected: &Drawing, version: Version, verify: impl Fn(&Drawing, &Drawing, &str)) {
let expected_dimensions = compare::authored_text_dimensions(expected);
let expected = &expected_dimensions;
cadcraft_io::dwg_worker::allow_in_process();
let options = SaveOptions { version: Some(version), binary: false };
let mut current = original.clone();
+2
View File
@@ -33,6 +33,8 @@ fn check_version(case: &str, original: &Drawing, expected: &Drawing, version: Ve
}
fn check_version_with(case: &str, original: &Drawing, expected: &Drawing, version: Version, extra: impl Fn(&Drawing, &Drawing, &str)) {
let expected_dimensions = compare::authored_text_dimensions(expected);
let expected = &expected_dimensions;
for binary in [false, true] {
let options = SaveOptions { version: Some(version), binary };
let mut current = original.clone();
+1 -1
View File
@@ -27,7 +27,7 @@ fn drawing() -> Drawing {
RawTag { code: 30, value: "3.75".into() },
RawTag { code: 330, value: target.hex() },
];
d.model.push(Entity::new(handle, EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags })));
d.model.push(Entity::new(handle, EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags, graphics: Vec::new() })));
d.model.push(Entity::new(target, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(5.0, 6.0, 7.0) })));
d
}
+1 -1
View File
@@ -19,7 +19,7 @@ fn user_linetypes_and_patterns_survive_dxf() {
let h = Hatch {
pattern: steps.name.clone(),
solid: false,
loops: vec![HatchLoop { vertices: square, outer: true, sources: Vec::new() }],
loops: vec![HatchLoop { vertices: square, outer: true, boundary_flags: None, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
+95
View File
@@ -0,0 +1,95 @@
//! Original synthetic geometry, style values and xdata, licensed with the repository.
//! The fixed fields follow Autodesk's 2010 DXF Reference, VISUALSTYLE, pp. 208-210:
//! https://images.autodesk.com/adsk/files/acad_dxf1.pdf
use cadcraft_doc::EntityKind;
use cadcraft_io::{SaveOptions, Version};
fn source(version: &str) -> String {
let mut text = format!(
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\n{version}\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nAPPID\n5\n10\n100\nAcDbSymbolTable\n70\n1\n\
0\nAPPID\n5\n11\n330\n10\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n2\nACAD\n70\n0\n0\nENDTAB\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n30\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n0\n20\n0\n30\n0\n11\n10\n21\n5\n31\n0\n0\nENDSEC\n\
0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_VISUALSTYLE\n350\n20\n\
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nSynthetic0\n350\n21\n3\nSynthetic1\n350\n22\n"
);
for index in 0..2 {
text.push_str(&format!(
"0\nVISUALSTYLE\n5\n{:X}\n330\n20\n100\nAcDbVisualStyle\n2\nSynthetic{index}\n\
70\n0\n71\n1\n72\n1\n73\n1\n90\n0\n40\n1.0\n41\n0.5\n63\n7\n\
74\n2\n91\n0\n64\n7\n65\n7\n75\n1\n175\n1\n42\n30.0\n92\n0\n66\n7\n43\n1.0\n\
76\n1\n77\n0\n78\n0\n67\n7\n79\n1\n170\n0\n171\n0\n290\n0\n174\n0\n93\n0\n44\n0.0\n173\n0\n291\n0\n\
1001\nACAD\n1000\nAcRTDxfName\n1000\nVISUALSTYLE\n",
0x21 + index
));
}
text.push_str("0\nENDSEC\n0\nEOF\n");
text
}
#[test]
fn legacy_visualstyles_are_reported_and_left_out_of_2007_dwg_only() {
cadcraft_io::dwg_worker::allow_in_process();
for from in ["AC1021", "AC1024"] {
let drawing = cadcraft_io::read_dxf(source(from).as_bytes()).unwrap();
let styles = || drawing.foreign.objects.iter().filter(|object| object.kind == "VISUALSTYLE").count();
assert_eq!(styles(), 2);
for version in [Version::R2007, Version::R2013] {
let options = SaveOptions { version: Some(version), binary: false };
let (bytes, report) = cadcraft_io::write_noted(&drawing, "styles.dwg", &options).unwrap();
let back = cadcraft_io::read(&bytes, "styles.dwg").unwrap();
assert!(back.model.iter().any(|entity| matches!(entity.kind, EntityKind::Line(_))));
let retained = back
.foreign
.objects
.iter()
.any(|object| object.kind == "VISUALSTYLE" && object.tags.iter().any(|tag| tag.code == 2 && tag.value.starts_with("Synthetic")));
if version == Version::R2007 {
assert_eq!(report.get("VISUALSTYLE"), Some(&styles()));
assert!(!retained);
} else {
assert!(!report.contains_key("VISUALSTYLE"));
assert!(retained);
}
let (dxf, report) = cadcraft_io::write_noted(&drawing, "styles.dxf", &options).unwrap();
assert!(report.is_empty());
let back = cadcraft_io::read_dxf(&dxf).unwrap();
assert_eq!(back.foreign.objects.iter().filter(|object| object.kind == "VISUALSTYLE").count(), styles());
}
assert_eq!(styles(), 2);
}
}
#[test]
fn orphaned_legacy_visualstyles_are_not_reported_as_compatibility_omissions() {
cadcraft_io::dwg_worker::allow_in_process();
let mut drawing = cadcraft_io::read_dxf(source("AC1021").as_bytes()).unwrap();
let foreign = std::sync::Arc::make_mut(&mut drawing.foreign);
let orphan = foreign.objects.iter_mut().find(|object| object.kind == "VISUALSTYLE").unwrap();
orphan.tags.iter_mut().find(|tag| tag.code == 330).unwrap().value = "FF".into();
let options = SaveOptions { version: Some(Version::R2007), binary: false };
let (bytes, report) = cadcraft_io::write_noted(&drawing, "styles.dwg", &options).unwrap();
let back = cadcraft_io::read(&bytes, "styles.dwg").unwrap();
assert!(back.model.iter().any(|entity| matches!(entity.kind, EntityKind::Line(_))));
assert_eq!(report.get("VISUALSTYLE"), Some(&1));
}
#[test]
fn newer_visualstyle_properties_are_kept_in_2007_dwg() {
cadcraft_io::dwg_worker::allow_in_process();
let document = acadrust::DxfReader::from_reader(std::io::Cursor::new(source("AC1027").into_bytes())).unwrap().read().unwrap();
let modern = acadrust::DxfWriter::new(&document).write_to_vec().unwrap();
let drawing = cadcraft_io::read_dxf(&modern).unwrap();
assert!(drawing.foreign.objects.iter().any(|object| object.kind == "VISUALSTYLE" && object.tags.iter().any(|tag| tag.code == 176)));
let options = SaveOptions { version: Some(Version::R2007), binary: false };
let (bytes, report) = cadcraft_io::write_noted(&drawing, "styles.dwg", &options).unwrap();
assert!(!report.contains_key("VISUALSTYLE"));
let back = cadcraft_io::read(&bytes, "styles.dwg").unwrap();
assert!(
back.foreign
.objects
.iter()
.any(|object| { object.kind == "VISUALSTYLE" && object.tags.iter().any(|tag| tag.code == 2 && tag.value.starts_with("Synthetic")) })
);
}
+22 -128
View File
@@ -3,7 +3,8 @@
//! rotation, width factor and obliquing; fonts whose licence bits forbid embedding, the stroke
//! font and the `text: "geometry"` option keep filled outlines.
//!
//! The fonts are tiny synthetic TrueType files built here (no font files in the repository).
//! The fonts are tiny synthetic TrueType files built by the shared test helper in
//! `crates/fonts/tests/support/sfnt.rs` (no font files in the repository).
use cadcraft_doc::{Common, Drawing, EntityKind, Space, Text, TextStyle, Viewport};
use cadcraft_geom::{Vec2, Vec3};
@@ -15,137 +16,30 @@ mod pdf_read;
use pdf_read::Doc;
// The synthetic TrueType file: the fonts layer's test-only helper, inlined rather than published
// or depended on.
#[path = "../../fonts/tests/support/sfnt.rs"]
mod sfnt;
// ---------- a minimal TrueType font: .notdef, "A" (triangle), "B" (square) ----------
fn be16(v: &mut Vec<u8>, x: u16) {
v.extend_from_slice(&x.to_be_bytes());
}
fn be32(v: &mut Vec<u8>, x: u32) {
v.extend_from_slice(&x.to_be_bytes());
}
/// A simple glyph: one closed contour of on-curve points.
fn simple_glyph(pts: &[(i16, i16)]) -> Vec<u8> {
let mut g = Vec::new();
let xs: Vec<i16> = pts.iter().map(|p| p.0).collect();
let ys: Vec<i16> = pts.iter().map(|p| p.1).collect();
be16(&mut g, 1);
for v in [*xs.iter().min().unwrap(), *ys.iter().min().unwrap(), *xs.iter().max().unwrap(), *ys.iter().max().unwrap()] {
be16(&mut g, v as u16);
}
be16(&mut g, pts.len() as u16 - 1);
be16(&mut g, 0);
g.extend(std::iter::repeat_n(1u8, pts.len()));
let (mut px, mut py) = (0i16, 0i16);
for (x, _) in pts {
be16(&mut g, (x - px) as u16);
px = *x;
}
for (_, y) in pts {
be16(&mut g, (y - py) as u16);
py = *y;
}
while g.len() % 4 != 0 {
g.push(0);
}
g
}
/// A TrueType font with glyphs .notdef (empty), A and B, and OS/2 `fsType`. `hmtx` holds
/// `metrics` of the three metrics `hhea` declares.
/// `metrics` of the three metrics `hhea` declares: fewer is a font the writer cannot subset.
fn test_font(fs_type: u16, metrics: usize) -> Vec<u8> {
let glyphs = [Vec::new(), simple_glyph(&[(50, 0), (550, 0), (300, 700)]), simple_glyph(&[(50, 0), (550, 0), (550, 700), (50, 700)])];
let mut glyf = Vec::new();
let mut loca = Vec::new();
for g in &glyphs {
be32(&mut loca, glyf.len() as u32);
glyf.extend_from_slice(g);
}
be32(&mut loca, glyf.len() as u32);
let mut head = Vec::new();
be32(&mut head, 0x0001_0000);
be32(&mut head, 0x0001_0000);
be32(&mut head, 0);
be32(&mut head, 0x5F0F_3CF5);
be16(&mut head, 0);
be16(&mut head, 1000);
head.extend_from_slice(&[0; 16]);
for v in [0i16, 0, 600, 700] {
be16(&mut head, v as u16);
}
for v in [0u16, 8, 2, 1, 0] {
be16(&mut head, v);
}
let mut hhea = Vec::new();
be32(&mut hhea, 0x0001_0000);
for v in [800i16, -200, 0, 600, 0, 0, 600, 1, 0, 0, 0, 0, 0, 0, 0] {
be16(&mut hhea, v as u16);
}
be16(&mut hhea, 3);
let mut maxp = Vec::new();
be32(&mut maxp, 0x0001_0000);
for v in [3u16, 4, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] {
be16(&mut maxp, v);
}
let mut hmtx = Vec::new();
for _ in 0..metrics {
be16(&mut hmtx, 600);
be16(&mut hmtx, 50);
}
// cmap: format 4, 'A'..'B' → 1..2.
let mut sub = Vec::new();
let segs: [(u16, u16, u16); 2] = [(0x41, 0x42, 1u16.wrapping_sub(0x41)), (0xFFFF, 0xFFFF, 1)];
be16(&mut sub, 4);
be16(&mut sub, (16 + segs.len() * 8) as u16);
be16(&mut sub, 0);
be16(&mut sub, (segs.len() * 2) as u16);
for v in [4u16, 1, 0] {
be16(&mut sub, v);
}
for s in segs {
be16(&mut sub, s.1);
}
be16(&mut sub, 0);
for s in segs {
be16(&mut sub, s.0);
}
for s in segs {
be16(&mut sub, s.2);
}
for _ in segs {
be16(&mut sub, 0);
}
let mut cmap = Vec::new();
for v in [0u16, 1, 3, 1] {
be16(&mut cmap, v);
}
be32(&mut cmap, 12);
cmap.extend_from_slice(&sub);
let mut os2 = vec![0u8; 78];
os2[8..10].copy_from_slice(&fs_type.to_be_bytes());
let mut tables: Vec<(&[u8; 4], Vec<u8>)> =
vec![(b"OS/2", os2), (b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)];
tables.sort_by_key(|t| *t.0);
let mut out = Vec::new();
be32(&mut out, 0x0001_0000);
for v in [tables.len() as u16, 128, 3, tables.len() as u16 * 16 - 128] {
be16(&mut out, v);
}
let mut off = 12 + 16 * tables.len();
for (t, d) in &tables {
out.extend_from_slice(*t);
be32(&mut out, 0);
be32(&mut out, off as u32);
be32(&mut out, d.len() as u32);
off += d.len().div_ceil(4) * 4;
}
for (_, d) in &tables {
out.extend_from_slice(d);
while out.len() % 4 != 0 {
out.push(0);
}
}
out
sfnt::bytes(&sfnt::Sfnt {
// "A" is a triangle and "B" a square: one contour each.
glyphs: &[
sfnt::notdef(),
sfnt::glyph(&[vec![(50, 0), (550, 0), (300, 700)]]),
sfnt::glyph(&[vec![(50, 0), (550, 0), (550, 700), (50, 700)]]),
],
cmap: &[(0x41, 0x42, 1 - 0x41)], // "A".."B" → glyphs 1..2
advance: 600,
lsb: 50,
metrics,
fs_type,
ink_box: [0, 0, 600, 700],
})
}
/// Register the test fonts once: an embeddable one, one with a restricted licence, and one
+17
View File
@@ -40,6 +40,23 @@ pub(crate) fn sub_ctx<'a>(ctx: &Ctx<'a>, e: &Entity, m: Mat3) -> Ctx<'a> {
}
}
/// A proxy entity draws its proxy graphics as AutoCAD does with PROXYSHOW 1, like block contents:
/// layer 0 and ByBlock in the picture stand for the proxy's own layer and properties. Other
/// unknown records draw nothing. `own` is the proxy's transparency without its locked-layer fade,
/// as for a block reference.
pub(crate) fn proxy(b: &mut Builder, ctx: &Ctx, e: &Entity, u: &cadcraft_doc::Unknown, own: u8) {
if u.graphics.is_empty() || ctx.depth >= cadcraft_doc::MAX_BLOCK_DEPTH {
return;
}
let sub = Ctx { block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, Mat3::IDENTITY) };
for g in &u.graphics {
if !b.expand() {
break;
}
entity(b, &sub, g);
}
}
/// `own` is the reference's resolved transparency without its locked-layer fade: what ByBlock
/// children inherit (a child fades only for its own layer).
pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert, rgb: Ink, own: u8) {

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