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
Tanish Manku 8d3236c5a3 Merge pull request #3350 from storytold/stack/r2
Land #2763, #2905, #2918, #3233, #2804: tilted 2D polylines, mirrored heights on save, kept APPIDs, plot layout flags, Generate Boundary
2026-11-20 17:48:52 -07:00
Tanish Manku f4d4a6e4e1 DXF read: a thick polyline drawn as seen from above keeps the side of Z it extruded toward 2026-11-20 17:37:24 -07:00
Tanish Manku 80e9a97164 Merge main 2026-11-20 17:20:59 -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 97dccaf9e7 Merge pull request #3348 from storytold/docs/parity-batch-1120
Parity docs: batch for 2026-11-19 and 2026-11-20, alpha-blocker marks follow the six-row gate
2026-11-20 16:54:58 -07:00
Tanish Manku b39170aded HATCHGENERATEBOUNDARY: a mirrored hatch's boundary goes to its world height; the command is classified as using no files 2026-11-20 16:45:17 -07:00
Tanish Manku 20d489f059 ROADMAP: TRIM/EXTEND depth landed, drop it from Upcoming 2026-11-20 16:43:29 -07:00
Tanish Manku 318d8d9de1 Plot layout flag tests that save DWG opt in to the in-process bridge 2026-11-20 16:40:30 -07:00
Tanish Manku 4076a71dee Registered applications alone note no file version; the APPID tests that save DWG opt in to the in-process bridge 2026-11-20 16:40:26 -07:00
Tanish Manku e5a7d38a67 Merge #2804: Generate Boundary in a hatch's right-click menu (#2801) 2026-11-20 16:37:35 -07:00
Tanish Manku 46053d43c1 Merge #3233: save the plot layout flags as read (#3227) 2026-11-20 16:37:17 -07:00
Tanish Manku 6aa64fb5ae Merge #2918: a file's registered applications are kept when no xdata names them 2026-11-20 16:34:22 -07:00
Tanish Manku 543285778b Merge #2905: mirrored objects keep their world height and extrusion side 2026-11-20 16:34:00 -07:00
Tanish Manku fed8b0f4e4 Merge #2763: draw a tilted 2D POLYLINE as seen from above, like LWPOLYLINE 2026-11-20 16:33:50 -07:00
Tanish Manku 50baa3cfae Parity docs: batch for the merges of 2026-11-19 and 2026-11-20, alpha-blocker marks follow the six-row gate 2026-11-20 16:32:11 -07:00
Tanish Manku ef6df4dffa Merge pull request #3347 from storytold/stack/u8
Land #3313, #3300, #3316, #1873: arrowheads in DIMSTYLE, single-instance tests, Thai in the MTEXT editor, DIMPOST on angular dimensions
2026-11-20 16:31:01 -07:00
Tanish Manku 97c5670a0a Merge pull request #3346 from storytold/stack/s8
Land #2904, #3302, #3341, #1728, #2882, #1687, #3234: files other CAD programs refuse, and data lost on save
2026-11-20 16:30:51 -07:00
Tanish Manku ed294b3fb3 Single-instance tests: the skip note goes straight to stderr, where a passing test still shows it 2026-11-20 16:16:59 -07:00
Tanish Manku 40ddd7baca DWG bridge: an R2000 DWG keeps constraint groups and proxies as its reader takes them
The writer told the bridge from a DXF file by comparing the declared and the
target version, which are both R2000 for an R2000 DWG. Kept constraint groups
of a 2013+ drawing were then put in the old node order although the bridge
reads them as the version they came from, and kept proxies took the pre-2007
DXF layout. The bridge says so itself now. The render settings test module is
skipped where acadrust isn't built.
2026-11-20 16:12:50 -07:00
Tanish Manku ea4a59b662 Save warning: a DXF before 2013 that leaves out solids points to 2013 and later
Since #2882 a DXF of 2010 or earlier leaves out solids whose geometry only
the data store holds, and the interactive QSAVE asks before it does. The
warning's hint still said DXF 2010 and earlier keep them, which is the
version that loses them. The hint now depends on the version the file is
saved in: 2013 and later keep such solids, and the proxies a DXF before
2007 leaves out as well. Also rustfmt of the merged finish signature.
2026-11-20 14:23:07 -07:00
Tanish Manku 9e645ba17a Merge #3234: DXF: write kept proxies in the layout of the version written (#3229)
Conflicts with #2882 resolved: a DXF's loss report counts both what #2882
leaves out (solids whose ACIS geometry the version has no place for, in
either direction of 2013) and what #3234 leaves out before 2007 (proxies
whose strings it can't hold, with what goes with them), each named with its
own reason, for SAVE/SAVEAS, document.bytes, EXPORT, -WBLOCK and the
interactive QSAVE question. dxf_raw::finish takes both flags.
2026-11-20 14:22:04 -07:00
Tanish Manku 8da04230af Merge #1687: DXF/DWG save: kept render settings take the declared version's class-version form
Conflicts with main resolved: the source form is main's Foreign::version
(#2471), recorded at read time for the same reason, instead of the PR's own
Foreign::acadver. The conversion goes to the version the text is read as,
as #1728's constraint groups do: a DXF's own version, and for the DWG
bridge the version the kept objects came from, which craft-dwg's
encode_kept_noted declares, so there they stay as read. The DWG test opts
in to in-process DWG.
2026-11-20 14:20:07 -07:00
Tanish Manku af5c658a4b Merge #2882: Solids: no empty modeler records before 2013; list ACIS 4.0 SAT a DWG can't keep (#2334)
# Conflicts:
#	crates/io/src/dxf_write/sections.rs
2026-11-20 14:19:21 -07:00
Tanish Manku 5d76e47342 io tests: the constraint group DWG test opts in to in-process DWG and skips where acadrust isn't built
nextest runs each test in its own process, and the opt-in is process-wide,
so a DWG test calls it itself. acadrust is a dev-dependency only where
craft-dwg builds its native bridge (#2526), as the other DWG test files say.
2026-11-20 14:18:55 -07:00
Tanish Manku 3caad662a4 Single-instance length test uses its own folder; the angular DIMPOST DWG test builds on main and opts into the in-process DWG path 2026-11-20 14:18:52 -07:00
Tanish Manku 615fee3e12 Merge #1728: DWG: constraint groups keep their nodes 2026-11-20 14:18:36 -07:00
Tanish Manku 92fe0a655d io: the kept-data doc comment goes back on dxf_raw, not dwg_hatch 2026-11-20 14:18:33 -07:00
Tanish Manku a62dd047a4 Merge #1873: dim: apply the style's DIMPOST to angular dimensions (#1653) 2026-11-20 14:18:24 -07:00
Tanish Manku b4c325a36b Merge #3316: MTEXT editor: show Thai (and other drawing scripts) instead of boxes 2026-11-20 14:18:22 -07:00
Tanish Manku 1ad4fc7c91 Merge #3341: DWG: read a hatch's elliptic boundary edge angles as degrees (#3332) 2026-11-20 14:18:21 -07:00
Tanish Manku 8178a68f3e Merge #3300: Windows single-instance tests: short socket paths, skip when AF_UNIX can't bind (#3283) 2026-11-20 14:18:20 -07:00
Tanish Manku 29a22f7955 Save: a kept dimension block with another name keeps its record and description
A block with a name other than *D that an unedited dimension was read with
is written with the dimension blocks (#3302). Its BLOCK_RECORD lost its
insertion units and explodability there, and the BLOCK its description.
When that block is empty, the picture is regenerated in world coordinates,
so the block now goes at the origin rather than at the read base point,
which shifted the picture.

The new DWG-saving test of #3302 opts in to in-process DWG conversion.
2026-11-20 14:18:18 -07:00
Tanish Manku 48f0a590ab Merge #3313: Preserve per-end Closed filled arrowheads in DIMSTYLE 2026-11-20 14:18:18 -07:00
Tanish Manku 80f2b6838d Merge #3302: Save: an unedited dimension keeps its read block whatever the block's name (#3299) 2026-11-20 14:14:27 -07:00
Tanish Manku 70e55f21cc Merge #2904: DXF: a solid or gradient hatch no longer makes AutoCAD refuse the file 2026-11-20 14:13:38 -07:00
Tanish Manku d3af2d5077 Merge pull request #3345 from storytold/feat/text-edit-in-place
Double-click edits TEXT, attribute definitions and dimension text in place (#842)
2026-11-20 12:07:44 -07:00
Tanish Manku afcf5d3461 Start each in-place text box with no undo history
All boxes share one text field, so Ctrl+Z in a new box could bring back
the text typed into the last one; its undo history is cleared when a box
opens.
2026-11-20 11:45:44 -07:00
Tanish Manku 7ecf836de7 Keep an in-place text draft with the drawing it was typed in
The draft was keyed by the object's handle only, and handles repeat across
drawings; it is now also bound to the drawing's id, so it is never shown
or submitted for another drawing's object.
2026-11-20 11:45:44 -07:00
Tanish Manku 4b97a1a25e Size the in-place box of annotative text and dimensions as drawn
At a non-unit annotation scale an annotative TEXT, attribute definition or
dimension is drawn scaled; the editor box now takes its height, position
and extents from that scaled object, as the renderer and EXPLODE do.
2026-11-20 11:45:43 -07:00
Tanish Manku 4683023d94 Test the command line's IME at TEXT's prompt, which has no in-place editor
TEXTEDIT on a TEXT now edits it in place, so the IME goes into that box
(tested in text_double_click.rs); the command line's own IME handling is
tested where it still collects the text: TEXT's Enter text prompt.
2026-11-20 11:45:43 -07:00
Tanish Manku 44e0e431ee Make the in-place text box cover the text as drawn
The one-line editor was narrower than the text it edits: an egui area
caps its width, and a centred or right-justified text's box started at
its insertion point. TEXTEDIT now gives the editor the drawn text's
extents (TextEditor::extents, from the renderer's text placement), and
the box starts at the drawn left edge, is at least as wide and as tall as
the drawn text, and still grows as more is typed.
2026-11-20 10:56:18 -07:00
Tanish Mankuandsimanov 0b454bb536 Test that a double-clicked MTEXT is edited in its in-place editor
Double-clicking an MTEXT opens the editor with its contents; what is typed
is kept with Ctrl+Enter. Carried from #1425.

Co-authored-by: simanov <asimfali@mail.ru>
2026-11-20 10:40:08 -07:00
Tanish MankuandLuminati 9f2cd4ca78 Edit TEXT, attribute definitions and dimensions in place on a double-click
Double-clicking single-line text, an attribute definition or a dimension
(no command running) now opens a one-line text box over it on the canvas,
as AutoCAD does, instead of asking at the command line (#842). Enter or a
click outside keeps the text, Esc cancels, and an emptied box keeps the old
text. A dimension's box shows its text override, or <> for the measured
value, with the measured value beside it; emptying it or typing <> alone
gives the measurement back.

The box answers TEXTEDIT's prompt, so the edit is one undo step and
scripts, the command line and engine.execute behave as before. The engine
describes what to edit through Interactive::text_editor, TextEditor and
EditorKind (MText, Line, Dimension), following the design in #2320.

Co-authored-by: Luminati <347279204+luminatiguy@users.noreply.github.com>
2026-11-20 10:40:07 -07:00
Tanish Manku 1d92bb275c Merge pull request #3343 from storytold/fix/open-off-ui-thread
OPEN with a typed path opens that file, read in the background
2026-11-20 10:11:17 -07: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
Tanish Manku c73b1487ea Open a typed OPEN path in the background, as File > Open does
OPEN followed by a file name, or the JSON form with only a path, typed
at the command line and entered with Enter now reads the file on the
background reader with the Opening card, instead of opening the file
picker and dropping the path (or, for the JSON form, reading it on the
UI thread). Programmatic calls (control channel, MCP, scripts, LISP)
still open synchronously and return their result.
2026-11-20 09:47:34 -07:00
Tanish Manku fafe5f128c Merge pull request #3342 from storytold/stack/r1
Stack r1: ten long-waiting fixes (#1280, #1292, #1505, #1605, #1740, #1741, #1815, #2261, #2745, #2870)
2026-11-20 09:29:53 -07:00
Tanish Manku 9c53d527f8 Stack r1: #1815: the Vietnamese interface font is looked for among the discovered fonts too, as the interface font is 2026-11-20 09:06:56 -07:00
Tanish Manku 7ec88f7e27 Stack r1: #1815: with only FONTCONFIG_PATH set, its fonts.conf is the configuration, then /etc/fonts as in fontconfig 2026-11-20 09:06:56 -07:00
Tanish Manku 7189295bc3 Stack r1: #1280: each IMAGE keeps its own IMAGEDEF when a repeated handle is reassigned 2026-11-20 09:06:55 -07:00
Tanish Manku 0191a5fa61 Stack r1: #1292: a -PAN displacement is measured in the current UCS, so 0,0 in a moved UCS does not pan 2026-11-20 09:00:47 -07:00
Tanish Manku a7808fdc9d Stack r1: #1292: realtime PAN moves only the view, so a drag frame no longer rebuilds the drawing's geometry 2026-11-20 09:00:46 -07:00
lforgiarini 2dc136781b fix(io): read a DWG hatch's elliptic boundary edge angles as degrees (#3332)
The DWG decoder writes the start and end angles of an elliptic hatch edge in radians; DXF
keeps degrees and the DXF reader reads degrees. A circle stored as an elliptic edge (0 to
2π) became an arc of 6.28 degrees, and the hatch covered the hole it should leave open.

The decoded DXF is passed through dwg_hatch::elliptic_edge_degrees before it is read.
2026-11-20 16:36:43 +01:00
Tanish Manku be0f2f7083 Stack r1: #1505: the locked-layer fade is worked out in its own function (clippy cognitive complexity) 2026-11-20 08:33:26 -07:00
Tanish Manku 5e697dde2b Merge #2870: Layers palette: list layers by name (fixes #2858) 2026-11-20 08:18:35 -07:00
Tanish Manku 2c8b8f438c Stack r1: #2745: the portable write probe writes a byte; the README names the profile's app.ron to copy 2026-11-20 08:18:35 -07:00
Tanish Manku 8ea4c908e2 Merge #2745: Windows: keep portable settings in CADCraftData and ship portable.txt
# Conflicts:
#	apps/cadcraft/src/main.rs
2026-11-20 08:17:57 -07:00
Tanish Manku 410c55aaee Stack r1: #2261: a pinned cap height below 1 unit is dropped, as the font's own never goes below 1 2026-11-20 08:16:34 -07:00
Tanish Manku 75cdbd49b4 Merge #2261: fonts: a substitute's text scales by the cap height the installation pins for it, not the substitute's own 2026-11-20 08:16:17 -07:00
Tanish Manku c4c632d1f0 Stack r1: #1815: the CJK, Arabic and Japanese fonts skip a candidate that cannot be read 2026-11-20 08:16:17 -07:00
Tanish Manku 120d9dd1a0 Merge #1815: Find installed fonts where fontconfig looks: XDG dirs, fontconfig <dir> entries, Flatpak host fonts 2026-11-20 08:15:47 -07:00
Tanish Manku 2c8a6edf9d Stack r1: #1741: a cloud made from an object after Reverse direction keeps its RevcloudProps xdata 2026-11-20 08:15:44 -07:00
Tanish Manku dbe34ad3bc Merge #1741: REVCLOUD: ask maximum arc length and Reverse direction for Object (#1714)
# Conflicts:
#	crates/engine/src/cmd/draw2/revcloud.rs
#	crates/engine/src/cmd/draw2/tests.rs
2026-11-20 08:13:15 -07:00
Tanish Manku 1ff6241ecb Merge #1740: REVCLOUD: the Object option accepts an entity name (#1713) 2026-11-20 08:12:36 -07:00
Tanish Manku e1f87447cb Merge #1605: Write RevcloudProps xdata on revision clouds 2026-11-20 08:12:36 -07:00
Tanish Manku 01d6eca913 Merge #1505: Fade objects on locked layers on screen (LAYLOCKFADECTL) 2026-11-20 08:05:15 -07:00
Tanish Manku 816bd9591c Stack r1: #1292: a realtime PAN drag pans only the tile it started on 2026-11-20 08:05:10 -07:00
Tanish Manku aab42ef9df Stack r1: #1292: realtime PAN follows a twisted view; -PAN is on the file-access lists 2026-11-20 07:58:43 -07:00
Tanish Manku a0b29c0a11 Merge #1292: PAN pans in realtime by dragging; -PAN asks for two points
# Conflicts:
#	crates/ui-egui/src/canvas.rs
2026-11-20 07:38:31 -07:00
Tanish Manku fae1d05994 Merge #1280: io: a handle repeated across ENTITIES sections keeps both entities
# Conflicts:
#	crates/io/src/dxf_read.rs
2026-11-20 07:37:44 -07:00
Tanish Manku 1c5e4f41f5 Merge pull request #3338 from storytold/land/3228
Land #3228: craft-libs pins to 453b0da782; DWG-saving tests opt in to in-process conversion
2026-11-20 07:30:29 -07:00
Tanish Manku 2cc0100d70 The CLI's run names both ways to set up DWG conversion 2026-11-20 07:06:06 -07:00
Tanish Manku db66a8cd95 One more layer-state DWG test opts in; the CLI's run documents that it needs a DWG worker
Found by running every test of the io, engine, CLI, UI and MCP crates in its
own process, as CI does: no other test needs the call.
2026-11-20 06:45:34 -07:00
Tanish Manku 8152c9e71b The layer-state DWG tests allow in-process conversion too 2026-11-20 06:12:22 -07:00
Tanish Manku d02dc3e91e Two tests that save DWG allow in-process conversion
With the craft-libs bump a DWG is converted by a worker unless the process
opts in. The UCS round-trip test and the SETVAR save test write their own
drawings as DWG and now opt in themselves; the SETVAR one passed only when
another test in the same binary had opted in first.
2026-11-20 06:11:09 -07:00
Tanish Manku 184571d17b Merge remote-tracking branch 'origin/main' into land/3228 2026-11-20 06:11:09 -07:00
Tanish Manku 3b0f88861b Merge #3228 into land/3228 2026-11-20 05:02:49 -07:00
NateMerida 5c00b66572 Test Thai in both interface families (command line, layer names, FIND results)
The provider is asked per family; FIND shows matching drawing text in
the monospace family, the command line and palettes in the proportional
one. Thai typed at the command line (#2949) goes through the same path.
2026-11-20 11:50:21 +07:00
NateMerida 0e0344be94 MTEXT editor: show Thai (and other drawing scripts) instead of boxes
The in-place editor lays text out with the interface fonts, which have no
Thai, so a Thai MTEXT the canvas draws correctly showed as boxes while
editing (and in the command-line prompt, layout tabs and layer names).

An egui font provider now answers a character no interface font has with
the face drawing text takes for it (cadcraft_fonts::ttf::fallback_for),
sharing the font table's bytes. A face whose letters are small for its em
(Cordia New, Angsana New) is scaled up to the interface's x-height, and
its glyphs sit on the interface baseline. theme::install_fonts is not
changed.

Face::glyph_height measures a glyph in ems for that scale.
2026-11-20 10:26:18 +07:00
0bnoxide 3ec1e1b210 fix(dimstyle): preserve per-end closed filled arrowheads 2026-11-19 19:56:28 -07:00
martin-mirantes 3165d2735e io: a kept dimension block with another name keeps its base point and flags (#3299) 2026-11-20 00:52:01 +00:00
martin-mirantes d04d67f8c3 io: an unedited dimension keeps its read block whatever the block's name (#3299)
Other programs name a dimension's picture block as they like (DXF group 2
may name any block). dim_block_plan only reused blocks named *D, so such a
dimension was regenerated into a fresh *D block on save, its text changed,
and the read block stayed in the file unreferenced. The plan now reuses the
block an unedited dimension names, whatever its name, and leaves it out of
the ordinary blocks when nothing else uses it.
2026-11-20 00:36:59 +00:00
sedoll 67cc9a28c3 Windows single-instance tests: short socket paths, skip when AF_UNIX can't bind (#3283)
The two socket tests put their socket at <temp>\cadcraft-single-instance-<pid>-<test>\instance-test.sock,
about 58 bytes on top of %TEMP%. uds_windows allows 107 bytes, so a long %TEMP% made
UnixListener::bind(...).unwrap() panic and left launches_at_once_open_one_window with no window.

- Shorten the folder and socket names to cc-si-<pid>-<test>\t.sock (about 33 bytes).
- Skip a test with a note when no socket can be bound at its path, instead of panicking.
- Add a test that the test socket path stays within 40 bytes of %TEMP%.
2026-11-20 09:27:25 +09:00
dotCooCoo ceb28303f5 Merge main into chore/craft-libs-3af2280 2026-11-19 15:41:14 -08: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
Ray 73d1b65f3e DXF: write kept proxies in the layout of the version written (#3229)
Kept proxy records were written with the groups they were read with. The
DWG bridge brings them in the DWG's own version's layout, so a 2010
drawing saved as an R2000 DXF carried 161/162 groups that R2000 readers
reject (ODA, BricsCAD: Out of range), and a 2018 DXF carried 95 instead
of 71/97.

DXF output now rewrites each proxy's groups after its AcDbProxy subclass
marker into the target version's form: 95 or 71/97 for the drawing
format, 92/160 graphics size, 93/161 data size, 96/162 string stream
size (none before 2007). The DWG bridge is left as it was.

From 2007 a proxy keeps its strings in a separate stream (group 96, then
162). DXF before 2007 has no such group, so converting dropped the stream's
size while keeping its bytes, and readers took them as object data. Such a
proxy is now left out of an R2000 or R2004 DXF with its dictionary entry, as
proxies of unwritten classes are, and SAVEAS and document.bytes say so on the
command line and in notSaved.

loss_on_save now lists the proxies whose strings a DXF before 2007 can't hold,
so an interactive QSAVE asks before replacing the file; the warning points to
DXF 2007 and later when proxies are what would go. The proxy report test also

The pre-save hint checked for a .dxf extension, but a save picks the
format with Format::from_path, which treats a name without one as DXF.
Such a file got "DXF keeps them" instead of the version advice.

EXPORT writes a DXF at the drawing's own version too, so before 2007 it now reports
the proxies it leaves out (echo and notSaved), as a save does.

What a pre-2007 DXF loses is now counted by the writer itself
(cadcraft_io::proxies_lost, installed in the apps with set_proxies_lost): the
drawing is written as 2007 and as the target version and the two compared.
A proxy that no version writes (its class is not written, or no written block
holds it) is no longer reported with "save as 2007 or later", and the objects
that go with a dropped proxy (its extension dictionary and the XRECORDs in it)
are reported too. The DXF writer's finish returns the foreign objects it kept
for this.

The count reads the drawing the file is written from: the committed drawing
during a reference edit (the working copy is not counted again), the drawing
EXPORT writes while the Block Editor is open (for the SAT-text report too), and
the drawing -WBLOCK writes, which now reports a pre-2007 DXF's losses as well.
2026-11-18 17:33:51 -07:00
Davit Matchakhelidze 6fb27ffa9e Merge origin/main into ka-update-2026-11-07 2026-11-18 15:06:41 +04:00
dotCooCoo 4d2381a5ca Merge main into chore/craft-libs-3af2280 2026-11-17 20:17:59 -08: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
Ray dab89a38ed Layouts: keep an unchanged standard plot scale (#3227)
A layout read with a standard scale other than 1:1 (flags 176, group 75 = 25,
scale 0.02 for 1:50) lost plot layout flag 16 and its standard-scale choice on
save, because only scaled to fit and 1:1 counted as standard. The page now
keeps the file's group 75 with the scale it was read with; while the scale is
unchanged, saving writes that choice and keeps flag 16.
2026-11-17 12:33:43 -07:00
dotCooCoo ef12e7a9e2 Dependencies: take craft-libs main at 453b0da782
Every craft-libs git dependency and patch entry moves from be0b1e6552 to
craft-libs main at 453b0da782. Cargo.lock changes only the revision of
each craft-libs package.
2026-11-16 21:02:49 -08:00
Cody VogtandClaude Opus 5.5 3c956c4ccf DWG: kept constraint groups follow the version the bridge's DXF is read as
Since main's craft-dwg cutover, cadcraft passes the drawing's original file
version to encode_kept_noted, which declares the bridge's R2000 text as that
version when it is newer. Kept constraint groups are in that version's form as
read, so for the bridge they stay as read; reordering them for R2000 put each
node's status where the newer reader doesn't look. A DXF of another version is
still reordered for its own version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:31:56 -06:00
Ray 3ee12a8c62 Layouts: save the plot layout flags as read (#3227)
The DXF writer, which also feeds the DWG bridge, built the layout's plot
flags (AcDbPlotSettings group 70) from the bits CADCraft models and always
set 512 (plot paper space last) and 32 (plot with plot styles), plus 16
for a standard scale. A layout read with flags 0 came back as 560.

The page setup now keeps the flags as read; saving sets or clears only
the bits the page models (2, 4, 128, and 16 when the scale decides it).
Page setups made in CADCraft keep the old defaults.
2026-11-16 21:18:35 -07:00
Cody VogtandClaude Opus 5.5 b8f60e1e60 Tests: the constraint group test's Tag comes from craft_dxf, as main's DXF crate now is
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:05:45 -06:00
Cody VogtandClaude Opus 5.5 984596fead Merge storytold/cadcraft main into fix/dwg-constraint-group
crates/dwg is gone from main (the bridge is craft-dwg in storytold/craft-libs);
its part of this branch was #1725's, already in craft-dwg. sections.rs keeps
this PR's constraint_node_order after main's new finish() signature; the
dynblock_read test and io manifest are main's (#1725's test already landed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:59:44 -06:00
dotCooCoo e9638efc69 Dependencies: take craft-libs main at be0b1e6552
Every craft-libs git dependency moves from 3af2280ee3 to craft-libs main
at be0b1e655229e34f1ad263ef3d2170e46449c39b, which includes
storytold/craft-libs#1580: DWG fields from a drawing saved before DWG
2007 keep their format when it is saved as DWG 2007 or later.
Cargo.lock adds craft-dds, which craft-image-codecs now uses.
2026-11-16 15:55:50 -08:00
dotCooCoo d71fb54b39 Tests: enable in-process DWG conversion after each test's use items
Moves the allow_in_process call below the local use items in ten tests, matching the order every other function body in these files uses. Behavior does not change.
2026-11-16 13:33:37 -08:00
dotCooCoo f81c52b979 Dependencies: take craft-libs main at 3af2280ee3
Every craft-libs git dependency (Cargo.toml, its [patch.crates-io]
entries and apps/cadcraft-web/Cargo.toml) moves from eleven different
revisions to craft-libs main at 3af2280ee3434a2c860012df2f440652621c2c81.
Cargo.lock keeps one copy of each craft-libs crate and adds harfrust
0.13.3 and read-fonts 0.43.3, which craft-font-catalog now needs.

craft-dwg at this revision refuses to convert DWG when no worker process
is configured (storytold/craft-libs#1345). The app and the CLI configure
one at startup and are unaffected. The tests that read or write DWG in
their own process now call cadcraft_io::dwg_worker::allow_in_process(),
which cadcraft-io re-exports. dwg_worker.rs now checks that a worker
that cannot start is an error instead of a fallback to this process.
2026-11-16 12:49:47 -08: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
midasmatterhorn 4d1d85d298 fonts: say whose cap height CADCRAFT_CAP_HEIGHT takes 2026-11-14 17:13:41 +03:00
lorie-capella f5e98c3cb1 Merge main and retain portable settings and macOS sheets 2026-11-13 05:16:34 -05:00
midasmatterhorn 014ecbc7dc Merge remote-tracking branch 'upstream/main' into fix/issue-939-dxf-cross-section-handles
# Conflicts:
#	crates/io/src/dxf_read.rs
#	crates/io/src/dxf_read/document.rs
2026-11-12 23:42:41 +03:00
Walter Haslbeck 5869cf91f9 Merge remote-tracking branch 'origin/main' into fix/tilted-2d-polyline 2026-11-12 07:35:17 +01: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
2ez4gcxandClaude Opus 5.5 8e2aa822f7 Merge main into fix/dxf-mirrored-heights
Brings the branch up to main 6d744887, which has #2954's fix for
mtext::tests::strips_formatting, so the gate runs on a main that passes.
No conflicts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:21:46 +07: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
Walter Haslbeck a34cf69439 Merge remote-tracking branch 'origin/main' into fix/tilted-2d-polyline 2026-11-09 07:21:14 +01:00
2ez4gcxandClaude Opus 5.5 6ec0f2400a DXF test: the same objects facing up keep their height and thickness
The mirrored-objects test only had objects whose normal is 0,0,-1, so a
writer that flips the elevation and thickness of every object passed it.
It now reads the same nine objects with no normal and with 0,0,1 as
well: those keep +5 and +2 through a save, and their LINEs keep 39 = 2.0
with no 230.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 09:28:55 +07:00
assamaralandClaude Opus 5.5 203865064a refactor(engine): name report_acis_dropped; put has_sat_text's doc back
The report also covers data-store solids before 2013. The SAT text encoding
applies to every DXF before 2013, so say that in the comments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 18:57:50 -03:00
Filippo ReimerandClaude Opus 5.5 e56571eafc Merge origin/main into fix/layer-palette-sort-2858
main's Properties palette tests (#2444) added a `painted_texts` helper next
to this PR's; this PR's helper, which also returns each text's top edge, is
now `painted_texts_at`. The layer list test checks that the combo above the
list shows "0" before comparing the list rows, instead of dropping repeated
names, so a missing "0" list row would fail it (CodeRabbit nitpick).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 18:06:29 +01:00
mkzungandClaude Opus 5.5 18effe68b4 DXF/DWG: the registered applications test counts the records
The test only checked that an `Other_App` record was there, so a second record for the same
application would have passed. It now asks for exactly one, and a second test has a line's xdata
name the application as `OTHER_APP` beside the registered `Other_App`: DXF and DWG, twice, keep
the xdata and one APPID record. With `add_appids` keyed by the name as written instead of
case-insensitively, that test fails (2 records).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01H43qQA41CJLauqXnPgBQ7r
2026-11-08 14:17:58 +00:00
SoldierPePe 410bdc733f i18n(ar): test that Stretch, Trim and Point keep words of their own 2026-11-08 07:24:34 +03:00
mkzungandClaude Opus 5.5 b325046f76 DXF/DWG: a file's registered applications are kept when no xdata names them
The writer rebuilt the APPID table only from the applications whose xdata
the drawing still had, so every other registered application of the file
was dropped at each save. The reader now keeps the names of all of the
file's APPID records, and the writer adds them to the table with the ones
in use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01H43qQA41CJLauqXnPgBQ7r
2026-11-07 23:47:26 +00:00
2ez4gcxandClaude Opus 5.5 48bcb817ed DXF writer: say the mirrored flips are exact for 0,0,-1 only
The elevation and thickness flips are exact for a normal of 0,0,-1; a
tilted normal pointing partly down is flipped the same way, an
approximation. The comments now say so (CodeRabbit's note on #2905).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 22:04:50 +07:00
2ez4gcxandClaude Opus 5.5 467ab20ace DXF: a solid or gradient hatch no longer makes AutoCAD refuse the file
Since #2665 the writer put groups 52, 41 and 77 (pattern angle, scale,
double flag) on solid fills too. AutoCAD 2024 writes none of them there
and refuses a DXF whose solid HATCH has any of them: "Error: expected
group code 98 / Invalid or incomplete DXF input -- drawing discarded".
So every DXF CADCraft saved with a solid or gradient hatch, including an
AutoCAD drawing passed through it, was discarded by AutoCAD. They are
written for pattern fills only again, as before #2665.

Measured in AutoCAD 2024: CADCraft's file with each of the three groups
dropped alone is still refused, with all three dropped it opens; with
this change AutoCAD opens CADCraft's solid, gradient and pattern hatches
and a 46-object drawing, DXF and DWG, with AUDIT reporting 0 errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 20:57:14 +07:00
2ez4gcxandClaude Opus 5.5 275f989aa5 DXF: mirrored objects keep their world height and extrusion side
The reader keeps a mirrored object's normal (0,0,-1) but brings its points
into world coordinates; a polyline's or hatch's elevation stays along the
normal. The writer writes these objects with no normal, along +Z, so a
mirrored polyline or hatch at elevation 5 (world Z -5) came back at Z +5,
and a mirrored circle, arc, point, solid or text extruded up instead of
down. Their elevation and thickness are now written along +Z too: negated
when the normal points down Z. LINE writes its normal and keeps its
thickness as read.

Measured in AutoCAD 2024 (AutoCAD's objects, converted by CADCraft,
reopened in AutoCAD): every world point and thickness top now matches the
original.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 20:30:03 +07:00
assamaralandClaude Opus 5.5 fd17a05b95 fix(doc): read the ACIS version of encoded SAT text in the save-loss report
DXF before 2007 encodes SAT text (each character but a space is 159 minus it), so
an encoded 7.0 solid read as no version and a DWG before 2013 listed it as lost.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 07:18:00 -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
assamaralandClaude Opus 5.5 f7b3b68952 Solids: no empty modeler records in DXF/DWG before 2013; list ACIS 4.0 SAT a DWG can't keep
A 3DSOLID/REGION/BODY whose ACIS geometry is only in the data store (read from a
2013+ file) was written to DXF 2010 and earlier, and DWG 2004-2010, as an empty
2013-style record (290/2 groups, no SAT), silently: ZWCAD drops it from the DXF and
opens it as an empty body from the DWG. Such files have no data store, so the entity is
now left out there and the save says so (DXF note, notSaved, the save-loss question).

A DWG before 2013 was assumed to keep any SAT-text solid. ACIS 4.0 SAT (what ZWCAD
writes to DXF 2000) reaches the DWG through acadrust without usable geometry (ZWCAD
2025 opens it as a proxy), so it is now listed as not saved
(hakanaktt/acadrust#348).

Fixes #2334

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 20:31:52 -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
filforce95andClaude Opus 5.5 b1f477bfc2 fix(layers): the Layers palette lists layers by name (fixes #2858)
The palette's layer list and its current-layer combo showed layers in the order
they were made, so new layers piled up at the bottom. They now sort by name,
ignoring case, with the same key the Layer Properties Manager already uses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 22:02:02 +01:00
lorie-capella 8c7bfb3efe fix: persist portable eframe state in app.ron 2026-11-05 10:16:07 -05:00
moandClaude Opus 5.5 9a4bc98bbf Merge remote-tracking branch 'origin/main' into xdg-font-dirs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:44:40 -05:00
okereke-devandClaude Opus 5.5 ad6d3d12ca HATCHGENERATEBOUNDARY: compare the loop count with the room left, so it can't overflow (CodeRabbit on #2804)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 21:53:26 -05:00
okereke-devandClaude Opus 5.5 6412e9c99a HATCHGENERATEBOUNDARY: a hatch named twice gets one boundary (CodeRabbit on #2804)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 21:36:46 -05:00
okereke-devandClaude Opus 5.5 f7c4c148a3 HATCHGENERATEBOUNDARY: keep the hatch elevation, refuse other spaces and over-limit calls (CodeRabbit on #2804)
Each polyline takes its hatch's elevation; a hatch outside the current space
is refused with a clear message; every selected hatch counts toward the
10,000-polyline limit, refused before anything is added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 21:25:18 -05:00
okereke-devandClaude Opus 5.5 0bd4d54f4a HATCHGENERATEBOUNDARY: Generate Boundary in the right-click menu of a hatch (#2801)
A closed polyline around every boundary loop (outer and islands) of the
selected hatches, which stay as they are: an associative hatch keeps its own
boundary objects and is not linked to the new polylines. Runs at once on a
pickfirst selection, otherwise asks for objects; one undo step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 21:02:24 -05:00
mattlafy 158d043d41 Merge remote-tracking branch 'upstream/main' into pr/locked-layer-fade
# Conflicts:
#	crates/render/src/blocks.rs
2026-11-04 20:07:10 -05: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 11ee9f1f64 Merge remote-tracking branch 'origin/main' into fix/tilted-2d-polyline 2026-11-04 08:56:37 +01:00
Walter Haslbeck e928316c4d docs: leave file-format-parity.md to the maintainers (AGENTS.md); the rows are named in the PR description 2026-11-04 08:55:57 +01:00
MarekSpodBiedry b6f17bd9be REVCLOUD: test that Reverse direction Yes reverses the arcs (#1714) 2026-11-04 07:51:32 +01:00
MarekSpodBiedry a6ee8bc596 Merge origin/main into REVCLOUD arc-length/reverse prompts (#1714) 2026-11-04 07:51:14 +01:00
MarekSpodBiedry 6294cd1546 Merge origin/main into issue-1713 (#1713) 2026-11-04 07:50:25 +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 1a3d2f6015 Merge branch 'pr2584' into fix/tilted-2d-polyline 2026-11-04 07:24:26 +01:00
Oliver HagmannandClaude Fable 5.1 a801739ea7 DXF/DWG save: kept render settings take the declared version's class-version form
Render settings store their AcDbRenderSettings class version in the
form of the file's version: a 2013+ file stores it one higher, and a
2013 file stores a rapid RT one one lower, as acadrust reads and writes
them. A kept RENDERSETTINGS, MENTALRAYRENDERSETTINGS or
RAPIDRTRENDERSETTINGS object carried the form of the file it was read
from into whatever file it was written to. The DWG bridge is an R2000
DXF for a 2018 DWG: a 2018 drawing's render settings went in with the
2018 form, the DWG writer raised it once more, and BricsCAD refused the
DWG for an object of class version 3 (#907, one of two causes; the
other is an empty constraint group written short, fixed in acadrust
0.6.6, hakanaktt/acadrust#146).

The form the kept objects are in is the $ACADVER the file declared,
recorded at read time in Foreign::acadver (the DWG bridge reads
through the DXF reader, so it is set there too). The drawing's own
$ACADVER is not used: SAVEAS changes it while the kept objects stay
as read, so a 2018 drawing saved as 2000 and then as 2018 wrote class
version 3 again. A file without $ACADVER records none, and its kept
objects are written as read.

Tests: the conversion is checked against acadrust itself (acadrust
writes the fixture in four versions, and CADCraft, reading any of them
and saving in any of them, stores what acadrust stores); SAVEAS 2000,
QSAVE, then SAVEAS 2018 through the engine; a file without $ACADVER.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 07:00:46 +01:00
moandClaude Opus 5.5 757601780d Try FreeSerif before Unifont for missing glyphs
Unifont has no mark-to-mark positioning, so taking it ahead of GNU FreeSerif drew Thai and
Indic text with marks on top of each other; FreeSerif shapes those scripts properly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 17:30:22 -05:00
mo f66434ee8f Merge remote-tracking branch 'origin/main' into xdg-font-dirs 2026-11-03 17:13:38 -05:00
lorie-capella 8b6c204fd8 Windows: Keep portable settings beside the executable (#731) 2026-11-03 16:12:55 -05:00
Walter Haslbeck 41f9e394b9 fix(io): draw a tilted 2D POLYLINE as seen from above, like LWPOLYLINE (follow-up to #2584) 2026-11-03 15:42:49 +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
mattlafy d5720c6403 Merge remote-tracking branch 'upstream/main' into pr/locked-layer-fade
# Conflicts:
#	crates/render/src/draw.rs
2026-11-02 21:51:22 -05:00
NetterSilverandClaude Haiku 5.5 0f94865fa9 Write RevcloudProps xdata on revision clouds
Fixes #1570

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 00:29:49 +00:00
Nicholas Gower dc59a8e33c dim: note that DIMPOST wraps angles 2026-11-02 08:30:17 -08:00
Nicholas Gower b17880ca89 dim: apply the style's DIMPOST to angular dimensions (#1653) 2026-11-02 08:29:34 -08:00
moandClaude Opus 5.5 0cbe1b7e50 Gate the fonts crate's HashSet import to the targets that walk font directories
Only walk_font_dirs uses it, and that function is not built on wasm32, where the
import was an unused-import warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 18:42:44 -05:00
moandClaude Opus 5.5 577aa81e8b Leave docs/gaps.md and docs/localization-parity.md to the maintainers
AGENTS.md asks PRs not to edit the parity and gaps documents: the affected
rows are named in the PR description, and the maintainers update them in
batches. The two files are back to main's version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 18:40:29 -05:00
Cody VogtandClaude Sonnet 5.5 72e82c59d0 Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 16:17:36 -06:00
midasmatterhorn 1dcb30426c io: group the ENTITIES handle rules into one HandlePolicy parameter
clippy -D warnings refused parse_entities' eight parameters; the seen /
reserved / source-wins trio travels together anyway.
2026-11-01 15:18:55 +03:00
Cody VogtandClaude Sonnet 5.5 72f8dd8076 Merge #1725's acadrust version doc fix into fix/dwg-constraint-group
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 01:45:04 -06:00
Cody VogtandClaude Sonnet 5.5 cc74fe32ed DWG: the scale action byte doc names acadrust 0.6.6, the version in use
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 01:44:41 -06:00
midasmatterhorn 722aeb1080 fonts: cover the cap-height fallback chain and document CADCRAFT_CAP_HEIGHT 2026-11-01 08:29:13 +03:00
midasmatterhorn 44f026833c io: a handle repeated across ENTITIES sections keeps both entities 2026-11-01 05:21:13 +03:00
midasmatterhorn d03af7d7a6 fonts: a substitute's text scales by the cap height the installation pins for it, not the substitute's own 2026-11-01 05:02:23 +03:00
mo 60ac0548e1 Merge remote-tracking branch 'origin/main' into xdg-font-dirs
# Conflicts:
#	crates/ui-egui/src/theme.rs
2026-10-31 11:33:56 -04:00
mattlafyandClaude Opus 5.5 a5c8b1acf6 Format the Escape-drag test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:37:22 -04:00
mattlafy b17523e53c Merge remote-tracking branch 'upstream/main' into pr/realtime-pan 2026-10-30 15:31:14 -04:00
mattlafyandClaude Opus 5.5 53ac71c1fe Clear the navigation drag when its button is released after Escape stopped it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:30:39 -04:00
mattlafyandClaude Opus 5.5 b2ebb3958d Place no point on the release of a realtime PAN or ZOOM drag
A primary drag that moved the view is marked while it lasts; its release reaches no point prompt, also when Enter ended the transparent PAN or ZOOM mid-drag and handed the prompt back to the drawing command.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:46:01 -04:00
mattlafy 393475f308 Merge remote-tracking branch 'upstream/main' into pr/locked-layer-fade
# Conflicts:
#	crates/render/src/lib.rs
#	crates/ui-egui/src/canvas.rs
2026-10-28 15:26:04 -04:00
mattlafy a9294b5151 Merge remote-tracking branch 'upstream/main' into pr/realtime-pan
# Conflicts:
#	crates/ui-egui/src/canvas.rs
2026-10-28 15:23:30 -04:00
Cody Vogt 9a5f26d5aa Merge commit '5ab29b40908316b59a74d67cab9e53ac66b7f591' into HEAD 2026-10-28 09:20:16 -06:00
Cody Vogt f646452065 Merge branch 'main' of https://github.com/storytold/cadcraft into fix/dwg-constraint-group 2026-10-28 09:20:15 -06:00
Cody Vogt 5ab29b4090 Merge branch 'main' of https://github.com/storytold/cadcraft into fix/dwg-scale-action 2026-10-28 09:20:12 -06:00
Cody Vogt b6cc1c29ee Merge remote-tracking branch 'origin/fix/dwg-scale-action' into fix/dwg-constraint-group 2026-10-27 12:17:32 -06:00
Cody VogtandClaude Opus 5.5 015fe2a18d ui: block description field ids from Ui::scope_id (egui 0.37 deprecates Ui::id)
main's gate fails clippy -D warnings on the one Ui::id() call (#2113);
Ui::scope_id is its new name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 12:17:26 -06:00
Cody Vogt bb95044b19 Merge remote-tracking branch 'origin/fix/dwg-scale-action' into fix/dwg-constraint-group 2026-10-27 12:02:12 -06:00
Cody Vogt bee69e6f24 Merge branch 'main' of https://github.com/storytold/cadcraft into fix/dwg-constraint-group
# Conflicts:
#	crates/io/src/dxf_write.rs
#	docs/file-format-parity.md
2026-10-27 12:02:12 -06:00
Cody Vogt 0bf230b14a Merge branch 'main' of https://github.com/storytold/cadcraft into fix/dwg-scale-action
# Conflicts:
#	docs/file-format-parity.md
2026-10-27 12:00:07 -06:00
mattlafy b48c82c1fe docs(render): DPrim::transparency includes the on-screen locked-layer fade 2026-10-26 16:47:47 -04:00
mattlafy 16290fd8d6 fix(render): ByBlock attributes take the reference's transparency without its locked-layer fade 2026-10-26 15:44:59 -04:00
mattlafy a35a9add42 Merge remote-tracking branch 'upstream/main' into pr/locked-layer-fade
# Conflicts:
#	crates/render/src/lib.rs
2026-10-25 16:25:32 -04:00
mo aa08cfc0a9 Merge main: localization-parity keeps main's header and IME note beside the font-directory lines 2026-10-25 12:26:59 -04:00
mo e0f8751f08 Merge main: the installed UI font also backs Monospace after Hack 2026-10-25 11:16:34 -04:00
mo 584e5471b1 Merge main: take main's gaps.md header; the font-directory row stays in the change log 2026-10-25 01:48:40 -04:00
mo 911b4f766e Merge main: gaps.md header keeps the font-directory change as the previous one 2026-10-25 00:12:47 -04:00
Cody VogtandClaude Opus 5.5 0a23281d45 io test: malformed constraint groups keep their content after each mode
The length check couldn't see a rotation, and checking only after both modes
could miss one undone by the second.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 15:41:51 -06:00
Cody Vogt 3f3ac1ded9 Merge branch 'main' of https://github.com/storytold/cadcraft into fix/dwg-constraint-group
# Conflicts:
#	crates/io/src/tests.rs
2026-10-24 15:41:50 -06:00
moandClaude Opus 5.5 dc2acd9b72 Read each font directory once by its resolved path
A symlink back up the tree was read again at every hop until the kernel
gave up, about 40 hops; a large directory could use up the 20 000 entry
budget there before the other font directories were reached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 03:49:40 -04:00
mo ef36f222aa Merge main: keep both changelog rows in gaps.md and localization-parity.md 2026-10-24 03:18:08 -04:00
Cody Vogt 7f2e4bb817 Merge remote-tracking branch 'origin/fix/dwg-scale-action' into fix/dwg-constraint-group 2026-10-24 00:30:05 -06:00
Cody VogtandClaude Opus 5.5 c667151667 io tests: a scale action survives CADCraft's own DWG save
The cadcraft-dwg test builds its DXF with acadrust's writer; this one goes
through cadcraft_io::write (the bridge DXF, then acadrust) with a scale
action added to the synthetic Door fixture, and checks the DWG holds it
with its connections and reads back as the same action.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 00:29:55 -06:00
Cody Vogt d2a1090357 Merge branch 'main' of https://github.com/storytold/cadcraft into fix/dwg-constraint-group
# Conflicts:
#	crates/io/src/tests.rs
#	docs/file-format-parity.md
2026-10-24 00:20:22 -06:00
Cody Vogt 24e5687c3d Merge branch 'main' of https://github.com/storytold/cadcraft into fix/dwg-scale-action
# Conflicts:
#	docs/file-format-parity.md
2026-10-24 00:16:25 -06:00
Cody Vogt a35817eaea Merge branch 'main' of https://github.com/storytold/cadcraft into fix/dwg-constraint-group
# Conflicts:
#	crates/dwg/Cargo.toml
#	crates/dwg/src/lib.rs
#	crates/io/Cargo.toml
2026-10-23 11:28:21 -06:00
Cody Vogt b49137f6dd Merge branch 'main' of https://github.com/storytold/cadcraft into fix/dwg-scale-action
# Conflicts:
#	crates/dwg/Cargo.toml
#	crates/dwg/src/lib.rs
#	crates/io/Cargo.toml
2026-10-23 11:17:40 -06:00
Cody VogtandClaude Opus 5.5 5147aae2c2 DWG: constraint groups keep their nodes (AutoCAD opened none with parametric blocks)
A kept 2D constraint group (ACDBASSOC2DCONSTRAINTGROUP) was written with its tags as read. From
AutoCAD 2013 on a node's status (70) comes after its connections, before that right after its id,
and acadrust reads it by the DXF's version. The DWG bridge's DXF declares R2000, so a 2013+
drawing's groups gave acadrust every node's status and connections from the wrong groups, and
AutoCAD refused the DWG ("Error Decrypting Data"), e.g. the dynamic blocks sample with
parametric blocks. The writer now puts each node's status where the written version has it; a
group whose nodes it can't all find is left as it is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 09:38:54 -06:00
Cody VogtandClaude Opus 5.5 b551acec8d DWG: acadrust 0.6.6; multi-layout DWGs get unique paper space names
0.6.6 keeps the scale action byte and the dimension flag mapping this branch
relies on, and writes only the active layout as *Paper_Space (others get
unique *Paper_SpaceN names; hakanaktt/acadrust#143), so ACadSharp opens a
DWG CADCraft saves with more than one layout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 09:34:47 -06:00
Cody VogtandClaude Opus 5.5 fa4f997eed DWG: scale actions keep the byte AutoCAD reads after their connections (acadrust 0.6.5)
AutoCAD's DWG scale action (BLOCKSCALEACTION) ends with one byte after its
three connections that DXF doesn't carry. acadrust 0.6.4 neither read nor
wrote it, so AutoCAD read past the object and refused every DWG CADCraft
wrote with a dynamic block that scales ("Error Decrypting Data"), even an
unchanged one. acadrust 0.6.5 keeps the byte (dwg_tail_byte).

0.6.5 also maps the dimension flags byte's bit 0 to text_user_positioned
both ways, so the bridge no longer inverts it (it would now double-invert);
it still sets bit 1, which acadrust keeps no DXF source for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 09:34:47 -06:00
moandClaude Fable 5.1 0327f7512b Ask the font database for an interface font only after the usual places
`installed()` consulted `installed_font_path` for every candidate even
when the file was already found at its absolute path, and that lookup's
first use walks every font directory on the machine; `install_fonts`
runs at start-up, so the walk happened just to open a file under
/usr/share/fonts that a few `fs::read` calls used to find. The absolute
candidates are now yielded first and the database is asked lazily, only
when a caller needs more than they hold.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 16:32:00 -04:00
moandClaude Fable 5.1 61fc55d7b6 Cap the system UI font read like the other interface font reads
installed() handed its candidates to std::fs::read, the one uncapped
font read in theme.rs, while the CJK, Arabic, Korean and embedded faces
go through read_capped(path, MAX_UI_FONT_BYTES), so a system UI font
file of any size was read into memory. It now goes through read_capped
too; the first candidate that reads within the cap is still the one
used.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 14:13:17 -04:00
moandClaude Fable 5.1 b121eb1517 Run the font-directory resolver tests on Unix only
The tests in ttf/dirs.rs build configurations from POSIX paths such as
/usr/share/fonts, which Path::is_absolute rejects on Windows, so
`cargo test -p cadcraft-fonts` would fail there although the resolver
itself builds on every target and is only consulted on Linux and the
BSDs. The test module is gated on unix and says so; the non-test code is
unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 14:11:42 -04:00
moandClaude Fable 5.1 e0f33d7d93 Read fontconfig prefix attributes with whitespace around '='
The <dir> and <include> scanner split a start tag on whitespace and took
each token as a whole attribute, so legal XML such as
<dir prefix = "relative">extra-fonts</dir> or
<include prefix = "xdg">fontconfig/fonts.conf</include>, with spaces or
newlines around '=', was read as having no prefix: the relative directory
was dropped and the xdg include looked up under $FONTCONFIG_PATH instead
of $XDG_CONFIG_HOME. A start tag's attributes are now parsed as a name,
optional whitespace, '=', optional whitespace and a single- or
double-quoted value, in any order, within the same file, depth and
element bounds. Tests cover spaces and newlines around '=' on both
elements, attribute order, and malformed attributes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 14:10:29 -04:00
moandClaude Fable 5.1 14e3126df8 docs: installed fonts are found where fontconfig looks
Localization parity: drawing-text fallbacks and the system UI font now
work on NixOS, Guix and Flatpak. Gaps: P2 narrowed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 12:05:48 -04:00
moandClaude Fable 5.1 f1aa54b9c2 Look for the interface's fonts by stem wherever the system keeps them
install_fonts(), cjk_font(), arabic_font(), japanese_font() and
korean_font() named absolute /usr/share/fonts paths, so on NixOS, Guix and
in Flatpak sandboxes the interface kept egui's bundled font and a Chinese,
Japanese, Korean or Arabic interface showed boxes with the fonts installed
(#674). Each candidate list is now resolved through installed(): the
absolute paths first, unchanged for Debian, Arch and Fedora, then the same
file stems through the fonts crate's scan, which looks where fontconfig
does. No font names are added and nothing is bundled.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 12:05:48 -04:00
moandClaude Fable 5.1 3b8531ff5f Rank Unifont last among the known fallback fonts
The missing-glyph search loads at most 24 files: the known wide-coverage
fonts first, then the rest alphabetically, which never reaches "u".
NixOS's default font set (DejaVu, FreeFont, TeX Gyre, Liberation, Unifont,
Noto Color Emoji) has Unifont as its only CJK-capable font, so even with
the fonts found Chinese text still drew boxes. Listed last, Unifont's
bitmap-like outlines serve only characters no listed font has.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 12:05:48 -04:00
moandClaude Fable 5.1 bbd4eddd45 Find installed fonts where fontconfig looks: XDG dirs, fontconfig <dir> entries, Flatpak host fonts
On Linux and the BSDs the font scan only walked /usr/share/fonts,
/usr/local/share/fonts, ~/.fonts and ~/.local/share/fonts. NixOS and Guix
keep every font package in its own store path and tell fontconfig about
them through <dir> entries (/etc/fonts/conf.d/00-nixos-cache.conf,
home-manager's ~/.config/fontconfig/conf.d) and $XDG_DATA_DIRS; a Flatpak
sandbox sees the host's fonts only under /run/host. On such systems the
scan found nothing, so CJK and Arabic characters in drawing text drew the
missing-glyph box although fonts with them were installed (#674).

A resolver in ttf/dirs.rs returns the directories fontconfig would use, in
priority order: $XDG_DATA_HOME/fonts and ~/.fonts, every $XDG_DATA_DIRS
entry + /fonts (plus /usr/share/fonts and /usr/local/share/fonts whether
listed or not), Flatpak's /run/host/{fonts,local-fonts,user-fonts}, then
the <dir> elements of $FONTCONFIG_FILE or /etc/fonts/fonts.conf, following
<include> files and conf.d directories with fontconfig's documented prefix
rules (~, xdg, relative). It is a pure function of injected env and file
lookups, so its tests run the same everywhere, and bounded in files,
nesting, bytes, elements and directories; a hand-written scanner reads the
two element names rather than adding an XML dependency to the fonts crate.
The scan canonicalizes the directories so a symlinked profile is not
walked twice, and keeps its entry cap. macOS and Windows are unchanged.

installed_font_path() exposes the scan's stem map, for the interface to
find its fonts by file stem.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 12:05:48 -04:00
MarekSpodBiedry b44cb36865 REVCLOUD: ask maximum arc length and Reverse direction for Object (#1714) 2026-10-20 18:45:39 +02:00
MarekSpodBiedry 6f5bf85dc0 REVCLOUD: the Object option accepts an entity name (#1713) 2026-10-20 18:45:20 +02:00
mattlafy 15dcfcfba9 ByBlock children of a reference on a locked layer take its own transparency, not its fade 2026-10-19 22:42:36 -04:00
mattlafy e9471f6140 Merge remote-tracking branch 'upstream/main' into fix/locked-layer-fade
# Conflicts:
#	crates/render/src/tests.rs
2026-10-19 21:39:00 -04:00
mattlafyandClaude Opus 5.5 17408bdb65 Fade locked layers only in on-screen builds
The render `Options::on_screen` flag (off by default) applies the
LAYLOCKFADECTL fade; only the interactive canvas sets it, so plots and
SVG, PNG, PDF and CLI exports never fade objects on locked layers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 09:15:02 -04:00
mattlafyandClaude Opus 5.5 7f84dab948 Fade objects on locked layers on screen by LAYLOCKFADECTL
Objects on a locked layer draw faded by LAYLOCKFADECTL percent (default 50;
0 or negative: no fade), whether or not transparency display is on. An object
keeps its own transparency when that is greater. Plots never fade. Layer 0
inside a block takes the reference's layer.

LAYLOCKFADECTL is a header variable (-90 to 90) available to GETVAR and SETVAR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 18:48:18 -04: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
mattlafyandClaude Opus 5.5 fc67a5c28a PAN pans in realtime by dragging; -PAN asks for two points
PAN (alias P, View > Pan > Realtime) is realtime: a left-button drag
moves the drawing with the cursor until Esc or Enter, and the session is
one Zoom Previous entry. -PAN takes a base point and a second point, or
a point then Enter as a displacement. The JSON form of pan is unchanged.

Fixes #1245.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 21:48:16 -04:00
240 changed files with 11667 additions and 921 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
+83 -88
View File
@@ -661,6 +661,7 @@ dependencies = [
"craft-window",
"eframe",
"egui",
"fmv-macos-events",
"hidapi",
"log",
"muda",
@@ -780,7 +781,7 @@ dependencies = [
"cadcraft-render",
"craft-dwg",
"craft-dxf",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
"craft-image-codecs",
"craft-pdf",
"craft-svg",
"image",
@@ -817,7 +818,7 @@ dependencies = [
"cadcraft-doc",
"cadcraft-fonts",
"cadcraft-geom",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
"craft-image-codecs",
"lyon_tessellation",
"rayon",
"serde_json",
@@ -836,7 +837,7 @@ dependencies = [
"cadcraft-io",
"cadcraft-render",
"chrono",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
"craft-image-codecs",
"craft-ui",
"craft-update",
"craft-window",
@@ -1180,22 +1181,30 @@ dependencies = [
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db#0325b2d73676d736e94097dbcef01219cf25c7db"
source = "git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a#219c1d0b14177af6f291395d6587f61a5e09043a"
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a#219c1d0b14177af6f291395d6587f61a5e09043a"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"rayon",
]
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
[[package]]
name = "craft-dwg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf#7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"acadrust",
"log",
@@ -1216,22 +1225,26 @@ dependencies = [
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c07e38090879ffa994f893df9956c6d5b96c049c#c07e38090879ffa994f893df9956c6d5b96c049c"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"harfrust 0.13.3",
"kurbo",
"skrifa 0.47.0",
"thiserror 2.0.21",
"unicode-bidi",
"unicode-segmentation",
"windows-registry",
]
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1254,35 +1267,12 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
"crc32fast",
"exr",
"flate2",
"half",
"hayro-jpeg2000",
"image",
"image-webp",
"jpeg-encoder",
"png",
"rayon",
"serde_json",
"thiserror 2.0.21",
"tiff",
"zune-core",
"zune-jpeg",
"zune-jpegxl",
]
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
dependencies = [
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
"craft-dds",
"craft-jpeg",
"craft-metadata",
"craft-tiff",
"crc32fast",
"exr",
"flate2",
@@ -1304,15 +1294,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"thiserror 2.0.21",
]
@@ -1320,7 +1302,7 @@ dependencies = [
[[package]]
name = "craft-jsonrpc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b6222158fbc2a628f27d2c1fff9f648cd194404c#b6222158fbc2a628f27d2c1fff9f648cd194404c"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"serde_json",
]
@@ -1328,7 +1310,7 @@ dependencies = [
[[package]]
name = "craft-mcp"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b6222158fbc2a628f27d2c1fff9f648cd194404c#b6222158fbc2a628f27d2c1fff9f648cd194404c"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"craft-jsonrpc",
"serde_json",
@@ -1337,23 +1319,11 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"brotli-decompressor",
"chrono",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
"quick-xml 0.41.0",
"serde",
]
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
dependencies = [
"brotli-decompressor",
"chrono",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
"craft-tiff",
"quick-xml 0.41.0",
"serde",
]
@@ -1361,17 +1331,17 @@ dependencies = [
[[package]]
name = "craft-mime"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db#0325b2d73676d736e94097dbcef01219cf25c7db"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"chrono",
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db)",
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc)",
"encoding_rs",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"hayro-syntax",
"krilla",
@@ -1381,14 +1351,13 @@ dependencies = [
[[package]]
name = "craft-shx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2f2d1d84e3a36b3f93e81507aeff3f0da97a7162#2f2d1d84e3a36b3f93e81507aeff3f0da97a7162"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
"craft-xml",
"flate2",
"kurbo",
@@ -1402,16 +1371,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1420,7 +1380,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1441,7 +1401,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"chrono",
"dunce",
@@ -1468,7 +1428,7 @@ dependencies = [
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"js-sys",
"serde_json",
@@ -1479,7 +1439,7 @@ dependencies = [
[[package]]
name = "craft-web-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"wasm-bindgen",
"web-sys",
@@ -1488,7 +1448,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"egui",
"objc2 0.6.5",
@@ -1499,7 +1459,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -2097,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"
@@ -2446,6 +2417,19 @@ dependencies = [
"smallvec",
]
[[package]]
name = "harfrust"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "948d0741125ba89cd3e1c23e5642415b6ade7e1d29d67ba25fb925b533e989d6"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"once_cell",
"read-fonts 0.43.3",
"smallvec",
]
[[package]]
name = "harfrust"
version = "0.14.0"
@@ -2505,7 +2489,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"hayro-ccitt",
]
@@ -2522,7 +2506,7 @@ dependencies = [
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"hayro-jbig2",
"hayro-jpeg2000",
@@ -3022,7 +3006,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -4284,6 +4268,17 @@ dependencies = [
"once_cell",
]
[[package]]
name = "read-fonts"
version = "0.43.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "005c8acf251756c478b0bf402885bfd88a1476020c4c7e6060edc1aa68da38ea"
dependencies = [
"bytemuck",
"font-types 0.12.7",
"once_cell",
]
[[package]]
name = "read-fonts"
version = "0.44.0"
+16 -16
View File
@@ -15,10 +15,10 @@ repository = "https://github.com/storytold/cadcraft"
cadcraft-geom = { path = "crates/geom" }
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "219c1d0b14177af6f291395d6587f61a5e09043a" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "2f2d1d84e3a36b3f93e81507aeff3f0da97a7162" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ae5020c1ed922cf7976a3a5545f05b07f466be12" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0325b2d73676d736e94097dbcef01219cf25c7db" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
cadcraft-color = { path = "crates/color" }
cadcraft-doc = { path = "crates/doc" }
cadcraft-constraints = { path = "crates/constraints" }
@@ -28,17 +28,17 @@ cadcraft-io = { path = "crates/io" }
cadcraft-engine = { path = "crates/engine" }
cadcraft-ui-egui = { path = "crates/ui-egui" }
cadcraft-mcp = { path = "crates/mcp" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "b6222158fbc2a628f27d2c1fff9f648cd194404c" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "b6222158fbc2a628f27d2c1fff9f648cd194404c" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# SVG/SVGZ import and export geometry (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# Which paths stored in a drawing (xrefs, data links) may be opened.
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", default-features = false }
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "c07e38090879ffa994f893df9956c6d5b96c049c", default-features = false }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4.6.11"
clap_mangen = { version = "0.3.3", features = ["env"] }
@@ -70,8 +70,8 @@ encoding_rs = "0.8.35"
quick-xml = "0.42"
# ui
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["serde"] }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
@@ -81,7 +81,7 @@ egui-wgpu = "0.37"
# Monotonic time on native and web (performance.now on wasm).
web-time = "1.1"
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
rfd = "0.17"
arboard = { version = "3.6", default-features = false }
@@ -113,9 +113,9 @@ debug = 0
# PDF backends for craft-pdf: pinned to the same reviewed craft-libs revision as craft-pdf itself
# (Cargo ignores dependency-local patches).
[patch.crates-io]
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# Keep the complete egui family and native event bridge on reviewed fork commits.
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+28
View File
@@ -184,6 +184,34 @@ in the text style or set `FONTFALLBACK` (`CADCRAFT_FONTFALLBACK="Vazirmatn"`). F
inside a word (an MTEXT colour change in the middle of a Persian word) break the joining at that
point.
### Portable Windows ZIP
The Windows portable ZIP includes `portable.txt` beside `cadcraft.exe`. With that
marker present, the desktop app's settings, logs, autosaves, workspace data,
plotter files, and eframe preferences/window state stay in `CADCraftData` beside
the executable. eframe saves its preferences and window state in `CADCraftData/app.ron`.
Keep that directory when replacing the binaries. The MSI does not include the
marker and continues to use the normal user profile.
`CADCRAFT_CONFIG_DIR` takes precedence over the marker, including an empty or
blank value that disables the settings folder. If `CADCraftData` cannot be
created or written, CADCraft warns and uses the normal profile. Existing profile
settings are not automatically copied into the portable directory.
Before switching an existing Windows installation to portable mode, close CADCraft,
back up `%APPDATA%\CADCraft`, and copy the settings you want to retain into
`CADCraftData`. Include the `autosave` folder if you need to recover unsaved drawings. The
preferences and window state are kept apart, in `%APPDATA%\ai.storyteller.cadcraft\data\app.ron`:
copy that file to `CADCraftData\app.ron` to keep them.
Updating a portable ZIP, including through the updater, can restore `portable.txt`;
set `CADCRAFT_CONFIG_DIR` to your existing profile folder to keep using it across updates.
`cadcraft-cli.exe` does not detect the marker. To share the desktop app's portable
settings, pass `--config-dir` with the full path to `CADCraftData`, or set
`CADCRAFT_CONFIG_DIR` to that path. The marker is also recognized on other desktop
platforms, but is intended for a standalone writable installation, not inside a
signed macOS application bundle.
### Logs
The desktop app writes its `log` records to standard error and to `logs/cadcraft.log` in the
+15 -10
View File
@@ -2,7 +2,7 @@
**Stage: pre-alpha** · next: alpha, when the six rows of the [alpha gate](docs/roadmap.md#alpha-gate) pass (five fail today; the gate was revised on 2026-11-19 and its hours are not re-estimated yet)
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-19 · **Change:** major (alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-20 · **Change:** minor (Upcoming updated for what merged on 2026-11-19 and 2026-11-20; previously major: alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
CADCraft targets full parity with AutoCAD (2D drafting first, then annotation, layouts and
plotting, DWG, parametrics and 3D), plus what AutoCAD doesn't have: agent control over MCP, a
@@ -115,21 +115,23 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
- The open findings of the security audit (#1919–#1935): check each against the input limits that
landed on 2026-11-11, close what is fixed and fix the rest. A crafted handle that makes new entities
overwrite existing ones (#1921) is fixed by #1276.
- Hostile-input fixes waiting in pull requests (#2820, #2821, #2765).
- A saved file that crashes AutoCAD 2021 (#3303) and dimension text lost on save (#3299).
- Crashes and hangs with a reproduction: the web build on a large DXF (#1603), a DWG with 3D content
(#2174), startup on older graphics hardware (#1724, #1631, #3222).
**2. Parity with AutoCAD: the alpha gate rows, then the beta checklist (apart from its items named under tier 3).**
- It starts on common hardware (#1596, then an automatic fallback renderer).
- It starts on common hardware: an automatic fallback renderer (`CADCRAFT_STENCIL=0` is the manual
switch since #3336).
- It opens the DWG and DXF files people already have: large files (#3102, #2633, #1088), layouts and
paper units (#1672, #2836), and a corpus of real files run in CI.
- Saving loses nothing and other CAD programs open the result (#2904, #1687, #3234, #2632).
- Input feels like AutoCAD for Windows: clicks while the mouse moves (#1001, #2092), right-click and
Space as Enter (#1387), double-click to edit text (#842).
- The prompt options that still say "not available yet", and TRIM/EXTEND depth.
- Layouts print at scale on a system printer, and the menu bar and panels can always be restored
(#3216, #1240).
- 714 pull requests are open (2026-11-19). About 230 are mergeable, pass CI and are small; they are
- Input feels like AutoCAD for Windows: the fixes for clicks while the mouse moves, right-click and
Space as Enter, and double-click text editing landed (#3307, #3345); waiting for the reporters to
confirm, and table cells are left (#842).
- The prompt options that still say "not available yet" (gaps F1).
- Layouts print at scale on a system printer (#3216); the menu bar and panels can be restored since
#3308.
- 661 pull requests are open (2026-11-20; 714 the day before). About 230 were mergeable, passed CI and were small; they are
reviewed and landed in this order, the longest-waiting authors first within a row.
**3. Lower priority: affects fewer people and nothing breaks without it.**
@@ -139,7 +141,9 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
but a file with 3D content must open safely (tier 1).
- Menu breadth against AutoCAD for Mac as a headline number.
Done since the last ranking: precision input (#379, #441, #60, #519), prompt options in TRIM/EXTEND,
Done on 2026-11-19 and 2026-11-20: the hostile-input fixes #1276, #2820, #2821 and #2765 (#3304, #3305), clicks while the mouse moves and right-click or Space as Enter (#3307), the interface reset (#3308), paper units (#3309), the UCS command (#3310), -ATTEDIT, -RENAME and -LAYER options (#3311), TRIM/EXTEND depth (#3312), dimension values kept on save (#3335), the stencil switch (#3336), a typed OPEN path (#3343) and double-click text editing (#3345).
Done before that: precision input (#379, #441, #60, #519), prompt options in TRIM/EXTEND,
OFFSET, ROTATE, PLINE, SPLINE, MTEXT and MLEADER (#397, #408, #547), autosave, recovery, AUDIT and
RECOVER on the desktop (#406, #416), xrefs (#525), groups (#417), the Block Editor (#824, #833, #885),
REFEDIT (#818), XCLIP (#2354), dynamic block references (#838–#883), and the Dimension Style Manager
@@ -166,6 +170,7 @@ REFEDIT (#818), XCLIP (#2354), dynamic block references (#838–#883), and the D
| Date | Change | Summary |
|---|---|---|
| 2026-11-20 | minor | Upcoming updated for the merges of 2026-11-19 and 2026-11-20 (security stacks, input, interface reset, paper units, UCS, prompt options, TRIM/EXTEND, text editing in place); pull-request count 714 → 661; percentages and hours not re-scored |
| 2026-11-19 | major | Alpha gate revised from user reports (six rows, Windows first; block authoring, xref editing in place and exact curve geometry moved to beta); Upcoming re-ranked into three tiers: urgent (security, leaks, crashes, lost work), parity, lower priority; percentages and hours not re-scored |
| 2026-10-24 | minor | Re-audit against main 41d9b5e95: language table, CI gate and open-PR count re-checked against main 41d9b5e95 |
| 2026-10-21 | trivial | Progress log: proxy objects keep their class through a save (#1812) |
+28 -1
View File
@@ -56,6 +56,9 @@ fn install_io() {
});
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
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.
@@ -76,6 +79,11 @@ pub fn command() -> clap::Command {
/// Run the CLI on its arguments (without the program name). Returns the process exit code (0 ok,
/// 1 failure, 2 usage). clap reads the arguments as they are: a value that is not valid Unicode
/// is a usage error, never a panic as with `std::env::args()`.
///
/// Reading or writing DWG needs a conversion worker, which this function does not set up: the
/// binary calls `cadcraft_io::dwg_worker::use_own_worker()` first. A caller that converts only its
/// own, trusted files can call `cadcraft_io::dwg_worker::allow_in_process()` instead. With
/// neither, a DWG file gets "no worker is configured" and exit code 1.
pub fn run<I, T>(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32
where
I: IntoIterator<Item = T>,
@@ -88,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
@@ -158,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(())
+4 -2
View File
@@ -8,6 +8,7 @@ use cadcraft_io::dwg_worker;
#[test]
fn a_real_worker_reads_and_writes_and_its_death_is_an_error_here() {
let drawing = cadcraft_engine::sample::bracket();
dwg_worker::allow_in_process();
let in_process = cadcraft_io::write(&drawing, "a.dwg").unwrap();
dwg_worker::use_worker(env!("CARGO_BIN_EXE_cadcraft-cli").into(), vec![dwg_worker::WORKER_ARG.into()]);
@@ -34,7 +35,8 @@ fn a_real_worker_reads_and_writes_and_its_death_is_an_error_here() {
assert!(e.contains("worker stopped"), "{e}");
assert!(cadcraft_io::read(&written, "a.dwg").is_ok(), "the next file gets a new worker");
// No worker to start: the work happens here, as without one.
// A worker that cannot start is an error, even where in-process conversion is allowed.
dwg_worker::use_worker("no-such-program-here".into(), Vec::new());
assert!(cadcraft_io::read(&written, "a.dwg").is_ok());
let e = cadcraft_io::read(&written, "a.dwg").unwrap_err().to_string();
assert!(e.contains("could not start"), "{e}");
}
+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]
+9
View File
@@ -824,6 +824,7 @@ fn non_unicode_arguments() {
fn non_unicode_output_names() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
cadcraft_io::dwg_worker::allow_in_process();
let s = Scratch::new("nonunicode-out");
let latin1 = |ext: &str| {
let mut n = b"caf\xe9.".to_vec();
@@ -948,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
@@ -11,6 +11,7 @@ fn cli(args: &[&str]) -> Output {
/// A DWG of 200 lines, and a copy damaged so that the reader skips some of its records (found the
/// way the reader's own test finds one: flipping a few bytes at a time across the objects area).
fn dwg_and_damaged_copy() -> (Vec<u8>, Vec<u8>) {
cadcraft_io::dwg_worker::allow_in_process();
let mut dxf = String::from("0\nSECTION\n2\nENTITIES\n");
for i in 0..200 {
dxf += &format!("0\nLINE\n8\n0\n10\n{i}\n20\n0\n11\n{i}\n21\n10\n");
+2 -2
View File
@@ -21,8 +21,8 @@ cadcraft-io = { workspace = true }
cadcraft-fonts = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
# The page command API (storytold/craft-libs#413): window.cadcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
+3
View File
@@ -130,6 +130,9 @@ mod web {
});
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
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());
}
}
+56 -2
View File
@@ -35,8 +35,10 @@ pub(crate) const VARS: &[(&str, &str)] = &[
/// `CADCRAFT_CONFIG_DIR`.
#[derive(Debug, PartialEq)]
pub(crate) struct Env {
/// Portable eframe storage file, kept with the other settings instead of the user profile.
pub(crate) portable_storage_file: Option<PathBuf>,
/// The settings folder (logs, autosave, workspace, plotters): `CADCRAFT_CONFIG_DIR`; else, when
/// that is unset, the platform's (`cadcraft_engine::settings_dir::platform`). `None`: no
/// that is unset, the portable directory or the platform's (`cadcraft_engine::settings_dir::platform`). `None`: no
/// folder, because the variable is empty or blank (the way to run without one) or the
/// platform has none.
pub(crate) config_dir: Option<PathBuf>,
@@ -63,7 +65,26 @@ pub(crate) struct Env {
impl Env {
pub(crate) fn read() -> Env {
Env::from_vars(|k| std::env::var_os(k))
let exe_dir = std::env::current_exe().ok().and_then(|p| p.parent().map(PathBuf::from));
Self::from_vars_and_exe(|k| std::env::var_os(k), exe_dir.as_deref())
}
fn from_vars_and_exe(var: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&std::path::Path>) -> Env {
let mut vars = Env::from_vars(&var);
// An explicit override (including blank, which disables settings) takes precedence.
if var(CONFIG_DIR).is_none()
&& let Some(exe) = exe_dir
{
match crate::portable::directory_in(exe) {
Ok(Some(data)) => {
vars.config_dir = Some(data.clone());
vars.portable_storage_file = Some(data.join("app.ron"));
}
Ok(None) => {}
Err(error) => log::warn!("portable settings cannot be written ({error}); using the user profile"),
}
}
vars
}
/// [`Env::read`] with `var` looking a variable up.
@@ -71,6 +92,7 @@ impl Env {
let text = |k: &str| var(k).and_then(|v| v.into_string().ok()).filter(|v| !v.trim().is_empty());
let switch = |k: &str| Switch::parse(k, var(k).map(|v| v.to_string_lossy().into_owned()).as_deref());
Env {
portable_storage_file: None,
config_dir: match var(CONFIG_DIR) {
Some(dir) if dir.to_str().is_some_and(|d| d.trim().is_empty()) => None,
Some(dir) => Some(PathBuf::from(dir)),
@@ -102,6 +124,37 @@ mod tests {
use super::*;
use std::cell::RefCell;
#[test]
fn portable_eframe_storage_is_a_file_inside_the_settings_directory() {
let exe = std::env::temp_dir().join(format!("cadcraft-env-portable-{}", std::process::id()));
std::fs::create_dir_all(&exe).unwrap();
std::fs::write(exe.join("portable.txt"), "").unwrap();
let vars = Env::from_vars_and_exe(env(&[("APPDATA", "/profile")]), Some(&exe));
assert_eq!(vars.config_dir, Some(exe.join("CADCraftData")));
let storage_file = vars.portable_storage_file.unwrap();
assert_eq!(storage_file, exe.join("CADCraftData").join("app.ron"));
assert_eq!(storage_file.parent(), vars.config_dir.as_deref());
std::fs::write(&storage_file, r#"{"window":"saved window state"}"#).unwrap();
let restarted = Env::from_vars_and_exe(env(&[("APPDATA", "/profile")]), Some(&exe));
assert_eq!(restarted.portable_storage_file.as_ref(), Some(&storage_file));
assert_eq!(std::fs::read_to_string(restarted.portable_storage_file.unwrap()).unwrap(), r#"{"window":"saved window state"}"#);
std::fs::remove_dir_all(exe).unwrap();
}
#[test]
fn explicit_override_skips_portable_probe() {
let exe = std::env::temp_dir().join(format!("cadcraft-env-override-{}", std::process::id()));
std::fs::create_dir_all(&exe).unwrap();
std::fs::write(exe.join("portable.txt"), "").unwrap();
for value in ["/custom", "", " "] {
let vars = Env::from_vars_and_exe(env(&[(CONFIG_DIR, value)]), Some(&exe));
assert_eq!(vars.config_dir, (!value.trim().is_empty()).then(|| PathBuf::from(value)));
assert_eq!(vars.portable_storage_file, None);
assert!(!exe.join("CADCraftData").exists());
}
std::fs::remove_dir_all(exe).unwrap();
}
fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v))
}
@@ -146,6 +199,7 @@ mod tests {
assert_eq!(
read,
Env {
portable_storage_file: None,
config_dir: Some(PathBuf::from("/private/cc")),
locale: Some("cs-CZ".into()),
vsync: Switch::On,
+36 -4
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;
@@ -23,6 +25,7 @@ mod launch_args;
mod logging;
#[cfg(target_os = "macos")]
mod native_menu;
mod portable;
#[cfg(target_os = "macos")]
mod sheet;
mod single_instance;
@@ -53,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 {
@@ -101,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
@@ -173,6 +182,9 @@ pub fn install_io() {
});
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
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 {
@@ -235,9 +247,12 @@ fn saved_window(app_ron: &str) -> bool {
/// The window state from the last session is saved and will be restored (#2595). A saved size
/// below the minimum (seen on Windows: 64×64 points, which eframe restores un-maximized and
/// unusable) is dropped first, so the window opens at its default size.
fn restores_window() -> bool {
let Some(path) = eframe::storage_dir(APP_ID).map(|dir| dir.join("app.ron")) else { return false };
/// unusable) is dropped first, so the window opens at its default size. `portable_file`: the
/// portable copy's settings file, read instead of the user profile's.
fn restores_window(portable_file: Option<&std::path::Path>) -> bool {
let Some(path) = portable_file.map(std::path::PathBuf::from).or_else(|| eframe::storage_dir(APP_ID).map(|dir| dir.join("app.ron"))) else {
return false;
};
let Ok(mut ron) = std::fs::read_to_string(&path) else { return false };
// Through a temporary file: a failed write (a full disk) keeps the other saved settings.
if let Some(fixed) = without_tiny_window(&ron)
@@ -391,7 +406,8 @@ fn main() -> eframe::Result {
// The crosshair is drawn by the app: present without a queue on Linux/BSD, where X11
// swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync).
wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface),
..window_options(restores_window(), stencil)
persistence_path: vars.portable_storage_file.clone(),
..window_options(restores_window(vars.portable_storage_file.as_deref()), stencil)
};
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
@@ -430,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,
@@ -493,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;
@@ -520,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);
}
+82
View File
@@ -0,0 +1,82 @@
//! Windows portable ZIP settings, selected by a marker beside the executable.
use std::io::Write as _;
use std::path::{Path, PathBuf};
/// A marker must be a file. Prove the data folder is writable before selecting it.
pub(crate) fn directory_in(exe_dir: &Path) -> std::io::Result<Option<PathBuf>> {
if !exe_dir.join("portable.txt").is_file() {
return Ok(None);
}
let data = exe_dir.join("CADCraftData");
std::fs::create_dir_all(&data)?;
let probe = data.join(format!(".portable-write-test-{}", std::process::id()));
// A byte, not just an empty file: a full drive can still make the file and refuse its data.
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
let written = file.write_all(&[0]).and_then(|()| file.sync_all());
drop(file);
let removed = std::fs::remove_file(&probe);
written?;
removed?;
Ok(Some(data))
}
#[cfg(test)]
mod tests {
use super::*;
struct Temp(PathBuf);
impl Temp {
fn new(name: &str) -> Self {
let root = std::env::temp_dir().join(format!("cadcraft-portable-{}-{name}", std::process::id()));
std::fs::create_dir_all(&root).unwrap();
Self(root)
}
}
impl Drop for Temp {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn absent_marker_and_directory_named_marker_do_not_enable_portable_mode() {
let temp = Temp::new("no-marker");
assert_eq!(directory_in(&temp.0).unwrap(), None);
std::fs::create_dir(temp.0.join("portable.txt")).unwrap();
assert_eq!(directory_in(&temp.0).unwrap(), None);
assert!(!temp.0.join("CADCraftData").exists());
}
#[test]
fn marker_selects_adjacent_data_and_preserves_existing_settings() {
let temp = Temp::new("settings-é");
std::fs::write(temp.0.join("portable.txt"), "").unwrap();
let data = directory_in(&temp.0).unwrap().unwrap();
assert_eq!(data, temp.0.join("CADCraftData"));
assert_eq!(std::fs::read_dir(&data).unwrap().count(), 0);
std::fs::write(data.join("workspace.json"), "existing settings").unwrap();
assert_eq!(directory_in(&temp.0).unwrap(), Some(data.clone()));
assert_eq!(std::fs::read_to_string(data.join("workspace.json")).unwrap(), "existing settings");
}
#[test]
fn blocked_data_folder_is_an_error() {
let temp = Temp::new("blocked");
std::fs::write(temp.0.join("portable.txt"), "").unwrap();
std::fs::write(temp.0.join("CADCraftData"), "a file blocks the directory").unwrap();
assert!(directory_in(&temp.0).is_err());
}
#[test]
fn independent_copies_have_independent_settings() {
let a = Temp::new("copy-a");
let b = Temp::new("copy-b");
for temp in [&a, &b] {
std::fs::write(temp.0.join("portable.txt"), "").unwrap();
}
assert_ne!(directory_in(&a.0).unwrap(), directory_in(&b.0).unwrap());
}
}
+36 -3
View File
@@ -331,16 +331,43 @@ mod tests {
}
}
/// A fresh folder for one test, and its socket path.
/// A fresh folder for one test, and its socket path. Both names stay short: a Windows socket path
/// holds at most 107 bytes, and a long `%TEMP%` already uses most of them.
#[cfg(windows)]
fn socket_dir(test: &str) -> (Cleanup, PathBuf) {
let dir = std::env::temp_dir().join(format!("cadcraft-single-instance-{}-{test}", std::process::id()));
let dir = std::env::temp_dir().join(format!("cc-si-{}-{test}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("instance-test.sock");
let path = dir.join("t.sock");
(Cleanup(dir), path)
}
/// Whether a socket can be bound at `path` here. It can't when `%TEMP%` is too long or lives
/// under a redirected `%LOCALAPPDATA%`; the socket tests then skip instead of failing.
#[cfg(windows)]
fn can_bind(path: &std::path::Path) -> bool {
let bound = uds_windows::UnixListener::bind(path)
.map(drop)
.map_err(|e| {
// Straight to stderr: the test harness hides `eprintln!` from a test that passes.
use std::io::Write;
let _ = writeln!(std::io::stderr(), "skipping: no AF_UNIX socket at {}: {e}", path.display());
})
.is_ok();
let _ = std::fs::remove_file(path);
bound
}
#[cfg(windows)]
#[test]
fn the_test_socket_path_stays_far_below_the_limit() {
// Its own folder, with a name as long as the longest one used here: `socket_dir` empties the
// folder, and the launches test may be using "together" at the same moment.
let (_dir, path) = socket_dir("lengthck");
let added = path.as_os_str().len() - std::env::temp_dir().as_os_str().len();
assert!(added <= 40, "{added} bytes on top of %TEMP%");
}
/// The whole exchange over a real socket: a stale socket file is taken over, a later launch
/// hands its files to that listener, one that asked for its own window gets it, and a request
/// naming a relative path is refused.
@@ -348,6 +375,9 @@ mod tests {
#[test]
fn a_later_launch_hands_its_files_to_the_first() {
let (dir, path) = socket_dir("handoff");
if !can_bind(&path) {
return;
}
drop(uds_windows::UnixListener::bind(&path).unwrap());
assert!(path.exists(), "the stale socket file stays behind");
@@ -369,6 +399,9 @@ mod tests {
fn launches_at_once_open_one_window() {
const LAUNCHES: usize = 6;
let (dir, path) = socket_dir("together");
if !can_bind(&path) {
return;
}
let start = Arc::new(std::sync::Barrier::new(LAUNCHES));
let launches: Vec<_> = (0..LAUNCHES)
.map(|i| {
+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
+99 -7
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.
@@ -85,6 +89,9 @@ pub struct Foreign {
/// The drawing's own `$ACADVER` is the version it is saved as, which SAVEAS changes, so a
/// later save must not take it for this one (#2471).
pub version: Option<String>,
/// The file's registered applications (APPID names as read, in file order). Saving writes
/// them all back, whether or not any xdata still names them.
pub appids: Vec<String>,
}
impl Foreign {
@@ -103,6 +110,7 @@ impl Foreign {
&& self.targets.is_empty()
&& self.class_order.is_empty()
&& self.data_store.is_empty()
&& self.appids.is_empty()
}
/// The entities with a geometry record in the data store: an `ACDSRECORD` naming the entity
@@ -126,22 +134,89 @@ pub fn sat_text_acis(u: &crate::Unknown, handle: Handle, stored: &std::collectio
["3DSOLID", "REGION", "BODY"].iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) && !stored.contains(&handle) && has_sat_text(&u.tags)
}
/// Whether a solid modeler entity can't be written to a DXF of 2013 and later (`modern`: SAT text
/// with no data store record, [`sat_text_acis`]) or of 2010 and earlier (geometry only in the data
/// store, which those files don't have, and no SAT text to write instead) (#2334).
pub fn acis_left_out(u: &crate::Unknown, handle: Handle, stored: &std::collections::BTreeSet<Handle>, modern: bool) -> bool {
if modern {
return sat_text_acis(u, handle, stored);
}
["3DSOLID", "REGION", "BODY"].iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) && stored.contains(&handle) && !has_sat_text(&u.tags)
}
/// The entities a DXF of 2013 or later leaves out because they hold SAT-text ACIS data
/// ([`sat_text_acis`]), counted by DXF type, across model space, layouts and block definitions.
pub fn sat_text_dropped(d: &crate::Drawing) -> BTreeMap<String, usize> {
acis_dropped(d, true)
}
/// The entities a DXF leaves out by [`acis_left_out`], counted like [`sat_text_dropped`].
pub fn acis_dropped(d: &crate::Drawing, modern: bool) -> BTreeMap<String, usize> {
let stored = d.foreign.data_store_entities();
let mut out = BTreeMap::new();
// The writer saves xrefs as references: their blocks (and `xref|` ones) hold nothing in the file.
for e in saved_entities(d) {
if let crate::EntityKind::Unknown(u) = &e.kind
&& acis_left_out(u, e.handle, &stored, modern)
{
count(&mut out, &u.dxf_type);
}
}
out
}
/// The entities a DXF file holds: model space, layouts and block definitions. The writer saves
/// xrefs as references: their blocks (and `xref|` ones) hold nothing in the file.
fn saved_entities(d: &crate::Drawing) -> impl Iterator<Item = &std::sync::Arc<crate::Entity>> {
let own_blocks = d.blocks.values().filter(|b| b.xref_path.is_none() && !xref_dependent(&b.name));
let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(own_blocks.map(|b| &b.entities));
for e in stores.flat_map(|s| s.iter()) {
if let crate::EntityKind::Unknown(u) = &e.kind
&& sat_text_acis(u, e.handle, &stored)
{
let n: &mut usize = out.entry(u.dxf_type.to_ascii_uppercase()).or_default();
*n = n.saturating_add(1);
stores.flat_map(|s| s.iter())
}
/// Add one record of DXF type `kind` to `out`.
fn count(out: &mut BTreeMap<String, usize>, kind: &str) {
let n: &mut usize = out.entry(kind.to_ascii_uppercase()).or_default();
*n = n.saturating_add(1);
}
/// Whether a DXF type is a proxy (ACAD_PROXY_OBJECT, ACAD_PROXY_ENTITY).
pub fn is_proxy(kind: &str) -> bool {
let k = kind.trim();
k.eq_ignore_ascii_case("ACAD_PROXY_OBJECT") || k.eq_ignore_ascii_case("ACAD_PROXY_ENTITY")
}
/// Whether a proxy's groups (after its type) give it a separate string stream: a size above 0 in
/// group 96 (2007) or 162 (2010 and later) after the `AcDbProxy…` marker. Before 2007 a proxy's
/// strings are part of its data, so a file of an earlier version has no form for one that keeps
/// them apart (#3229).
pub fn proxy_has_string_stream<S: AsRef<str>>(groups: impl IntoIterator<Item = (i32, S)>) -> bool {
let mut own = false;
for (code, value) in groups {
let v = value.as_ref().trim();
match code {
100 => own = own || v.to_ascii_lowercase().starts_with("acdbproxy"),
96 | 162 if own && v.parse::<i64>().is_ok_and(|n| n > 0) => return true,
_ => {}
}
}
false
}
/// The proxies a DXF earlier than 2007 leaves out because they have a separate string stream
/// ([`proxy_has_string_stream`]), counted by DXF type.
pub fn proxies_dropped_before_2007(d: &crate::Drawing) -> BTreeMap<String, usize> {
let mut out = BTreeMap::new();
let has_strings = |tags: &[RawTag]| proxy_has_string_stream(tags.iter().map(|t| (t.code, t.value.as_str())));
for e in saved_entities(d) {
if let crate::EntityKind::Unknown(u) = &e.kind
&& is_proxy(&u.dxf_type)
&& has_strings(&u.tags)
{
count(&mut out, &u.dxf_type);
}
}
for o in d.foreign.objects.iter().filter(|o| is_proxy(&o.kind) && has_strings(&o.tags)) {
count(&mut out, &o.kind);
}
out
}
@@ -164,6 +239,23 @@ pub fn data_store_records(tags: &[RawTag]) -> Vec<&[RawTag]> {
out
}
/// The ACIS version a modeler entity's SAT text declares (the first number of its first line:
/// 400, 700, 21800…), if it has SAT text.
pub fn sat_version(tags: &[RawTag]) -> Option<u32> {
let marked = tags.iter().take_while(|r| r.code < 1000).any(|r| r.code == 100);
let mut in_modeler = !marked;
for r in tags.iter().take_while(|r| r.code < 1000) {
if r.code == 100 {
in_modeler = r.value.trim().eq_ignore_ascii_case("AcDbModelerGeometry");
} else if in_modeler && r.code == 1 {
let first = r.value.split_whitespace().next()?;
// DXF before 2013 encodes SAT text: each character but a space is 159 minus it ("hoo" is 700).
return first.parse().ok().or_else(|| first.bytes().map(|b| char::from(159u8.wrapping_sub(b))).collect::<String>().parse().ok());
}
}
None
}
/// Whether an entity's groups hold SAT text: groups 1 and 3 inside its `AcDbModelerGeometry`
/// subclass. A file of a version before the subclass markers has no `100` groups: all of its
/// groups (before the extended data) are the entity's.
+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));
+14
View File
@@ -821,6 +821,18 @@ pub struct PageSetup {
/// save keeps where the sheet sits; `None` for a page CADCraft made, written as 0,0 (#2109).
#[serde(skip_serializing_if = "Option::is_none")]
pub image_origin: Option<Vec2>,
/// The plot layout flags (DXF group 70 of AcDbPlotSettings) as the file had them. Saving keeps
/// the bits CADCraft doesn't model (plot paper space last, plot with plot styles, standard
/// scale and the rest) as read instead of forcing its defaults (#3227); `None` for page setups
/// made in CADCraft.
#[serde(skip)]
pub file_plot_flags: Option<i64>,
/// The standard scale the file chose (DXF group 75, such as 25 for 1:50) and the plot scale it
/// was read with. While the scale is unchanged, saving keeps that choice and the standard scale
/// flag instead of writing the scale as a custom one; `None` for a custom scale, scaled to
/// fit, or a page setup made in CADCraft.
#[serde(skip)]
pub file_standard_scale: Option<(i64, f64)>,
}
impl Default for PageSetup {
@@ -844,6 +856,8 @@ impl Default for PageSetup {
paper_mm: None,
file_paper: None,
image_origin: None,
file_plot_flags: None,
file_standard_scale: 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;
+23 -17
View File
@@ -8,7 +8,7 @@ use cadcraft_geom::{Mat3, Vec2, Vec3};
use serde_json::{Value, json};
use super::super::curves::KW;
use super::super::file::{drops_unknown, new_folder, not_saved, not_saved_message, report_new_folder, report_not_saved};
use super::super::file::{Version, lost_message, lost_writing, new_folder, own_version, report_lost, report_new_folder};
use super::super::machines::{SelOutcome, SelectPhase};
use super::super::modify::erase_kept;
use super::super::{CommandSpec, bad, point_param, str_param, targets};
@@ -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
@@ -44,13 +46,14 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string();
let base = point_param(p, "base");
let folder = new_folder(&path);
let (entities, bytes, lost) = match str_param(p, "name") {
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)))?,
};
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
report_new_folder(s, &mut r, folder);
report_not_saved(s, &mut r, &lost);
report_lost(s, &mut r, &path, version, &lost);
Ok(r)
}
@@ -61,7 +64,7 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("-wblock", "`path` is required"))?.to_string();
let base = point_param(p, "base");
let folder = new_folder(&path);
let (entities, bytes, lost) = match str_param(p, "name") {
let (entities, bytes, lost, version) = match str_param(p, "name") {
Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?,
None => {
let hs = targets(s, p)?;
@@ -76,16 +79,17 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
};
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
report_new_folder(s, &mut r, folder);
report_not_saved(s, &mut r, &lost);
report_lost(s, &mut r, &path, version, &lost);
Ok(r)
}
/// Write `what` to `path` through the io hooks; the objects written, the file's size and what a
/// DWG file left out, for the caller to report as a save does. The
/// Write `what` to `path` through the io hooks; the objects written, the file's size, what the
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams) and
/// the version it was written at, for the caller to report as a save does. The
/// written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its units
/// ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches and
/// scaled on insert, and its defaults (text size, current styles, annotation scales).
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>)> {
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version)> {
let src = s.doc()?;
// The base point becomes the written drawing's origin: by default 0,0 for objects and the
// block's base point for a block.
@@ -108,13 +112,15 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi
crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?;
#[cfg(not(target_arch = "wasm32"))]
crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
let lost = if drops_unknown(path) { not_saved(&d) } else { BTreeMap::new() };
Ok((d.model.len(), bytes.len(), lost))
// The written drawing's own version: the writer is given no other.
let version = own_version(&d, path);
let lost = lost_writing(&d, path, version);
Ok((d.model.len(), bytes.len(), lost, version))
}
/// Say on the command line what the written DWG file left out.
fn echo_not_saved(s: &mut Session, lost: &BTreeMap<String, usize>) {
if let Some(msg) = not_saved_message(lost) {
/// Say on the command line what the file written at `path` and `version` left out.
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>) {
if let Some(msg) = lost_message(path, version, lost) {
s.echo(msg);
}
}
@@ -335,7 +341,7 @@ impl DashWblockM {
fn write(&self, s: &mut Session, what: Source) -> Result<Step> {
match write(s, "-wblock", &self.path, what) {
Ok((.., lost)) => echo_not_saved(s, &lost),
Ok((.., lost, version)) => echo_not_saved(s, &self.path, version, &lost),
Err(e) => s.echo(e.to_string()),
}
Ok(Step::Done)
@@ -346,8 +352,8 @@ impl DashWblockM {
return Ok(Step::Done);
}
match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) {
Ok((.., lost)) => {
echo_not_saved(s, &lost);
Ok((.., lost, version)) => {
echo_not_saved(s, &self.path, version, &lost);
erase(s, hs)?;
}
Err(e) => s.echo(e.to_string()),
+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),
}
+98 -21
View File
@@ -2,6 +2,7 @@ use super::{
Accept, Chain, Circle, Ellipse, EntityKind, Handle, Input, Interactive, Line, MAX_GEN, PolyVertex, Polyline, Prompt, Result, Session, Step,
Value, Vec2, added, bad, bool_or, curves, lwpoly, number, other, point_param, points_param, rect_vertices, shoelace, str_param,
};
use cadcraft_doc::RawTag;
// =====================================================================================
// REVCLOUD
@@ -20,6 +21,11 @@ fn default_arc_len(s: &Session) -> f64 {
d.map(|d| d.header.f64("REVCLOUDARCLEN", if metric { 15.0 } else { 0.5 })).unwrap_or(0.5).max(1e-6)
}
/// Maximum arc length remembered between REVCLOUD runs (CADCraft-only state, not an AutoCAD variable); never below `min`.
fn default_max_arc_len(s: &Session, min: f64) -> f64 {
s.doc().ok().map_or(min, |d| d.header.f64("CADCRAFT_REVCLOUDMAXARCLEN", min)).max(min)
}
/// Bulged closed polyline vertices for a revision cloud around `boundary`.
pub(crate) fn cloud_vertices(boundary: &[Vec2], arc_len: f64, per_edge: bool, reverse: bool) -> Option<Vec<PolyVertex>> {
let mut pts: Vec<Vec2> = Vec::new();
@@ -94,6 +100,38 @@ fn cloud_entity(vs: Vec<PolyVertex>, calligraphy: bool, arc_len: f64) -> EntityK
lwpoly(vs, true)
}
/// The application name of the xdata that marks a closed polyline as a revision cloud.
const REVCLOUD_APP: &str = "RevcloudProps";
/// Adds a revision cloud with its `RevcloudProps` xdata (how AutoCAD and other readers tell a
/// revision cloud from a polyline). Made from object `src`, the cloud takes the object's place
/// and properties.
fn add_cloud(s: &mut Session, vs: Vec<PolyVertex>, calligraphy: bool, arc_len: f64, src: Option<Handle>) -> Result<Handle> {
let h = s.add_entity(cloud_entity(vs, calligraphy, arc_len))?;
let mut common = match src {
Some(src) => curves::entity(s, src)?.common,
None => curves::entity(s, h)?.common,
};
let mut keep = true;
common.xdata.retain(|t| {
if t.code == 1001 {
keep = !t.value.trim().eq_ignore_ascii_case(REVCLOUD_APP);
}
keep
});
common.xdata.extend([
RawTag { code: 1001, value: REVCLOUD_APP.into() },
RawTag { code: 1070, value: "0".into() },
RawTag { code: 1040, value: arc_len.to_string() },
]);
let d = s.doc_mut()?;
d.modify_entity(h, |e| e.common = common)?;
if let Some(src) = src {
d.remove_entity(src);
}
Ok(h)
}
pub(super) fn run_revcloud(s: &mut Session, p: &Value) -> Result<Value> {
let arc_len = p.get("arcLength").and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0).unwrap_or_else(|| default_arc_len(s));
let reverse = bool_or(p, "reverse", false);
@@ -113,13 +151,7 @@ pub(super) fn run_revcloud(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("revcloud", "too many points"));
}
let vs = cloud_vertices(&pts, arc_len, per_edge, reverse).ok_or_else(|| bad("revcloud", "the boundary needs an area"))?;
let h = s.add_entity(cloud_entity(vs, calligraphy, arc_len))?;
if let Some(src) = src {
let common = curves::entity(s, src)?.common;
let d = s.doc_mut()?;
d.modify_entity(h, |e| e.common = common)?;
d.remove_entity(src);
}
let h = add_cloud(s, vs, calligraphy, arc_len, src)?;
added(h)
}
@@ -127,15 +159,31 @@ pub(super) struct RevcloudM {
kind: CloudKind,
pts: Vec<Vec2>,
arc_len: f64,
max_arc_len: f64,
asking_arc: bool,
asking_max: bool,
object: bool,
/// Outline of the picked object while "Reverse direction" is being asked.
picked: Option<(Handle, Vec<Vec2>)>,
calligraphy: bool,
asking_style: bool,
}
impl RevcloudM {
pub(super) fn new(s: &Session, kind: CloudKind) -> Self {
RevcloudM { kind, pts: Vec::new(), arc_len: default_arc_len(s), asking_arc: false, object: false, calligraphy: false, asking_style: false }
let arc_len = default_arc_len(s);
RevcloudM {
kind,
pts: Vec::new(),
arc_len,
max_arc_len: default_max_arc_len(s, arc_len),
asking_arc: false,
asking_max: false,
object: false,
picked: None,
calligraphy: false,
asking_style: false,
}
}
fn boundary(&self, extra: Option<Vec2>) -> Vec<Vec2> {
let mut pts = self.pts.clone();
@@ -151,7 +199,7 @@ impl RevcloudM {
let b = self.boundary(None);
match cloud_vertices(&b, self.arc_len, self.kind != CloudKind::Free, false) {
Some(vs) => {
s.add_entity(cloud_entity(vs, self.calligraphy, self.arc_len))?;
add_cloud(s, vs, self.calligraphy, self.arc_len, None)?;
s.echo("Revision cloud finished.");
Ok(Step::Done)
}
@@ -170,13 +218,19 @@ impl Interactive for RevcloudM {
CloudKind::Poly => "Polygonal",
CloudKind::Free => "Freehand",
};
s.echo(format!("Minimum arc length: {0:.4} Maximum arc length: {0:.4} Style: Normal Type: {t}", self.arc_len));
s.echo(format!("Minimum arc length: {0:.4} Maximum arc length: {1:.4} Style: Normal Type: {t}", self.arc_len, self.max_arc_len));
Ok(Step::Continue)
}
fn prompt(&self, _s: &Session) -> Prompt {
if self.picked.is_some() {
return Prompt::new("Reverse direction", curves::KW).kw(&["Yes", "No"]).default("No");
}
if self.asking_arc {
return Prompt::new("Specify minimum length of arc", Accept::NUMBER).default(format!("{:.4}", self.arc_len));
}
if self.asking_max {
return Prompt::new("Specify maximum length of arc", Accept::NUMBER).default(format!("{:.4}", self.max_arc_len));
}
if self.asking_style {
return Prompt::new("Select arc style", curves::KW).kw(&["Normal", "Calligraphy"]).default("Normal");
}
@@ -197,13 +251,34 @@ impl Interactive for RevcloudM {
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if let Some((h, pts)) = self.picked.take() {
let reverse = matches!(&i, Input::Keyword(k) | Input::Text(k) if k.to_ascii_lowercase().starts_with('y'));
let vs = cloud_vertices(&pts, self.arc_len, false, reverse).ok_or_else(|| other("The object has no area."))?;
add_cloud(s, vs, self.calligraphy, self.arc_len, Some(h))?;
s.echo("Revision cloud finished.");
return Ok(Step::Done);
}
if self.asking_arc {
if let Input::Text(t) = &i {
let v = number(t).filter(|v| *v > 0.0).ok_or_else(|| other("Requires a positive value."))?;
self.arc_len = v;
s.doc_mut()?.header.set_f64("REVCLOUDARCLEN", v);
self.max_arc_len = self.max_arc_len.max(v);
let max = self.max_arc_len;
let d = s.doc_mut()?;
d.header.set_f64("REVCLOUDARCLEN", v);
d.header.set_f64("CADCRAFT_REVCLOUDMAXARCLEN", max);
}
self.asking_arc = false;
self.asking_max = true;
return Ok(Step::Continue);
}
if self.asking_max {
if let Input::Text(t) = &i {
let v = number(t).filter(|v| *v >= self.arc_len).ok_or_else(|| other("Requires a value not less than the minimum arc length."))?;
self.max_arc_len = v;
s.doc_mut()?.header.set_f64("CADCRAFT_REVCLOUDMAXARCLEN", v);
}
self.asking_max = false;
return Ok(Step::Continue);
}
if self.asking_style {
@@ -214,17 +289,19 @@ impl Interactive for RevcloudM {
return Ok(Step::Continue);
}
if self.object {
let Input::Point(p) = i else { return if i == Input::Enter { Ok(Step::Cancel) } else { Ok(Step::Continue) } };
let h = curves::pick_at(s, p).ok_or_else(|| other("*Invalid selection*"))?;
let h = match i {
Input::Point(p) => curves::pick_at(s, p).ok_or_else(|| other("*Invalid selection*"))?,
Input::Pick(hs) => hs.first().copied().ok_or_else(|| other("*Invalid selection*"))?,
Input::Enter => return Ok(Step::Cancel),
_ => return Ok(Step::Continue),
};
let pts = object_outline(s, h)?;
let vs = cloud_vertices(&pts, self.arc_len, false, false).ok_or_else(|| other("The object has no area."))?;
let nh = s.add_entity(cloud_entity(vs, self.calligraphy, self.arc_len))?;
let common = curves::entity(s, h)?.common;
let d = s.doc_mut()?;
d.modify_entity(nh, |e| e.common = common)?;
d.remove_entity(h);
s.echo("Revision cloud finished.");
return Ok(Step::Done);
if cloud_vertices(&pts, self.arc_len, false, false).is_none() {
return Err(other("The object has no area."));
}
self.object = false;
self.picked = Some((h, pts));
return Ok(Step::Continue);
}
match i {
Input::Keyword(k) => {
+75 -2
View File
@@ -755,10 +755,44 @@ fn revcloud_json() {
assert!(s.execute("revcloud", &json!({"p1": [0, 0], "p2": [1e300, 1e300], "arcLength": 1e-300})).is_ok());
}
#[test]
fn revcloud_saves_revcloudprops_xdata() {
let mut s = Session::new();
let props = |s: &Session| {
let xd = s.doc().unwrap().model.last().unwrap().common.xdata.clone();
xd.iter().map(|t| (t.code, t.value.clone())).collect::<Vec<_>>()
};
let want = vec![(1001, "RevcloudProps".to_string()), (1070, "0".to_string()), (1040, "2".to_string())];
s.execute("revcloud", &json!({"p1": [0, 0], "p2": [100, 50], "arcLength": 2})).unwrap();
assert_eq!(props(&s), want);
let dxf = cadcraft_io::write_dxf(s.doc().unwrap());
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
let groups: Vec<(&str, &str)> = lines.chunks(2).filter_map(|c| Some((*c.first()?, *c.get(1)?))).collect();
assert!(groups.contains(&("1001", "RevcloudProps")), "no RevcloudProps xdata in the DXF");
let appid = groups
.iter()
.enumerate()
.any(|(i, g)| *g == ("0", "APPID") && groups[i + 1..].iter().take_while(|g| g.0 != "0").any(|g| *g == ("2", "RevcloudProps")));
assert!(appid, "no RevcloudProps APPID record");
// Made from an object: the object's properties are kept, the cloud is still a revision cloud.
let c = h(&s.execute("circle", &json!({"center": [10, 10], "radius": 1})).unwrap());
s.execute("revcloud", &json!({"handle": c, "arcLength": 2})).unwrap();
assert_eq!(props(&s), want);
// Interactive (the arc length takes a minimum and a maximum, #1714).
s.cmdline("revcloud a 2 2").unwrap();
s.cmdline("0,0 4,2").unwrap();
assert_eq!(props(&s), want);
// Interactive Object, after the "Reverse direction" prompt.
s.execute("rectang", &json!({"p1": [20, 20], "p2": [24, 22]})).unwrap();
s.cmdline("revcloud o 20,21 n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(props(&s), want);
}
#[test]
fn revcloud_command_line() {
let mut s = Session::new();
s.cmdline("revcloud a 1").unwrap();
s.cmdline("revcloud a 1 1").unwrap();
s.cmdline("0,0 4,2").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert!(matches!(last(&s), EntityKind::LwPolyline(p) if p.vertices.len() == 12));
@@ -771,11 +805,50 @@ fn revcloud_command_line() {
assert_eq!(kinds(&s).len(), 3);
// Object option converts a closed polyline.
s.execute("rectang", &json!({"p1": [10, 10], "p2": [12, 12]})).unwrap();
s.cmdline("revcloud o 10,11").unwrap();
s.cmdline("revcloud o 10,11 n").unwrap();
assert!(s.running.is_none());
assert_eq!(kinds(&s).len(), 4);
}
#[test]
fn revcloud_object_accepts_entity_name() {
let mut s = Session::new();
s.execute("rectang", &json!({"p1": [0, 0], "p2": [4, 4]})).unwrap();
let h = s.doc().unwrap().model.last().unwrap().handle;
s.cmdline("revcloud o").unwrap();
s.input(Input::Pick(vec![h])).unwrap();
// Object asks "Reverse direction" next (#1714); Enter keeps it.
s.input(Input::Enter).unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(kinds(&s).len(), 1);
assert!(matches!(last(&s), EntityKind::LwPolyline(p) if p.vertices.len() > 4));
}
#[test]
fn revcloud_arc_length_asks_max_and_object_asks_reverse() {
let mut s = Session::new();
s.execute("rectang", &json!({"p1": [10, 10], "p2": [12, 12]})).unwrap();
s.cmdline("revcloud a 200 800").unwrap();
assert!(s.prompt_text().contains("first corner"), "{}", s.prompt_text());
s.cmdline("0,0 2000,1000").unwrap();
assert!(s.running.is_none());
s.cmdline("revcloud").unwrap();
assert!(s.log.iter().any(|l| l.contains("Minimum arc length: 200.0000 Maximum arc length: 800.0000")), "{:?}", s.log);
s.cmdline("o").unwrap();
s.cmdline("10,11").unwrap();
assert!(s.running.is_some() && s.prompt_text().contains("Reverse direction"), "{}", s.prompt_text());
s.cmdline("n").unwrap();
assert!(s.running.is_none());
// Yes reverses the arcs (negative bulges).
s.execute("rectang", &json!({"p1": [30, 30], "p2": [32, 32]})).unwrap();
s.cmdline("revcloud o 30,31 y").unwrap();
assert!(s.running.is_none());
match last(&s) {
EntityKind::LwPolyline(p) => assert!(p.vertices.iter().all(|v| v.bulge < 0.0)),
k => panic!("{k:?}"),
}
}
// ---------------- BREAKLINE ----------------
fn breakline_points(s: &Session) -> Vec<(f64, f64)> {
+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()
+145 -43
View File
@@ -83,6 +83,40 @@ pub fn object_records() -> Option<ObjectRecords> {
OBJECT_RECORDS.get().copied()
}
/// What a DXF of a version before 2007 leaves out of a drawing because it has no form for a
/// proxy's separate string stream, counted by DXF type (installed by the app with the DXF writer,
/// a lower layer, which finds it by writing; see `cadcraft_io::proxies_lost`). Without it the
/// proxies themselves are counted ([`cadcraft_doc::foreign::proxies_dropped_before_2007`]).
pub type ProxiesLost = fn(&Drawing, Version) -> std::collections::BTreeMap<String, usize>;
static PROXIES_LOST: OnceLock<ProxiesLost> = OnceLock::new();
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> {
if version >= Version::R2007 {
return Default::default();
}
let d = d.committed();
match PROXIES_LOST.get() {
Some(f) => f(&d, version),
None => cadcraft_doc::foreign::proxies_dropped_before_2007(&d),
}
}
/// COMPARE (drawing comparison).
pub mod compare;
@@ -792,15 +826,23 @@ fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
/// The version a drawing is saved in at `path` when none is asked for: its `$ACADVER` (2018 by
/// default), and for DWG at least 2004 (the io layer's rule: R2000 DWG has no true colours).
fn drawing_version(s: &Session, path: &str) -> Version {
let v = s
.state()
.ok()
.and_then(|st| st.drawing().header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver))
.unwrap_or_default();
pub fn drawing_version(s: &Session, path: &str) -> Version {
let v = s.state().ok().and_then(|st| acadver(st.drawing())).unwrap_or_default();
if is_dxf(path) { v } else { v.max(Version::R2004) }
}
/// The version `d` is saved in at `path` when none is asked for, as [`drawing_version`] says for
/// the active drawing.
pub(crate) fn own_version(d: &Drawing, path: &str) -> Version {
let v = acadver(d).unwrap_or_default();
if is_dxf(path) { v } else { v.max(Version::R2004) }
}
/// The version `d`'s `$ACADVER` names.
fn acadver(d: &Drawing) -> Option<Version> {
d.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver)
}
/// `document.switch index`: require the index, cancel the running command, activate that drawing and bump the epoch even if it was already active (screenshot identity).
fn run_switch(s: &mut Session, p: &Value) -> Result<Value> {
let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("document.switch", "`index` is required"))? as usize;
@@ -826,8 +868,9 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len() });
if drops_unknown(format!("drawing.{fmt}")) {
report_not_saved(s, &mut r, &lost);
} else if version >= Version::R2013 && is_dxf_file(format!("drawing.{fmt}")) {
report_sat_text_dropped(s, &mut r);
} else if is_dxf_file(format!("drawing.{fmt}")) {
let lost = host_dxf_lost(s, version);
report_lost(s, &mut r, "drawing.dxf", version, &lost);
}
Ok(r)
}
@@ -862,10 +905,12 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap
let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities));
for e in stores.flat_map(|s| s.iter()) {
if let cadcraft_doc::EntityKind::Unknown(u) = &e.kind {
// A DWG before 2013 writes a solid's SAT text as it is; from 2013 the geometry has to be
// in the data store, and SAT text alone is lost (#2334).
// A DWG before 2013 keeps a solid's SAT text of ACIS 7.0 and later; from 2013 the geometry
// has to be in the data store, and SAT text alone is lost. Older SAT (ACIS 4.0, as ZWCAD
// writes to DXF 2000) reaches the DWG without usable geometry: ZWCAD 2025 opens such a
// solid as a proxy or an empty body (#2334).
if MODELER_TYPES.iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t))
&& (stored.contains(&e.handle) || (version < Version::R2013 && cadcraft_doc::foreign::has_sat_text(&u.tags)))
&& (stored.contains(&e.handle) || (version < Version::R2013 && cadcraft_doc::foreign::sat_version(&u.tags).is_some_and(|v| v >= 700)))
{
continue;
}
@@ -887,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
}
@@ -907,9 +958,8 @@ pub fn not_saved_message(lost: &std::collections::BTreeMap<String, usize>) -> Op
/// reports the same list afterwards to callers that never get a dialog.
pub fn loss_on_save(s: &Session, path: &str) -> std::collections::BTreeMap<String, usize> {
let version = drawing_version(s, path);
if is_dxf_file(path) && version >= Version::R2013 {
// The drawing a file holds: the host while the Block Editor is open.
return s.state().map(|st| cadcraft_doc::foreign::sat_text_dropped(st.drawing())).unwrap_or_default();
if is_dxf_file(path) {
return host_dxf_lost(s, version);
}
if !drops_unknown(path) {
return Default::default();
@@ -917,16 +967,85 @@ pub fn loss_on_save(s: &Session, path: &str) -> std::collections::BTreeMap<Strin
s.doc().map(|d| not_saved_as(d, version)).unwrap_or_default()
}
/// Report what the file `path`, just written at the drawing's own version, left out.
pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
if is_dxf_file(path) {
if drawing_version(s, path) >= Version::R2013 {
report_sat_text_dropped(s, r);
}
} else {
let lost = loss_on_save(s, path);
report_not_saved(s, r, &lost);
/// What a DXF of `version` leaves out of the drawing a save writes: the host while the Block
/// Editor is open ([`dxf_lost`]).
fn host_dxf_lost(s: &Session, version: Version) -> std::collections::BTreeMap<String, usize> {
s.state().map(|st| dxf_lost(st.drawing(), version)).unwrap_or_default()
}
/// What a DXF of `version` leaves out of `d`: solid modeler entities whose ACIS geometry that
/// version has no place for (#2334: SAT text alone from 2013, data store geometry alone before),
/// and before 2007 proxies whose strings it can't hold, with the objects that go with them
/// (#3229). The two never name the same record: a solid lost before 2013 is lost in 2007 too.
fn dxf_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
let mut lost = cadcraft_doc::foreign::acis_dropped(d, version >= Version::R2013);
for (kind, n) in proxies_lost(d, version) {
let m = lost.entry(kind).or_insert(0);
*m = m.saturating_add(n);
}
lost
}
/// What a file at `path` leaves out of `d`, written at `version`: empty when it keeps everything.
pub(crate) fn lost_writing(d: &Drawing, path: &str, version: Version) -> std::collections::BTreeMap<String, usize> {
if !is_dxf_file(path) {
return if drops_unknown(path) { not_saved_as(d, version) } else { Default::default() };
}
dxf_lost(d, version)
}
/// Report what the file `path`, just written from the active document (what EXPORT writes: the
/// block while the Block Editor is open) at its own version, left out.
pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
let Ok(d) = s.doc() else { return };
let version = own_version(d, path);
let lost = lost_writing(d, path, version);
report_lost(s, r, path, version, &lost);
}
/// Say on the command line what the file `path`, written at `version`, couldn't keep (`lost`),
/// in the words for that kind of file, and list it in the result's `notSaved`.
pub(crate) fn report_lost(s: &mut Session, r: &mut Value, path: &str, version: Version, lost: &std::collections::BTreeMap<String, usize>) {
match lost_message(path, version, lost) {
Some(msg) => s.echo(msg),
None => return,
}
if let Some(o) = r.as_object_mut() {
o.insert("notSaved".into(), json!(lost));
}
}
/// The command-line warning for what a file at `path` written at `version` left out, or `None`
/// when it kept everything.
pub(crate) fn lost_message(path: &str, version: Version, lost: &std::collections::BTreeMap<String, usize>) -> Option<String> {
if !is_dxf_file(path) {
return not_saved_message(lost);
}
if lost.is_empty() {
return None;
}
// Solids (#2334) and, before 2007, proxies and what goes with them (#3229), each with its reason.
let list = |solids: bool| -> Vec<String> {
lost.iter().filter(|(t, _)| MODELER_TYPES.iter().any(|m| t.eq_ignore_ascii_case(m)) == solids).map(|(t, n)| format!("{n} {t}")).collect()
};
let mut parts = Vec::new();
let solids = list(true);
if !solids.is_empty() {
let why = if version >= Version::R2013 {
"2013 and later keep ACIS geometry in a data store these entities have no record in; save as 2010 or earlier to keep them"
} else {
"2010 and earlier have no data store, where these entities keep their ACIS geometry; save as 2013 or later to keep them"
};
parts.push(format!("Not saved in the DXF file ({why}): {}", solids.join(", ")));
}
let others = list(false);
if !others.is_empty() {
parts.push(format!(
"Not saved in the DXF file (proxies that keep their strings apart from their data, which DXF before 2007 can't hold, and the objects that go with them; save as 2007 or later to keep them): {}",
others.join(", ")
));
}
Some(parts.join(" "))
}
/// Whether saving to `path` leaves out the entities [`not_saved`] counts: DWG does (the DWG
@@ -945,24 +1064,6 @@ fn is_dxf_file(path: impl AsRef<std::path::Path>) -> bool {
Format::from_path(path) == Some(Format::Dxf)
}
/// Say on the command line which solid modeler entities a DXF of 2013 or later left out because
/// they hold SAT-text ACIS data, which such files keep in a data store instead (#2334).
fn report_sat_text_dropped(s: &mut Session, r: &mut Value) {
// The drawing a file holds: the host while the Block Editor is open.
let lost = s.state().map(|st| cadcraft_doc::foreign::sat_text_dropped(st.drawing())).unwrap_or_default();
if lost.is_empty() {
return;
}
let list: Vec<String> = lost.iter().map(|(t, n)| format!("{n} {t}")).collect();
s.echo(format!(
"Not saved in the DXF file (2013 and later keep ACIS geometry in a data store these entities have no record in; save as 2010 or earlier to keep them): {}",
list.join(", ")
));
if let Some(o) = r.as_object_mut() {
o.insert("notSaved".into(), json!(lost));
}
}
/// The folder a write to `path` has to create, asked before writing so it can be reported after.
/// The web has no folders.
pub(super) fn new_folder(path: &str) -> Option<String> {
@@ -1006,8 +1107,9 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R
report_new_folder(s, &mut r, folder);
if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) {
report_not_saved(s, &mut r, &lost);
} else if version >= Version::R2013 && r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) {
report_sat_text_dropped(s, &mut r);
} else if r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) {
let lost = host_dxf_lost(s, version);
report_lost(s, &mut r, "drawing.dxf", version, &lost);
}
if r.get("path").and_then(Value::as_str).is_some_and(is_drawing_file) {
report_fonts(s, &mut r);
+13 -4
View File
@@ -1,4 +1,5 @@
//! HATCH, GRADIENT, BOUNDARY, REGION: boundaries from pick points or selected closed objects.
//! HATCHGENERATEBOUNDARY: polylines around existing hatches.
mod patfile;
pub(super) use edit::{set_pattern, takes_pattern};
@@ -36,6 +37,9 @@ pub fn specs() -> Vec<CommandSpec> {
// Typed with nothing selected it asks for objects, as in AutoCAD, rather than converting none.
.interactive(|_| Ok(Box::new(SelectRun::new("region", "REGION")))),
CommandSpec::new("hatchedit", "Hatch Edit", edit::run_hatchedit).menu(&["Modify", "Object", "Hatch..."]).alias(&["he", "-hatchedit"]).params("{handles?, pattern?, scale?, angle?, gradient?: {name?, color1?, color2?, angle? (degrees), centered?} (makes or changes a gradient fill; `pattern` turns it back), associative?: bool (false unlinks; true links each loop to a closed object of the same shape, or to `boundary` objects), boundary?: [hex], addPoints?: [[x,y]], addBoundary?: [hex], removeLoops?: [zero-based index] (geometry edits require one hatch), style?, origin? | originMode?, separate?: true, recreate?: \"polyline\"|\"region\", associate?: bool (link to the recreated boundary)}").interactive(|s| Ok(Box::new(edit::HatchEditM::new(s)))),
CommandSpec::new("hatchgenerateboundary", "Generate Boundary", edit::run_hatchgenerateboundary)
.params("{handles?} (a closed polyline around each boundary loop of the hatches, which stay as they are) → handles")
.interactive(|_| Ok(Box::new(SelectRun::new("hatchgenerateboundary", "HATCHGENERATEBOUNDARY")))),
CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick)
.params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing")
.enabled(has_doc)
@@ -228,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() {
@@ -244,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] });
}
}
}
@@ -256,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)
@@ -267,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 => {}
+53
View File
@@ -29,6 +29,59 @@ fn hatches(s: &Session, p: &Value) -> Result<Vec<Handle>> {
Ok(out)
}
/// Most polylines one HATCHGENERATEBOUNDARY call creates.
const MAX_GENERATED: usize = 10_000;
/// HATCHGENERATEBOUNDARY: a closed polyline around every boundary loop (outer and islands) of
/// the selected hatches, at each hatch's height. The hatches are not changed: an associative
/// hatch stays linked to its own boundary objects and is not linked to the new polylines.
pub(super) fn run_hatchgenerateboundary(s: &mut Session, p: &Value) -> Result<Value> {
let selected = targets(s, p)?;
// The polylines go to the current space, so every hatch must be there too.
let space = s.space();
let mut loops = Vec::new();
let mut found = false;
// A hatch named twice gets its boundary once.
let mut seen = std::collections::HashSet::new();
{
let d = s.doc()?;
for h in selected {
let Some(e) = d.entity(h) else { continue };
let EntityKind::Hatch(x) = &e.kind else { continue };
if !seen.insert(h) {
continue;
}
found = true;
if d.space_of(h).as_ref() != Some(&space) {
return Err(bad("hatchgenerateboundary", format!("hatch {} is not in the current space; switch to its layout first", h.hex())));
}
// Every selected hatch counts: none is left out of a call that succeeds. Compared
// against the room left, so a hostile loop count can't overflow the sum.
if x.loops.len() > MAX_GENERATED.saturating_sub(loops.len()) {
return Err(bad("hatchgenerateboundary", format!("more than {MAX_GENERATED} boundary polylines in one call; select fewer hatches")));
}
// The elevation runs along the hatch's normal: one facing down Z (mirrored) lies at its
// negative, where the polyline, facing up, goes.
let z = if e.common.extrusion.z < 0.0 { -x.elevation } else { x.elevation };
loops.extend(x.loops.iter().map(|l| (l.vertices.clone(), z)));
}
}
if !found {
return Err(bad("hatchgenerateboundary", "select one or more hatches"));
}
// Everything is checked before anything is added, so a refused call leaves nothing behind.
let mut created = Vec::new();
for (vs, elevation) in loops {
let mut kind = lwpoly(vs, true);
if let EntityKind::LwPolyline(pl) = &mut kind {
pl.elevation = elevation;
}
created.push(s.add_entity(kind)?.hex());
}
let n = created.len();
Ok(json!({ "handles": created, "message": format!("{n} boundary polyline(s) created.") }))
}
fn outline(l: &HatchLoop) -> Vec<Vec2> {
Polyline { vertices: l.vertices.clone(), closed: true }.tessellate(1e-3)
}
+99 -15
View File
@@ -18,6 +18,90 @@ fn text_of(k: &EntityKind) -> Option<String> {
}
}
/// A box for the in-place editor showing one line of text where `t` sits.
pub(crate) fn line_box(t: &cadcraft_doc::Text) -> cadcraft_doc::MText {
use cadcraft_doc::{HAlign, VAlign};
let col = match t.halign {
HAlign::Left => 0u8,
HAlign::Right => 2,
_ => 1,
};
let row = match t.valign {
VAlign::Top => 0u8,
VAlign::Middle => 1,
_ if t.halign == HAlign::Middle => 1,
_ => 2,
};
// Aligned and fit text is centred between its two points.
let at = match t.halign {
HAlign::Aligned | HAlign::Fit => t.align_pt.map_or(t.insert, |b| (t.insert + b) * 0.5),
_ => t.justify_point().to3(t.insert.z),
};
cadcraft_doc::MText {
insert: at,
height: t.height,
width: 0.0,
attach: row * 3 + col + 1,
rotation: t.rotation,
style: t.style.clone(),
contents: t.value.clone(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
}
}
/// The extents of one line of text as drawn (`value` in `t`'s place, style and justification);
/// `None` for empty or unusable extents.
fn drawn(d: &cadcraft_doc::Drawing, t: &cadcraft_doc::Text, value: &str) -> Option<cadcraft_geom::Bounds2> {
let (_, b) = cadcraft_render::place_text_entity(d, t, value);
let ok = [b.min.x, b.min.y, b.max.x, b.max.y].iter().all(|v| v.is_finite()) && b.min.x <= b.max.x && b.min.y <= b.max.y;
ok.then_some(b)
}
/// What the in-place editor edits for object `h`: an MTEXT or multileader text as multiline
/// text, a TEXT or attribute definition as one line, a dimension's text with `<>` for its value.
pub(crate) fn editor_for(s: &Session, h: Handle) -> Option<crate::TextEditor> {
use crate::{EditorKind, TextEditor};
let d = s.doc().ok()?;
let key = h.hex();
let e: &cadcraft_doc::Entity = d.entity(h)?;
// Annotative text and dimensions are drawn scaled to the current annotation scale: the box
// follows what is drawn. Multiline text keeps its stored height (it is written back from it).
let scaled = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Scaled(f) if matches!(e.kind, EntityKind::Text(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_)) => {
Some(cadcraft_doc::anno_scaled(e, f))
}
_ => None,
};
match &scaled.as_ref().unwrap_or(e).kind {
EntityKind::MText(t) => Some(TextEditor { mtext: t.clone(), kind: EditorKind::MText, key, extents: None }),
// A multileader's text opens in the same editor (#1081).
EntityKind::MLeader(m) => m.text.clone().map(|mtext| TextEditor { mtext, kind: EditorKind::MText, key, extents: None }),
// The box covers the text as drawn: its value, or a definition's tag.
EntityKind::Text(t) => Some(TextEditor { mtext: line_box(t), kind: EditorKind::Line, key, extents: drawn(d, t, &t.value) }),
EntityKind::AttDef(a) => Some(TextEditor { mtext: line_box(&a.text), kind: EditorKind::Line, key, extents: drawn(d, &a.text, &a.tag) }),
EntityKind::Dimension(dm) => {
let g = cadcraft_render::dimension_in(d, dm);
let measured = cadcraft_render::dimension_in(d, &cadcraft_doc::Dimension { text: String::new(), block: None, ..dm.clone() }).value;
let mtext = cadcraft_doc::MText {
insert: g.text_pos.to3(0.0),
height: if g.text_height > 0.0 && g.text_height.is_finite() { g.text_height } else { 0.18 },
width: 0.0,
attach: 5,
rotation: if g.text_angle.is_finite() { g.text_angle } else { 0.0 },
style: d.dim_style(&dm.style).map_or_else(|| "Standard".to_string(), |st| st.text_style.clone()),
contents: if dm.text.is_empty() { "<>".into() } else { dm.text.clone() },
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
};
Some(TextEditor { mtext, kind: EditorKind::Dimension { measured }, key, extents: None })
}
_ => None,
}
}
pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str) -> Result<()> {
if curves::is_locked(s, h) {
return Err(other("The object is on a locked layer."));
@@ -60,8 +144,8 @@ pub(super) struct TextEditM {
single: bool,
/// Asking for the edit mode.
mode: bool,
/// The MTEXT being edited, for the in-place editor (#842).
mtext: Option<cadcraft_doc::MText>,
/// What the in-place editor shows for the picked object (#842).
editor: Option<crate::TextEditor>,
}
impl Interactive for TextEditM {
@@ -70,7 +154,12 @@ impl Interactive for TextEditM {
}
/// An MTEXT asking for its new text opens in the in-place editor with its contents.
fn editing_mtext(&self) -> Option<cadcraft_doc::MText> {
self.h.as_ref().and(self.mtext.clone())
self.h.as_ref().and(self.editor.as_ref().filter(|e| e.kind == crate::EditorKind::MText).map(|e| e.mtext.clone()))
}
/// TEXT, an attribute definition or a dimension asking for its new text opens in the one-line
/// in-place editor; MTEXT and multileader text in the MTEXT editor.
fn text_editor(&self) -> Option<crate::TextEditor> {
if self.mode || self.h.is_none() { None } else { self.editor.clone() }
}
fn prompt(&self, _s: &Session) -> Prompt {
if self.mode {
@@ -100,18 +189,13 @@ impl Interactive for TextEditM {
if curves::is_locked(s, h) {
return Err(other("The object is on a locked layer."));
}
let kind = curves::entity(s, h)?.kind;
let old = text_of(&kind).ok_or_else(|| other("Select a text, mtext, multileader, attribute definition or dimension."))?;
self.mtext = match kind {
EntityKind::MText(m) => Some(m),
// A multileader's text opens in the same editor (#1081).
EntityKind::MLeader(m) => m.text,
_ => None,
};
let old = text_of(&curves::entity(s, h)?.kind)
.ok_or_else(|| other("Select a text, mtext, multileader, attribute definition or dimension."))?;
self.editor = editor_for(s, h);
// The editor would drop part of a text this long, and saving would lose it: the
// command line asks for it instead.
if self.mtext.as_ref().is_some_and(|m| !crate::mtext_edit::Formatted::fits(&m.contents)) {
self.mtext = None;
if self.editor.as_ref().is_some_and(|e| !crate::mtext_edit::Formatted::fits(&e.mtext.contents)) {
self.editor = None;
s.echo("This text is too long for the editor; enter the new text at the command line.");
}
self.h = Some((h, old));
@@ -123,12 +207,12 @@ impl Interactive for TextEditM {
set_text(s, h, &t)?;
self.edits.push((h, before));
self.h = None;
self.mtext = None;
self.editor = None;
Ok(if self.single { Step::Done } else { Step::Continue })
}
(Some(_), Input::Enter) => {
self.h = None;
self.mtext = None;
self.editor = None;
Ok(if self.single { Step::Done } else { Step::Continue })
}
(None, Input::Enter) => Ok(Step::Done),
+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> {
+71 -6
View File
@@ -67,7 +67,12 @@ pub fn specs() -> Vec<CommandSpec> {
.params("{delta: [dx,dy]} | {from, to} | {center}")
.noundo()
.transparent()
.interactive(|_| Ok(Box::new(PanM::default()))),
.interactive(|_| Ok(Box::new(PanM))),
CommandSpec::new("-pan", "Pan", run_pan)
.params("{delta: [dx,dy]} | {from, to} | {center}")
.noundo()
.transparent()
.interactive(|_| Ok(Box::new(PanPointsM::default()))),
CommandSpec::new("pan.left", "Pan Left", |s, _| pan_frac(s, Vec2::new(-0.25, 0.0))).menu(&["View", "Pan", "Left"]).noundo().transparent(),
CommandSpec::new("pan.right", "Pan Right", |s, _| pan_frac(s, Vec2::new(0.25, 0.0))).menu(&["View", "Pan", "Right"]).noundo().transparent(),
CommandSpec::new("pan.up", "Pan Up", |s, _| pan_frac(s, Vec2::new(0.0, 0.25))).menu(&["View", "Pan", "Up"]).noundo().transparent(),
@@ -601,6 +606,26 @@ impl Session {
self.touch();
Ok(())
}
/// PAN is in its realtime mode: the UI turns left-button drags into [`Session::realtime_pan`].
pub fn realtime_pan_active(&self) -> bool {
self.running.as_ref().is_some_and(|r| r.id == "pan") && self.current_prompt().is_some_and(|p| p.message == REALTIME_PAN_PROMPT)
}
/// One step of a realtime pan drag of `dx`, `dy` screen pixels (y down): the drawing follows
/// the cursor. Does nothing outside realtime PAN.
pub fn realtime_pan(&mut self, dx: f64, dy: f64) -> Result<()> {
if !self.realtime_pan_active() || !dx.is_finite() || !dy.is_finite() {
return Ok(());
}
let px = self.viewport_px.1.max(1.0);
let st = self.state_mut()?;
let v = st.view();
let scale = px / v.height;
// A twisted view (DVIEW TWist) turns the screen drag into the drawing's axes.
// Only the view moves, as with a middle-button drag: no new revision, so the canvas keeps
// its display list and does not rebuild the drawing's geometry on every frame.
st.set_view_quiet(View { center: v.center - Vec2::new(dx / scale, -dy / scale).rotate(-v.twist), ..v });
Ok(())
}
/// The zoom of a mouse wheel scroll by `delta` points (up zooms in): ZOOMFACTOR scales it
/// (60, the default, zooms about 18% per wheel step).
pub fn wheel_zoom_factor(&self, delta: f64) -> f64 {
@@ -612,15 +637,47 @@ impl Session {
}
}
#[derive(Default)]
struct PanM {
first: Option<Vec2>,
}
/// The prompt of realtime PAN; [`Session::realtime_pan_active`] recognises the mode by it.
const REALTIME_PAN_PROMPT: &str = "Drag to pan; press Esc or Enter to exit";
/// PAN: realtime. Dragging with the left button moves the drawing with the cursor until Esc or
/// Enter; the whole session is one Zoom Previous entry.
struct PanM;
impl Interactive for PanM {
fn name(&self) -> &'static str {
"PAN"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
let st = s.state_mut()?;
let v = st.view();
st.view_history.push(v);
if st.view_history.len() > 50 {
st.view_history.remove(0);
}
Ok(Step::Continue)
}
fn prompt(&self, _s: &Session) -> Prompt {
Prompt::new(REALTIME_PAN_PROMPT, Accept { enter: true, ..Accept::default() })
}
fn input(&mut self, _s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Enter => Ok(Step::Done),
_ => Ok(Step::Continue),
}
}
}
/// -PAN: a base point and a second point, or a displacement (a point, then Enter).
#[derive(Default)]
struct PanPointsM {
first: Option<Vec2>,
}
impl Interactive for PanPointsM {
fn name(&self) -> &'static str {
"-PAN"
}
fn prompt(&self, _s: &Session) -> Prompt {
match self.first {
None => Prompt::new("Specify base point or displacement (drag with the middle mouse button for realtime pan)", Accept::POINT),
@@ -637,7 +694,15 @@ impl Interactive for PanM {
run_pan(s, &json!({ "from": [a.x, a.y], "to": [b.x, b.y] }))?;
Ok(Step::Done)
}
(_, Input::Enter) => Ok(Step::Done),
// Enter at the second point: the first point is the displacement, as typed in the
// current UCS. The point arrives in world coordinates, so take the UCS origin off
// (0,0 in a moved UCS does not pan).
(Some(p), Input::Enter) => {
let d = p - s.input_ucs().origin.xy();
run_pan(s, &json!({ "delta": [d.x, d.y] }))?;
Ok(Step::Done)
}
(None, Input::Enter) => Ok(Step::Done),
_ => Ok(Step::Continue),
}
}
@@ -123,6 +123,7 @@ pub const NO_FILES: &[&str] = &[
"zoom.extents",
"zoom.object",
"pan",
"-pan",
"pan.left",
"pan.right",
"pan.up",
@@ -234,7 +235,9 @@ pub const NO_FILES: &[&str] = &[
"boundary",
"region",
"hatchedit",
"hatchgenerateboundary",
"hatchpick",
"wblockpick",
"overkill",
"block",
"-block",
+9
View File
@@ -110,6 +110,15 @@ impl Interactive for Guarded {
None
})
}
fn text_editor(&self) -> Option<crate::TextEditor> {
if self.broken.get().is_some() {
return None;
}
catch_unwind(AssertUnwindSafe(|| self.inner.text_editor())).unwrap_or_else(|_| {
self.broken.set(Some("panic in prompt"));
None
})
}
fn display_only(&self, s: &Session) -> Option<crate::prompt::DisplayOnly> {
if self.broken.get().is_some() {
return None;
+5 -1
View File
@@ -52,9 +52,10 @@ 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, Input, Interactive, Picker, Prompt, Step};
pub use prompt::{Accept, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
mod doc_state;
mod error;
@@ -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.
+34 -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
@@ -338,6 +338,11 @@ pub trait Interactive: Send {
fn editing_mtext(&self) -> Option<cadcraft_doc::MText> {
None
}
/// The text the in-place editor edits: where, how, its current contents and what kind of
/// object holds it. By default the new multiline text of [`Interactive::editing_mtext`].
fn text_editor(&self) -> Option<TextEditor> {
self.editing_mtext().map(|mtext| TextEditor { mtext, kind: EditorKind::NewMText, key: String::new(), extents: None })
}
/// What the drawing area shows in place of the drawing while the command runs (DVIEW draws
/// only its preview set); `None` shows the drawing.
fn display_only(&self, _s: &Session) -> Option<DisplayOnly> {
@@ -356,6 +361,34 @@ pub struct DisplayOnly {
pub extra: Vec<cadcraft_doc::Entity>,
}
/// What the in-place text editor edits ([`Interactive::text_editor`]). The editor answers the
/// command's text prompt with the new contents (`Input::Text`), or Enter to keep the old text.
#[derive(Clone, Debug, PartialEq)]
pub struct TextEditor {
/// Where the box sits (insertion point, attachment, rotation), its width (0: grows with the
/// text), text height and style; `contents` is the text to start from.
pub mtext: cadcraft_doc::MText,
pub kind: EditorKind,
/// Which object is being edited: a new key means a new text to load.
pub key: String,
/// The drawn text's extents in drawing units, when known (one line of text): the box covers
/// them, whatever the justification.
pub extents: Option<cadcraft_geom::Bounds2>,
}
/// The kind of text the in-place editor edits.
#[derive(Clone, Debug, PartialEq)]
pub enum EditorKind {
/// Multiline text being created (MTEXT).
NewMText,
/// Existing multiline text: an MTEXT, a multileader's text.
MText,
/// One line of plain text (TEXT, attribute definition): no formatting, Enter finishes.
Line,
/// A dimension's text: `<>` stands for the measured value, shown as `measured`.
Dimension { measured: String },
}
/// See [`Interactive::drag`].
#[derive(Clone, Debug)]
pub struct Drag {
+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 != ' ');
+5
View File
@@ -536,6 +536,11 @@ impl Session {
self.running.as_ref().and_then(|r| r.machine.editing_mtext())
}
/// The text the running command edits in place ([`Interactive::text_editor`]).
pub fn text_editor(&self) -> Option<crate::TextEditor> {
self.running.as_ref().and_then(|r| r.machine.text_editor())
}
pub fn current_prompt(&self) -> Option<Prompt> {
if let Some(p) = self.lisp_prompt() {
return Some(p);
+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();
+2
View File
@@ -60,6 +60,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
("HPNAME", Kind::Pattern, Def::Str("ANSI31")),
("HPSCALE", Kind::Real { min: 0.0, strict: true }, Def::Real(1.0)),
("INSNAME", Kind::Name, Def::Str("")),
// Percent that objects on locked layers fade on screen; 0 or negative: no fade.
("LAYLOCKFADECTL", Kind::Int(-90, 90), Def::Int(50)),
("LWDEFAULT", Kind::Choice(&LINEWEIGHTS), Def::Int(25)),
// Negative: Through (OFFSET picks a point).
("OFFSETDIST", Kind::AnyReal, Def::Real(-1.0)),
+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");
+21
View File
@@ -336,3 +336,24 @@ fn annotative_mtext_columns_follow_the_scale() {
assert_eq!((t.height, t.width, c.count, c.gutter, c.height, c.heights), (2.0, 20.0, 2, 2.0, 40.0, vec![6.0, 10.0]));
}
}
/// TEXTEDIT's in-place box for annotative text at a non-unit annotation scale has the height and
/// extents of the text as drawn (scaled), not as stored (#842 review).
#[test]
fn the_text_edit_box_of_annotative_text_is_as_drawn() {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let r = s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
let drawn = drawn_height(s.doc().unwrap(), h).unwrap();
assert!(drawn > 5.0, "drawn {drawn}");
s.cmdline("TEXTEDIT").unwrap();
s.input(cadcraft_engine::Input::Point(cadcraft_engine::geom::Vec2::new(0.0, 0.0))).unwrap();
let ed = s.text_editor().expect("the editor opens on the text");
assert!((ed.mtext.height - 12.5).abs() < 1e-9, "box height {}", ed.mtext.height);
let b = ed.extents.unwrap();
// The text's layout box (cell height), so a little taller than the strokes, never the
// stored 0.25-high text's.
assert!(b.height() >= drawn * 0.95 && b.height() <= drawn * 2.0, "box extents {} vs drawn {drawn}", b.height());
}
@@ -65,6 +65,7 @@ fn baseline(d: &Drawing, t: &Text) -> cadcraft_geom::Vec2 {
#[test]
fn all_attribute_value_paths_refresh_small_justified_export_changes() {
cadcraft_io::dwg_worker::allow_in_process();
for path in ["json", "interactive", "global-json", "global-interactive"] {
let (mut s, a, b) = fixture();
let before = attributes(s.doc().unwrap(), a);
@@ -147,6 +148,7 @@ fn equal_attribute_values_preserve_an_imported_font_baseline() {
/// Recomputing a justified baseline must not replace its independent insertion elevation.
#[test]
fn value_edits_preserve_distinct_insertion_and_alignment_elevations_on_export() {
cadcraft_io::dwg_worker::allow_in_process();
let (mut s, a, _) = fixture();
s.doc_mut()
.unwrap()
+19
View File
@@ -102,6 +102,8 @@ fn new_variables_are_style_overrides_and_read_back() {
#[test]
fn setvar_dimension_variables_are_saved_with_the_drawing() {
// The drawing is the test's own, so it is converted in this process.
cadcraft_io::dwg_worker::allow_in_process();
// DIMSCALE was kept and DIMTIH, DIMDEC and DIMTAD were not (#3100).
let mut s = Session::new();
for (name, v) in [("DIMSCALE", json!(2.5)), ("DIMTIH", json!(0)), ("DIMDEC", json!(2)), ("DIMTAD", json!(1))] {
@@ -315,6 +317,23 @@ fn tolerance_justification_angular_zeros_and_arc_symbol() {
assert_eq!(dim_lines(&g1).len(), dim_lines(&g2).len() + 1, "the symbol drawn over the text");
}
/// DIMPOST frames the angle too, as AutoCAD 2026 does to its own angular dimensions (#1653).
#[test]
fn dimpost_applies_to_angular_dimensions() {
let mut s = Session::new();
set(&mut s, "DIMPOST", json!("<> m"));
set(&mut s, "DIMADEC", json!(1));
// Vertex and two points.
s.execute("dimangular", &json!({ "vertex": [0, 0], "p1": [10, 0], "p2": [0, 10], "at": [3, 3] })).unwrap();
assert_eq!(last_dim(&s).1.value, "90.0° m");
// Two lines picked: the same suffix.
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
s.execute("line", &json!({ "points": [[0, 0], [5, 8.660254037844387]] })).unwrap();
let h: Vec<String> = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).map(|e| e.handle.hex()).collect();
s.execute("dimangular", &json!({ "lines": h, "at": [4, 1] })).unwrap();
assert_eq!(last_dim(&s).1.value, "60.0° m");
}
#[test]
fn linetypes_and_lineweights_of_dimension_and_extension_lines() {
let mut s = Session::new();
+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,
@@ -0,0 +1,205 @@
//! HATCHGENERATEBOUNDARY (#2801): closed polylines around existing hatches, which stay as they are.
use cadcraft_engine::doc::{EntityKind, Handle, Hatch, LwPolyline};
use cadcraft_engine::{Input, Session};
use serde_json::{Value, json};
fn hatch(s: &Session, h: &str) -> Hatch {
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
EntityKind::Hatch(x) => x.clone(),
k => panic!("not a hatch: {k:?}"),
}
}
fn poly(s: &Session, h: &str) -> LwPolyline {
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
EntityKind::LwPolyline(p) => p.clone(),
k => panic!("not a polyline: {k:?}"),
}
}
fn handle(v: &Value) -> String {
v["handle"].as_str().unwrap().to_string()
}
fn handles(v: &Value) -> Vec<String> {
v["handles"].as_array().unwrap().iter().map(|h| h.as_str().unwrap().to_string()).collect()
}
fn rect(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> String {
handle(&s.execute("rectang", &json!({ "p1": a, "p2": b })).unwrap())
}
fn count(s: &Session) -> usize {
s.doc().unwrap().model.iter().count()
}
#[test]
fn generates_a_closed_polyline_around_a_hatch_without_its_outline() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()] })).unwrap());
s.execute("erase", &json!({ "handles": [r] })).unwrap();
let before = hatch(&s, &h);
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap();
let new = handles(&v);
assert_eq!(new.len(), 1);
let p = poly(&s, &new[0]);
assert!(p.closed);
assert_eq!(p.vertices, before.loops[0].vertices);
assert_eq!(hatch(&s, &h), before, "the hatch is not changed");
s.execute("undo", &json!({})).unwrap();
assert_eq!(count(&s), 1, "one undo step removes what was generated");
}
#[test]
fn islands_get_their_own_polylines() {
let mut s = Session::new();
rect(&mut s, [0.0, 0.0], [20.0, 20.0]);
rect(&mut s, [5.0, 5.0], [10.0, 10.0]);
let h = handle(&s.execute("hatch", &json!({ "points": [[2, 2]] })).unwrap());
assert_eq!(hatch(&s, &h).loops.len(), 2);
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
assert_eq!(handles(&v).len(), 2);
}
#[test]
fn every_selected_hatch_gets_its_boundary() {
let mut s = Session::new();
let a = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let b = rect(&mut s, [10.0, 0.0], [14.0, 2.0]);
let ha = handle(&s.execute("hatch", &json!({ "handles": [a] })).unwrap());
let hb = handle(&s.execute("hatch", &json!({ "handles": [b] })).unwrap());
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [ha, hb] })).unwrap();
assert_eq!(handles(&v).len(), 2);
}
#[test]
fn a_hatch_named_twice_gets_one_boundary() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone(), h] })).unwrap();
assert_eq!(handles(&v).len(), 1);
}
#[test]
fn an_associative_hatch_stays_linked_to_its_own_boundary() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()], "associative": true })).unwrap());
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap();
let p = handles(&v)[0].clone();
// Moving the generated polyline leaves the hatch where it is.
s.execute("move", &json!({ "handles": [p], "delta": [0, 10] })).unwrap();
assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.y, 0.0);
// Moving the original rectangle still moves the hatch.
s.execute("move", &json!({ "handles": [r], "delta": [10, 0] })).unwrap();
assert!(hatch(&s, &h).associative);
assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.x, 10.0);
}
#[test]
fn boundaries_keep_the_hatch_elevation() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
s.doc_mut()
.unwrap()
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
if let EntityKind::Hatch(x) = &mut e.kind {
x.elevation = 300.0;
}
})
.unwrap();
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
assert_eq!(poly(&s, &handles(&v)[0]).elevation, 300.0);
}
/// A mirrored hatch (normal 0,0,-1, as exploding a mirrored block makes) at elevation 300 lies at
/// world Z -300; its boundary, facing up, goes there too, not to +300.
#[test]
fn a_mirrored_hatchs_boundary_keeps_its_world_height() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
s.doc_mut()
.unwrap()
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
e.common.extrusion = cadcraft_engine::geom::Vec3::new(0.0, 0.0, -1.0);
if let EntityKind::Hatch(x) = &mut e.kind {
x.elevation = 300.0;
}
})
.unwrap();
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
let new = Handle::parse_hex(&handles(&v)[0]).unwrap();
let e = s.doc().unwrap().entity(new).unwrap().clone();
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline") };
assert_eq!(e.common.extrusion.z.signum() * p.elevation, -300.0);
}
#[test]
fn refuses_a_hatch_in_another_space_and_adds_nothing() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
let before = s.doc().unwrap().entity_count();
let e = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap_err();
assert!(e.to_string().contains("not in the current space"), "{e}");
assert_eq!(s.doc().unwrap().entity_count(), before);
}
#[test]
fn refuses_more_boundaries_than_the_limit_and_adds_nothing() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
// One hatch with more loops than one call may turn into polylines.
s.doc_mut()
.unwrap()
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
if let EntityKind::Hatch(x) = &mut e.kind {
let l = x.loops[0].clone();
x.loops = vec![l; 10_001];
}
})
.unwrap();
let before = count(&s);
assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).is_err());
assert_eq!(count(&s), before);
}
#[test]
fn needs_a_hatch() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [r] })).is_err());
assert_eq!(count(&s), 1, "nothing is added");
}
#[test]
fn runs_at_once_on_selected_hatches() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
s.set_selection(vec![Handle::parse_hex(&h).unwrap()]);
s.start("hatchgenerateboundary").unwrap();
assert!(s.current_prompt().is_none(), "a pickfirst selection needs no prompt");
assert_eq!(count(&s), 3);
}
#[test]
fn asks_for_hatches_without_a_selection() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
s.set_selection(Vec::new());
s.start("hatchgenerateboundary").unwrap();
assert!(s.current_prompt().is_some());
s.input(Input::Pick(vec![Handle::parse_hex(&h).unwrap()])).unwrap();
s.input(Input::Enter).unwrap();
assert!(s.current_prompt().is_none());
assert_eq!(count(&s), 3);
}
+2
View File
@@ -68,6 +68,7 @@ mod group_selection;
mod groups;
mod hatch_assoc;
mod hatch_dialog_helpers;
mod hatch_generate_boundary;
mod hatch_numeric_validation;
mod hatch_options;
mod helix;
@@ -105,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;
@@ -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();
}
+80 -1
View File
@@ -1,5 +1,5 @@
//! Named views (#463): VIEW / -VIEW Save, Window, Restore, Delete, ? and the layer snapshot
//! setting; Zoom Realtime and Dynamic; ZOOMFACTOR. (The DXF round trip of views is tested in
//! setting; Zoom Realtime and Dynamic; realtime PAN and -PAN; ZOOMFACTOR. (The DXF round trip of views is tested in
//! `cadcraft-io`'s `view_tables_roundtrip`.)
use cadcraft_engine::doc::Space;
@@ -155,6 +155,85 @@ fn zoom_realtime_drags_and_enter_ends() {
assert_eq!(view(&s), View { center: Vec2::ZERO, height: 25.0, twist: 0.0 });
}
#[test]
fn pan_realtime_drags_and_enter_ends() {
for start in ["pan", "p"] {
let mut s = session();
set_view(&mut s, 0.0, 0.0, 100.0);
s.state_mut().unwrap().view_history.clear();
typed(&mut s, &[start]);
assert!(s.realtime_pan_active(), "{}", s.prompt_text());
// 800 px show 100 units: right 80 px and up 40 px move the drawing with the cursor.
s.realtime_pan(80.0, -40.0).unwrap();
assert!(close(view(&s).center.x, -10.0) && close(view(&s).center.y, -5.0), "{:?}", view(&s));
s.realtime_pan(f64::NAN, 3.0).unwrap();
assert!(close(view(&s).center.x, -10.0) && close(view(&s).center.y, -5.0), "{:?}", view(&s));
typed(&mut s, &[""]);
assert!(s.running.is_none() && !s.realtime_pan_active());
// Outside realtime PAN a drag does nothing; Zoom Previous returns to the view before it.
s.realtime_pan(80.0, -40.0).unwrap();
assert!(close(view(&s).center.x, -10.0) && close(view(&s).center.y, -5.0));
s.execute("zoom.previous", &json!({})).unwrap();
assert_eq!(view(&s), View { center: Vec2::ZERO, height: 100.0, twist: 0.0 });
}
}
#[test]
fn pan_realtime_moves_only_the_view() {
// A drag frame is not a change of the drawing: the revision stays, so the canvas does not
// rebuild the drawing's geometry on every frame (as with a middle-button drag).
let mut s = session();
set_view(&mut s, 0.0, 0.0, 100.0);
typed(&mut s, &["pan"]);
let revision = s.state().unwrap().revision;
s.realtime_pan(80.0, -40.0).unwrap();
assert!(close(view(&s).center.x, -10.0), "{:?}", view(&s));
assert_eq!(s.state().unwrap().revision, revision);
}
#[test]
fn pan_realtime_in_a_twisted_view_moves_the_drawing_with_the_cursor() {
// A view twisted a quarter turn (DVIEW TWist) shows the drawing's -Y to the right: a drag
// 80 px right moves the drawing with it, so the centre moves 10 units up the drawing's Y.
let mut s = session();
set_view(&mut s, 0.0, 0.0, 100.0);
s.state_mut().unwrap().set_view_quiet(View { center: Vec2::ZERO, height: 100.0, twist: std::f64::consts::FRAC_PI_2 });
typed(&mut s, &["pan"]);
assert!(s.realtime_pan_active(), "{}", s.prompt_text());
s.realtime_pan(80.0, 0.0).unwrap();
let v = view(&s);
assert!(close(v.center.x, 0.0) && close(v.center.y, 10.0), "{v:?}");
assert!(close(v.twist, std::f64::consts::FRAC_PI_2), "the pan kept the twist: {v:?}");
}
#[test]
fn dash_pan_takes_two_points_or_a_displacement() {
let mut s = session();
set_view(&mut s, 0.0, 0.0, 100.0);
typed(&mut s, &["-pan", "0,0", "10,5"]);
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(view(&s).center, Vec2::new(-10.0, -5.0));
typed(&mut s, &["-pan", "3,4", ""]);
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(view(&s).center, Vec2::new(-13.0, -9.0));
}
#[test]
fn dash_pan_displacement_is_measured_in_the_ucs() {
// A UCS moved to 100,50: the displacement 0,0 does not pan, and 3,4 pans by 3,4.
let mut s = session();
set_view(&mut s, 0.0, 0.0, 100.0);
s.execute("ucs", &json!({ "origin": [100.0, 50.0] })).unwrap();
typed(&mut s, &["-pan", "0,0", ""]);
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(view(&s).center, Vec2::ZERO);
typed(&mut s, &["-pan", "3,4", ""]);
assert_eq!(view(&s).center, Vec2::new(-3.0, -4.0));
// Two points: the difference, which the UCS origin does not change.
typed(&mut s, &["-pan", "0,0", "10,5"]);
assert_eq!(view(&s).center, Vec2::new(-13.0, -9.0));
}
#[test]
fn zoom_dynamic_places_and_sizes_the_view_box() {
let mut s = session();
+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();
@@ -29,6 +29,7 @@ fn defaults_are_the_ones_the_commands_use() {
("DONUTOD", json!(1.0)),
("WIPEOUTFRAME", json!(1)),
("LWDEFAULT", json!(25)),
("LAYLOCKFADECTL", json!(50)),
("DIMASSOC", json!(2)),
("CPLOTSTYLE", json!("ByLayer")),
("TRANSPARENCYDISPLAY", json!(1)),
@@ -61,6 +62,9 @@ fn values_reach_the_commands() {
assert!(!s.settings.transparency_display);
s.cmdline("setvar plottransparencyoverride 2").unwrap();
assert_eq!(s.settings.plot_transparency_override, 2);
for v in [-90, 0, 90] {
assert!(setvar(&mut s, "LAYLOCKFADECTL", json!(v)), "LAYLOCKFADECTL {v}");
}
assert!(setvar(&mut s, "INSNAME", json!("Valve")));
assert!(setvar(&mut s, "INSNAME", json!(".")));
assert_eq!(getvar(&mut s, "INSNAME"), json!(""));
@@ -74,6 +78,8 @@ fn bad_values_and_unknown_names_are_refused() {
("POLYSIDES", json!(5000)),
("TRIMMODE", json!(3)),
("LWDEFAULT", json!(26)),
("LAYLOCKFADECTL", json!(91)),
("LAYLOCKFADECTL", json!(-91)),
("HPSCALE", json!(0)),
("HPNAME", json!("NO-SUCH-PATTERN")),
("DONUTOD", json!(0)),
+1 -1
View File
@@ -30,7 +30,7 @@ fn transparent_zoom_resumes_the_running_command() {
s.cmdline("").unwrap();
s.cancel();
// Scripts nest the same way.
s.script("LINE 0,0 'PAN 0,0 1,1 5,0\n\n").unwrap();
s.script("LINE 0,0 '-PAN 0,0 1,1 5,0\n\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s), 2);
// Enter ends the nested command; Esc and a new command cancel both levels.
+2
View File
@@ -72,6 +72,7 @@ fn edit(drawing: Drawing, handle: Handle, points: &[Vec2], explicit: bool, index
}
fn check(format: &str, interactive: bool) {
cadcraft_io::dwg_worker::allow_in_process();
for explicit in [false, true] {
for reversed in [false, true] {
let (drawing, handle, points) = fixture(explicit, reversed);
@@ -166,6 +167,7 @@ fn polyline_closedness_is_not_inferred_from_coincident_endpoints() {
#[test]
fn coincident_endpoints_remain_separately_editable_after_save() {
cadcraft_io::dwg_worker::allow_in_process();
let original = [Vec2::ZERO, Vec2::new(8.0, 0.0), Vec2::new(8.0, 6.0), Vec2::new(0.0, 6.0)];
for explicit in [false, true] {
for interactive in [false, true] {
+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;
@@ -0,0 +1,179 @@
//! What a DXF before 2007 leaves out for its proxies' string streams, counted by the real DXF
//! writer (#3229): only what 2007 would keep, from the drawing the command writes. In its own
//! test binary because it installs the real io hooks for the whole process.
use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, SaveAs, set_io, set_proxies_lost, set_write_as};
use cadcraft_engine::doc::Drawing;
use serde_json::{Value, json};
#[path = "support/temp_dir.rs"]
mod temp_dir;
use temp_dir::TempDir;
/// The real reader and writer, and the real proxy-loss count.
fn install() {
set_io(IoHooks {
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: None,
});
set_write_as(|d, name, o: &SaveAs| {
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.
fn proxy(handle: &str, owner: &str, strings: &str, class: &str) -> Vec<(String, String)> {
let p = |c: &str, v: &str| (c.to_string(), v.to_string());
vec![
p("0", "ACAD_PROXY_ENTITY"),
p("5", handle),
p("330", owner),
p("100", "AcDbEntity"),
p("8", "0"),
p("100", "AcDbProxyEntity"),
p("90", "498"),
p("91", class),
p("95", "393245"),
p("70", "0"),
p("162", strings),
p("161", "16"),
p("310", "AABB"),
]
}
fn pairs(text: &str) -> Vec<(String, String)> {
let lines: Vec<&str> = text.lines().collect();
lines.chunks(2).map(|c| (c[0].trim().to_string(), c.get(1).map_or(String::new(), |v| v.trim().to_string()))).collect()
}
/// A drawing with `$ACADVER` `acadver` read from a DXF holding the class WIDGETX and, in model
/// space, the proxies `entities` gives (each from the model space block record's handle).
fn drawing(acadver: &str, entities: impl Fn(&str) -> Vec<Vec<(String, String)>>) -> Drawing {
let mut d = Drawing::new_imperial();
d.header.set_str("ACADVER", "AC1024");
let text = String::from_utf8(cadcraft_io::write(&d, "p.dxf").unwrap()).unwrap();
let mut p = pairs(&text);
let g = |c: &str, v: &str| (c.to_string(), v.to_string());
let classes = p.iter().position(|q| q.0 == "2" && q.1 == "CLASSES").unwrap() + 1;
let class =
[g("0", "CLASS"), g("1", "WIDGETX"), g("2", "AcDbWidgetX"), g("3", "ObjectDBX Classes"), g("90", "4095"), g("280", "0"), g("281", "1")];
p.splice(classes..classes, class);
// The model space block record: the owner of model space entities.
let record_end = |i: usize| i + 1 + p[i + 1..].iter().position(|q| q.0 == "0").unwrap_or(p.len() - i - 1);
let ms = (0..p.len())
.filter(|&i| p[i].0 == "0" && p[i].1 == "BLOCK_RECORD")
.find(|&i| p[i..record_end(i)].iter().any(|q| q.0 == "2" && q.1.eq_ignore_ascii_case("*Model_Space")))
.unwrap();
let owner = p[ms..].iter().find(|q| q.0 == "5").unwrap().1.clone();
let ents = p.iter().position(|q| q.0 == "2" && q.1 == "ENTITIES").unwrap();
let end = ents + p[ents..].iter().position(|q| q.0 == "0" && q.1 == "ENDSEC").unwrap();
p.splice(end..end, entities(&owner).into_iter().flatten());
let bytes: String = p.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect();
let mut d = cadcraft_io::read(bytes.as_bytes(), "p.dxf").unwrap();
d.header.set_str("ACADVER", acadver);
d
}
/// Two proxies with string streams, one whose class number names no class (no version writes
/// it), and one without: before 2007 only the first one is lost to the string stream.
fn three_proxies(owner: &str) -> Vec<Vec<(String, String)>> {
vec![proxy("AAA1", owner, "8", "500"), proxy("AAA2", owner, "8", "777"), proxy("AAA3", owner, "0", "500")]
}
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();
let dir = TempDir::new("proxy-loss");
let mut s = Session::empty();
s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None);
let path = dir.path_str("out.dxf");
let r = s.execute("saveas", &json!({ "path": path, "version": 2000 })).unwrap();
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "{:?}", s.log);
let r = s.execute("saveas", &json!({ "path": path, "version": 2007 })).unwrap();
assert_eq!(not_saved(&r), Value::Null);
}
#[test]
fn export_reports_the_drawing_it_writes() {
// In the Block Editor EXPORT writes the block, which holds no proxy: nothing is lost.
install();
let mut s = Session::empty();
s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None);
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }));
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
let line = s.execute("entities", &json!({ "type": "LINE" })).unwrap()["entities"][0]["handle"].as_str().unwrap().to_string();
s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [line], "keep": "convert" })).unwrap();
s.execute("bedit", &json!({ "name": "B" })).unwrap();
let n = s.log.len();
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
assert_eq!(not_saved(&r), Value::Null, "{:?}", &s.log[n..]);
}
#[test]
fn a_reference_edit_working_copy_is_not_counted_twice() {
install();
let dir = TempDir::new("proxy-loss");
let mut s = Session::empty();
s.open_drawing(drawing("AC1015", |o| vec![proxy("AAA1", o, "8", "500")]), "proxy.dxf", None);
s.execute("block", &json!({ "name": "W", "base": [0, 0], "handles": ["AAA1"], "keep": "convert" })).unwrap();
let ins = s.execute("entities", &json!({ "type": "INSERT" })).unwrap()["entities"][0]["handle"].as_str().unwrap().to_string();
let path = dir.path_str("before.dxf");
let r = s.execute("saveas", &json!({ "path": path, "version": 2000 })).unwrap();
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "in the block");
s.execute("refedit", &json!({ "handle": ins })).unwrap();
// Saves wait for REFCLOSE; the QSAVE question and `document.bytes` count the committed drawing.
let r = s.execute("document.bytes", &json!({ "format": "dxf", "version": 2000 })).unwrap();
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "the working copy isn't written");
assert_eq!(cadcraft_engine::cmd::file::loss_on_save(&s, "during.dxf"), [("ACAD_PROXY_ENTITY".to_string(), 1)].into_iter().collect());
}
#[test]
fn dash_wblock_of_the_whole_drawing_reports_a_pre_2007_dxf() {
install();
let dir = TempDir::new("proxy-loss");
let mut s = Session::empty();
s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None);
let path = dir.path_str("whole.dxf").replace('\\', "/");
s.cmdline(&format!("(command \"_.-WBLOCK\" \"{path}\" \"\" \"*\")")).unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert!(std::path::Path::new(&path).exists());
assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.ends_with("1 ACAD_PROXY_ENTITY")), "{:?}", s.log);
}
@@ -0,0 +1,55 @@
//! Kept render settings are in the form of the file they were read from, whatever the drawing's
//! `$ACADVER` says after a SAVEAS to another version: saving a 2018 drawing down to 2000 and back
//! up to 2018 writes the class version the 2018 file had, not one higher (which BricsCAD refuses,
//! #907).
use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, set_io, set_write_as};
use serde_json::json;
/// A 2018 DXF with one mental ray render settings object, stored as `90 2` (class version 1 in the
/// 2013+ form).
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\nMENTALRAYRENDERSETTINGS\n2\nAcDbMentalRayRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nENDSEC\n\
0\nSECTION\n2\nOBJECTS\n\
0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_RENDER_SETTINGS\n350\n20\n\
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n\
0\nMENTALRAYRENDERSETTINGS\n5\n21\n330\n20\n100\nAcDbRenderSettings\n90\n2\n1\nMedium\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n\
100\nAcDbMentalRayRenderSettings\n90\n2\n0\nENDSEC\n0\nEOF\n";
/// The `AcDbRenderSettings` class version in a written DXF.
fn class_version(path: &std::path::Path) -> Option<i64> {
let text = std::fs::read_to_string(path).unwrap();
let l: Vec<&str> = text.lines().map(str::trim).collect();
let at = l.windows(2).position(|w| w == ["0", "MENTALRAYRENDERSETTINGS"])?;
let base = l[at..].windows(2).position(|w| w == ["100", "AcDbRenderSettings"])? + at;
l[base..].windows(2).find(|w| w[0] == "90").map(|w| w[1].parse().unwrap())
}
#[test]
fn saveas_down_and_back_up_keeps_the_render_settings_class_version() {
set_io(IoHooks {
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: None,
});
set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
});
let dir = std::env::temp_dir().join(format!("cadcraft-render-settings-saveas-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut s = Session::empty();
s.open_drawing(cadcraft_io::read_dxf(DXF.as_bytes()).unwrap(), "render.dxf", None);
let save = |s: &mut Session, name: &str, version: &str| {
let path = dir.join(name);
s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": version })).unwrap();
class_version(&path)
};
assert_eq!(save(&mut s, "2018.dxf", "2018"), Some(2), "same version: as read");
assert_eq!(save(&mut s, "2000.dxf", "2000"), Some(1), "the 2000 form is one lower");
s.execute("qsave", &json!({})).unwrap();
assert_eq!(class_version(&dir.join("2000.dxf")), Some(1), "QSAVE keeps the 2000 form");
assert_eq!(save(&mut s, "back.dxf", "2018"), Some(2), "back to 2018: the 2018 file's value, not one higher");
let _ = std::fs::remove_dir_all(&dir);
}
+1
View File
@@ -212,6 +212,7 @@ fn whole_drawings_are_told_from_cut_off_ones() {
/// in a 2018 and a 2000 file, it doesn't replace the good backup; whole, it does.
#[test]
fn a_dwg_cut_off_anywhere_keeps_the_good_backup() {
cadcraft_io::dwg_worker::allow_in_process();
let _saving = saving();
hooks();
for version in [2018, 2000] {
+125 -7
View File
@@ -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")));
@@ -268,19 +271,27 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() {
assert_eq!(r["notSaved"], json!({ "REGION": 1 }));
}
/// A DWG before 2013 writes a solid's SAT text as it is, so a save there doesn't list a solid that
/// holds it; from 2013 the geometry must be in the data store and SAT text alone is lost, so the
/// save lists it. A solid with neither is always listed (#2334).
/// A DWG before 2013 writes a solid's SAT text of ACIS 7.0 and later, so a save there doesn't list
/// a solid that holds it; from 2013 the geometry must be in the data store and SAT text alone is
/// lost, so the save lists it. Older SAT (ACIS 4.0) and a solid with neither are always listed
/// (#2334).
#[test]
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, "400 1 1 0")])).unwrap();
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();
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 1)].into_iter().collect(), "2010 keeps the SAT-text solid");
assert_eq!(not_saved_as(&d, Version::R2018), [("3DSOLID".to_string(), 2)].into_iter().collect(), "2018 loses it");
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "400 85 1 0")])).unwrap();
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 2)].into_iter().collect(), "ACIS 4.0 SAT is listed");
// The same versions encoded, as a DXF before 2013 holds them: 700 is kept, 400 is listed.
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "hoo o n o")])).unwrap();
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 2)].into_iter().collect(), "encoded ACIS 7.0 SAT is kept");
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "koo gj n o")])).unwrap();
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 3)].into_iter().collect(), "encoded ACIS 4.0 SAT is listed");
}
/// The DWG bridge writes OLE objects (`ole2frame_roundtrip` in the io tests), so saving one as
@@ -302,3 +313,110 @@ fn ole_objects_are_not_reported() {
assert_eq!(not_saved_as(&d, v), [("MLINE".to_string(), 1), ("ole2frame".to_string(), 1)].into_iter().collect(), "{v:?}");
}
}
/// A solid whose geometry only the data store keeps (read from a 2013+ file) has nothing to write
/// to a DXF of 2010 or earlier, which has no data store: the save leaves it out and says so, and
/// the interactive save knows it beforehand; 2013 and later keep it (#2334).
#[test]
fn saving_data_store_solids_as_dxf_2010_reports_them() {
use cadcraft_engine::cmd::file::loss_on_save;
use cadcraft_engine::doc::foreign::Foreign;
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
set_write_as(|_, _, _: &SaveAs| Ok(b"x".to_vec()));
let mut d = Drawing::new_imperial();
d.header.set_str("ACADVER", "AC1032");
let h = d.add(&Space::Model, Common::default(), unknown("3DSOLID")).unwrap();
let record = vec![
RawTag { code: 0, value: "ACDSRECORD".into() },
RawTag { code: 320, value: h.hex() },
RawTag { code: 2, value: "ASM_Data".into() },
RawTag { code: 310, value: "00".into() },
];
d.foreign = std::sync::Arc::new(Foreign { data_store: record, ..Foreign::default() });
let mut s = Session::empty();
s.open_drawing(d, "solid.dxf", None);
assert!(loss_on_save(&s, "solid.dxf").is_empty(), "2018 keeps it");
let path = std::env::temp_dir().join(format!("cadcraft-ds-note-{}.dxf", std::process::id()));
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2010 })).unwrap();
assert_eq!(r["notSaved"], json!({ "3DSOLID": 1 }));
assert!(s.log.iter().any(|l| l.contains("2010 and earlier have no data store") && l.contains("1 3DSOLID")), "{:?}", s.log);
assert_eq!(loss_on_save(&s, "solid.dxf"), [("3DSOLID".to_string(), 1)].into_iter().collect(), "now a 2010 drawing");
let n = s.log.len();
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2018 })).unwrap();
let _ = std::fs::remove_file(&path);
assert!(r.get("notSaved").is_none() && s.log.len() == n);
}
/// A proxy entity (as a 2010 file has it) whose string stream is `strings` long (group 162).
fn proxy_entity(strings: &str) -> EntityKind {
let tags = [(8, "0"), (100, "AcDbProxyEntity"), (90, "498"), (91, "500"), (162, strings), (161, "16"), (310, "AABB")];
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(),
})
}
/// A DXF before 2007 has no form for a proxy's separate string stream: the writer leaves such a
/// proxy out, and the save says so instead of dropping it silently (#3229).
#[test]
fn a_dxf_before_2007_reports_the_proxies_it_leaves_out() {
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
// SAVEAS at a chosen version goes through this hook (each test may run in its own process).
set_write_as(|_, _, _: &SaveAs| Ok(b"x".to_vec()));
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap();
d.add(&Space::Model, Common::default(), proxy_entity("0")).unwrap();
let mut s = Session::empty();
s.open_drawing(d, "proxy.dxf", None);
let path = std::env::temp_dir().join(format!("cadcraft-proxy-r2000-{}.dxf", std::process::id()));
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2000 })).unwrap();
assert_eq!(r["notSaved"], json!({ "ACAD_PROXY_ENTITY": 1 }), "only the one with strings");
assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.contains("1 ACAD_PROXY_ENTITY")), "{:?}", s.log);
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2007 })).unwrap();
let _ = std::fs::remove_file(&path);
assert!(r.get("notSaved").is_none(), "2007 keeps it");
}
/// The interactive QSAVE asks before a pre-2007 DXF replaces a file and leaves such proxies out,
/// with the same list (#3229).
#[test]
fn a_pre_2007_dxf_proxy_loss_is_known_before_saving() {
use cadcraft_engine::cmd::file::loss_on_save;
let drawing = |acadver: &str| {
let mut d = Drawing::new_imperial();
d.header.set_str("ACADVER", acadver);
d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap();
d
};
let mut s = Session::empty();
s.open_drawing(drawing("AC1015"), "proxy.dxf", None);
assert_eq!(loss_on_save(&s, "proxy.dxf"), [("ACAD_PROXY_ENTITY".to_string(), 1)].into_iter().collect());
s.open_drawing(drawing("AC1021"), "proxy.dxf", None);
assert!(loss_on_save(&s, "proxy.dxf").is_empty(), "2007 keeps it");
}
/// EXPORT writes a DXF at the drawing's own version: before 2007 it leaves the same proxies out
/// and says so, like a save (#3229).
#[test]
fn exporting_a_dxf_before_2007_reports_the_proxies_it_leaves_out() {
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
let drawing = |acadver: &str| {
let mut d = Drawing::new_imperial();
d.header.set_str("ACADVER", acadver);
d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap();
d.add(&Space::Model, Common::default(), proxy_entity("0")).unwrap();
d
};
let mut s = Session::empty();
s.open_drawing(drawing("AC1015"), "proxy.dxf", None);
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
assert_eq!(r["notSaved"], json!({ "ACAD_PROXY_ENTITY": 1 }), "only the one with strings");
assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.contains("1 ACAD_PROXY_ENTITY")), "{:?}", s.log);
let mut s = Session::empty();
s.open_drawing(drawing("AC1021"), "proxy.dxf", None);
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
assert!(r.get("notSaved").is_none(), "2007 keeps it");
}
+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());
}
+1
View File
@@ -31,6 +31,7 @@ fn folder(tag: &str) -> TempDir {
}
fn save(d: &Drawing, path: &Path) {
cadcraft_io::dwg_worker::allow_in_process();
std::fs::write(path, cadcraft_io::write(d, path).unwrap()).unwrap();
}
+12
View File
@@ -477,6 +477,18 @@ mod tests {
ttf::fallback_for('\u{0E01}').filter(|f| ['\u{0E14}', '\u{0E34}', '\u{0E4C}', '\u{0E33}', '\u{0E10}'].iter().all(|c| f.has_glyph(*c)))
}
/// A Thai face's letters are measured in ems: ก has neither ascender nor descender, ไ rises
/// above it, and a space or an unmapped character has no height.
#[test]
fn thai_glyph_heights_are_measured_in_ems() {
let Some(face) = thai_face() else { return };
let ko = face.glyph_height('ก').unwrap_or_default();
assert!((0.2..1.0).contains(&ko), "ก is {ko} em");
assert!(face.glyph_height('ไ').is_some_and(|h| h > ko), "ไ is taller than ก");
assert_eq!(face.glyph_height(' '), None);
assert_eq!(face.glyph_height('\u{10fffd}'), None);
}
/// Lowest point of the glyph that shows `c`.
fn bottom_of(sh: &Shaped, c: char) -> Option<f64> {
let t = sh.text.iter().find(|t| t.ch == c)?;
+42 -22
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 ' '..='~' {
@@ -839,13 +858,14 @@ mod ttf_tests {
#[test]
fn fallback_ranking_prefers_wide_coverage_regular_fonts() {
let stems: Vec<String> =
["zapfino", "dejavusans", "notosanscjk-bold", "notosanscjk-regular", "wqy-zenhei", "notosansarabic-regular", "arial"]
["zapfino", "dejavusans", "notosanscjk-bold", "notosanscjk-regular", "wqy-zenhei", "notosansarabic-regular", "arial", "unifont"]
.map(String::from)
.to_vec();
let r = crate::ttf::rank_fallback(&stems);
assert_eq!(r.first().map(String::as_str), Some("notosanscjk-regular"));
assert_eq!(r.get(1).map(String::as_str), Some("notosanscjk-bold"));
assert_eq!(r.get(2).map(String::as_str), Some("wqy-zenhei"));
assert_eq!(r.get(r.len().wrapping_sub(2)).map(String::as_str), Some("unifont"), "a last resort, but ahead of unknown fonts");
assert_eq!(r.last().map(String::as_str), Some("zapfino"));
assert_eq!(r.len(), stems.len());
}
+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
}
+156 -8
View File
@@ -35,6 +35,9 @@ use skrifa::{FontRef, GlyphId, MetadataProvider};
use crate::{Run, Shaped};
#[cfg(not(target_arch = "wasm32"))]
mod dirs;
/// One face of a font file (a TrueType collection holds several).
#[derive(Clone)]
pub struct Face {
@@ -92,6 +95,17 @@ impl Face {
Some(s.chars().filter(|c| !c.is_control()).take(80).collect::<String>()).filter(|s| !s.trim().is_empty())
})
}
/// How tall the glyph of `c` is, from its lowest to its highest point, in ems: `None` when the
/// face doesn't map `c` or its glyph has no outline (a space, or one too big to keep).
pub fn glyph_height(&self, c: char) -> Option<f64> {
let g = glyph(self, c);
if !g.mapped {
return None;
}
let (low, high) = g.contours.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), p| (low.min(p.y), high.max(p.y)));
let height = (high - low) / f64::from(UPEM);
(height.is_finite() && height > 0.0).then_some(height)
}
/// The glyph ids the face's character map gives `chars` (`None` for an unmapped one).
pub(crate) fn glyph_ids(&self, chars: &[char]) -> Vec<Option<u32>> {
@@ -144,7 +158,11 @@ const MAX_CACHED_CHARS: usize = 50_000;
pub(crate) const MAX_SHAPED_POINTS: usize = 8_000_000;
/// Fonts known to cover many scripts (CJK first), tried first for missing glyphs. Matched as
/// substrings of the normalised file stem.
/// substrings of the normalised file stem. The last two are the wide nets: GNU FreeSerif (most
/// non-CJK scripts, with real OpenType shaping; in the default font set of NixOS and many
/// distributions), then Unifont (every BMP character, as bitmap-like outlines; the only
/// CJK-capable font of NixOS's default set) for what FreeSerif lacks. Both come before the
/// alphabetical rest, which the bounded search never gets through.
const PREFERRED_FALLBACK: &[&str] = &[
"notosanscjk",
"sourcehansans",
@@ -168,6 +186,8 @@ const PREFERRED_FALLBACK: &[&str] = &[
"dejavusans",
"segoeui",
"arial",
"freeserif",
"unifont",
];
/// Fonts known to cover a right-to-left script, tried before the general search for its
/// characters (the general search loads a bounded number of files, and wide-coverage CJK fonts
@@ -342,11 +362,11 @@ fn system_font_dirs() -> Vec<PathBuf> {
dirs.push(PathBuf::from(l).join("Microsoft\\Windows\\Fonts"));
}
} else {
dirs.extend(["/usr/share/fonts", "/usr/local/share/fonts"].map(Into::into));
if let Some(h) = std::env::var_os("HOME") {
dirs.push(PathBuf::from(&h).join(".fonts"));
dirs.push(PathBuf::from(h).join(".local/share/fonts"));
}
// Where fontconfig looks: NixOS, Guix and Flatpak keep fonts outside /usr/share/fonts
// (#674). Later directories take precedence (the stack pops them first), so the
// resolver's priority order is reversed; [`scan_dirs`] reads each resolved
// directory once and skips missing ones.
dirs.extend(dirs::font_dirs(|k| std::env::var_os(k), dirs::read_config).into_iter().rev());
}
dirs
}
@@ -866,6 +886,16 @@ pub fn find(name: &str) -> Option<Face> {
r
}
/// The installed font file with this stem (`DejaVuSans`, `NotoSansCJK-Regular`; case and an
/// extension don't matter), wherever the system keeps its fonts. A font compiled in from
/// craft-fonts is no file and gives `None`.
pub fn installed_font_path(stem: &str) -> Option<PathBuf> {
match lock().paths.get(&key(stem))? {
Source::File(p) => Some(p.clone()),
Source::Static(_) => None,
}
}
struct Prefs {
alt: String,
fallback: Vec<String>,
@@ -1073,9 +1103,38 @@ pub fn descent_ratio(face: &Face) -> Option<f64> {
(r.is_finite() && r > 0.0 && r < 2.0).then_some(r)
}
/// Cap height of a font in font units at 1000 units per em: the OS/2 value, else the height
/// of its "H", else an estimate from the ascent.
/// Cap heights the installation pins for metric-compatible substitutes, from `CADCRAFT_CAP_HEIGHT`
/// (`LiberationSans=715.8;LiberationSans-Bold=715.8`): a substitute keeps the advance widths of
/// the font it stands in for but not its cap height, so scaling by the substitute's own OS/2
/// value draws text the size of the substitute, not of the requested font. Each entry names a
/// substitute's PostScript name and the cap height to give it, in font units at 1000 per em: the
/// cap height of the font it replaces, not its own.
fn cap_height_overrides() -> &'static HashMap<String, f64> {
static OVERRIDES: OnceLock<HashMap<String, f64>> = OnceLock::new();
OVERRIDES.get_or_init(|| parse_cap_height_overrides(&std::env::var("CADCRAFT_CAP_HEIGHT").unwrap_or_default()))
}
/// Parse a `Name=height;…` list; entries without a name or with a height below 1 unit or not
/// finite are dropped (a font's own cap height is never taken below 1 either: a tiny one would
/// scale its glyphs past any drawing's extent). Names are matched normalised, like family names.
fn parse_cap_height_overrides(spec: &str) -> HashMap<String, f64> {
spec.split(';')
.filter_map(|entry| {
let (name, height) = entry.split_once('=')?;
let height: f64 = height.trim().parse().ok()?;
(height.is_finite() && height >= 1.0 && !name.trim().is_empty()).then(|| (norm(name.trim()), height))
})
.collect()
}
/// Cap height of a font in font units at 1000 units per em: the value `CADCRAFT_CAP_HEIGHT`
/// pins for this font's PostScript name, else the OS/2 value, else the height of its "H",
/// else an estimate from the ascent.
fn cap_height(f: &FontRef) -> f64 {
let named = f.localized_strings(skrifa::string::StringId::POSTSCRIPT_NAME).next().map(|s| norm(&s.to_string()));
if let Some(height) = named.as_deref().and_then(|n| cap_height_overrides().get(n)) {
return *height;
}
let metrics = f.metrics(Size::new(UPEM), LocationRef::default());
let measured = || {
let gid = f.charmap().map('H')?;
@@ -1408,6 +1467,74 @@ mod family_tests {
}
}
#[cfg(test)]
mod cap_height_override_tests {
use super::*;
use std::collections::HashMap;
#[test]
fn cap_height_env_parses_name_height_entries() {
let m = parse_cap_height_overrides("LiberationSans=715.8;LiberationSans-Bold=715.8");
let mut want = HashMap::new();
want.insert("liberationsans".to_string(), 715.8);
want.insert("liberationsansbold".to_string(), 715.8);
assert_eq!(m, want);
assert_eq!(
parse_cap_height_overrides("LiberationSans = 715.8 ; NotoSansCJK=1466"),
parse_cap_height_overrides("LiberationSans=715.8;NotoSansCJK=1466").into_iter().collect::<HashMap<_, _>>(),
"spaces around names and heights are tolerated"
);
assert!(
parse_cap_height_overrides("noheight;=5;Arial=0;Arial=-1;Arial=abc").is_empty(),
"entries without a name or a positive finite height are dropped"
);
assert!(parse_cap_height_overrides("").is_empty());
assert!(
parse_cap_height_overrides("Arial=0.0001;Arial=1e-300").is_empty(),
"a height below 1 unit is dropped, as `cap_height` never goes below 1"
);
}
#[test]
fn cap_height_override_applies_only_to_the_named_font() {
let m = parse_cap_height_overrides("LiberationSans=715.8");
assert_eq!(m.get(&norm("LiberationSans")), Some(&715.8));
assert_eq!(m.get(&norm("Liberation Sans")), Some(&715.8), "names match normalised");
assert_eq!(m.get(&norm("DejaVuSans")), None);
assert_eq!(m.get(&norm("LiberationSans-Bold")), None);
}
/// With no override for the face, `cap_height` walks its chain: the OS/2 value when the face
/// has one, else the height of its "H", else an estimate from the ascent. Uses the first of
/// these common fonts that is installed (Windows, macOS and Linux each have one); skips
/// without any. No override is in play: `CADCRAFT_CAP_HEIGHT` names other faces, and the
/// test binary's env is read once — a face this test does not name stays unoverridden.
#[test]
fn cap_height_without_an_override_follows_the_fallback_chain() {
let found = ["Arial", "Helvetica", "DejaVuSans", "Verdana", "LiberationSans-Regular"].into_iter().find_map(find);
let Some(face) = found else { return };
let f = face.font().expect("the face parses");
let named = f.localized_strings(skrifa::string::StringId::POSTSCRIPT_NAME).next().map(|s| norm(&s.to_string())).unwrap_or_default();
let m = f.metrics(Size::new(UPEM), LocationRef::default());
let h_height = || {
let gid = f.charmap().map('H')?;
let b = f.glyph_metrics(Size::new(UPEM), LocationRef::default()).bounds(gid)?;
Some(b.y_max).filter(|y| y.is_finite() && *y > 0.0)
};
let got = cap_height(&f);
let want = if cap_height_overrides().contains_key(&named) {
return; // this installation pins the face: the override leg is covered by the parser tests
} else if let Some(cap) = m.cap_height.filter(|c| c.is_finite() && *c > 0.0) {
f64::from(cap)
} else if let Some(h) = h_height() {
f64::from(h)
} else {
f64::from(m.ascent) * 0.72
};
assert!((got - want.max(1.0)).abs() < 1.0, "cap height {got} tracks the chain's value {want}");
}
}
#[cfg(test)]
mod geometry_budget_tests {
use super::*;
@@ -1495,4 +1622,25 @@ mod scan_tests {
#[cfg(all(unix, not(any(target_os = "macos", target_os = "android", target_env = "ohos"))))]
assert!(dirs.iter().any(|d| d == std::path::Path::new("/usr/share/fonts")), "{dirs:?}");
}
#[cfg(unix)]
#[test]
fn a_symlink_back_up_the_tree_does_not_hide_the_other_font_directories() {
let root = std::env::temp_dir().join(format!("cadcraft-font-walk-{}", std::process::id()));
let (looped, other) = (root.join("looped"), root.join("other"));
std::fs::create_dir_all(&looped).unwrap();
std::fs::create_dir_all(&other).unwrap();
std::fs::write(looped.join("a.ttf"), b"").unwrap();
// The kernel gives up on a symlink chain after about 40 hops; with this many entries,
// reading the directory at every hop would still run past the 20 000 entry budget.
for i in 0..600 {
std::fs::write(looped.join(format!("readme{i}.txt")), b"").unwrap();
}
std::fs::write(other.join("b.ttf"), b"").unwrap();
std::os::unix::fs::symlink(&looped, looped.join("again")).unwrap();
// The looped directory is walked first.
let found = scan_dirs(&[other.clone(), looped.clone()], false);
std::fs::remove_dir_all(&root).unwrap();
assert!(found.contains_key("a") && found.contains_key("b"), "{found:?}");
}
}
+502
View File
@@ -0,0 +1,502 @@
//! Where installed fonts live on Linux and the BSDs, the way fontconfig finds them: the XDG base
//! directories, the `<dir>` entries of fontconfig's configuration (NixOS and Guix keep each font
//! package in its own store path, nowhere near `/usr/share/fonts`) and the host fonts a Flatpak
//! sandbox mounts. Directories only: fontconfig's aliases and matching rules are not read.
//!
//! The resolver is a pure function of the environment and a configuration reader, so its tests
//! run the same on every machine.
use std::collections::HashSet;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
/// Bounds on a configuration a package or a user may have made hostile: files read, `<include>`
/// nesting, bytes per file, elements per file, entries per path list, directories returned.
const MAX_CONFIG_FILES: usize = 256;
const MAX_INCLUDE_DEPTH: usize = 4;
const MAX_CONFIG_BYTES: u64 = 1 << 20;
const MAX_ELEMENTS: usize = 4096;
const MAX_PATH_LIST: usize = 64;
const MAX_DIRS: usize = 1024;
/// Where Flatpak mounts the host's system, local and user font directories in a sandbox (it also
/// lists them in `/run/host/font-dirs.xml`, which the runtime's `fonts.conf` includes).
const FLATPAK_FONT_DIRS: &[&str] = &["/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"];
/// What an `<include>` names: a configuration file's text, or the `[0-9]*.conf` files of a
/// directory, sorted, as fontconfig reads them.
pub(super) enum Include {
File(String),
Dir(Vec<PathBuf>),
}
/// Font directories in priority order, without duplicates: the user's XDG font directories,
/// `$XDG_DATA_DIRS/fonts` (`/usr/local/share/fonts` and `/usr/share/fonts` whether listed or
/// not), Flatpak's host font mounts, then the `<dir>` entries of fontconfig's configuration
/// (`$FONTCONFIG_FILE`, else `fonts.conf` in the configuration path, following its `<include>`s;
/// as in fontconfig, the path is `$FONTCONFIG_PATH`'s directories then `/etc/fonts`). `env` reads an
/// environment variable, `read` a configuration file or directory (`None` when missing).
pub(super) fn font_dirs(env: impl Fn(&str) -> Option<OsString>, read: impl Fn(&Path) -> Option<Include>) -> Vec<PathBuf> {
let var = |k: &str| env(k).filter(|v| !v.is_empty());
let home = var("HOME").map(PathBuf::from);
let data_home = var("XDG_DATA_HOME").map(PathBuf::from).or_else(|| home.as_ref().map(|h| h.join(".local/share")));
let config_home = var("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| home.as_ref().map(|h| h.join(".config")));
let list = |k: &str, default: &str| -> Vec<PathBuf> {
std::env::split_paths(&var(k).unwrap_or_else(|| default.into())).filter(|p| p.is_absolute()).take(MAX_PATH_LIST).collect()
};
let mut user: Vec<PathBuf> = data_home.iter().map(|d| d.join("fonts")).chain(home.iter().map(|h| h.join(".fonts"))).collect();
user.extend(list("XDG_DATA_DIRS", "/usr/local/share:/usr/share").into_iter().map(|d| d.join("fonts")));
user.extend(["/usr/local/share/fonts", "/usr/share/fonts"].iter().chain(FLATPAK_FONT_DIRS).map(PathBuf::from));
let mut config_path = list("FONTCONFIG_PATH", "/etc/fonts");
if !config_path.iter().any(|p| p == Path::new("/etc/fonts")) {
config_path.push(PathBuf::from("/etc/fonts"));
}
let mut r = Resolver { home, data_home, config_home, config_path, read: &read, out: Vec::new(), visited: HashSet::new() };
for d in user {
r.add(d);
}
r.include(&var("FONTCONFIG_FILE").map(|f| f.to_string_lossy().into_owned()).unwrap_or_else(|| "fonts.conf".into()), None, 0);
r.out
}
struct Resolver<'a> {
home: Option<PathBuf>,
data_home: Option<PathBuf>,
config_home: Option<PathBuf>,
/// Where a relative top-level name is looked up: `$FONTCONFIG_PATH`'s directories, then
/// `/etc/fonts`.
config_path: Vec<PathBuf>,
read: &'a dyn Fn(&Path) -> Option<Include>,
out: Vec<PathBuf>,
/// Configuration files and directories read: cycles and the file bound.
visited: HashSet<PathBuf>,
}
impl Resolver<'_> {
fn add(&mut self, p: PathBuf) {
if p.is_absolute() && self.out.len() < MAX_DIRS && !self.out.contains(&p) {
self.out.push(p);
}
}
/// A path with a leading `~` meaning `$HOME`.
fn expand_home(&self, s: &str) -> Option<PathBuf> {
match s.strip_prefix('~') {
Some(rest) => self.home.as_ref().map(|h| h.join(rest.trim_start_matches('/'))),
None => Some(PathBuf::from(s)),
}
}
/// Follow an `<include>` (or the top-level file): an absolute name, or a relative one looked
/// up in the configuration path. `here` is the including file's directory.
fn include(&mut self, name: &str, here: Option<&Path>, depth: usize) {
match self.expand_home(name) {
Some(p) if p.is_absolute() => {
self.config(&p, depth);
}
Some(p) => {
let bases: Vec<PathBuf> = if here.is_some() { here.map(Path::to_path_buf).into_iter().collect() } else { self.config_path.clone() };
for base in bases {
if self.config(&base.join(&p), depth) {
break;
}
}
}
None => {}
}
}
/// Read a configuration file (or every file of a directory) and its includes, nested at most
/// `MAX_INCLUDE_DEPTH` deep. True when something was read.
fn config(&mut self, file: &Path, depth: usize) -> bool {
if depth > MAX_INCLUDE_DEPTH || self.visited.len() >= MAX_CONFIG_FILES || !self.visited.insert(file.to_path_buf()) {
return false;
}
let xml = match (self.read)(file) {
Some(Include::File(xml)) => xml,
Some(Include::Dir(files)) => {
for f in files.iter().take(MAX_CONFIG_FILES) {
self.config(f, depth);
}
return true;
}
None => return false,
};
let here = file.parent().map(Path::to_path_buf);
for e in elements(&xml) {
match (e.name, e.prefix) {
("dir", Some("xdg")) => {
if let Some(d) = self.data_home.as_ref().map(|d| d.join(&e.text)) {
self.add(d);
}
}
("dir", Some("relative")) => {
if let Some(d) = here.as_ref().map(|h| h.join(&e.text)) {
self.add(d);
}
}
// "default", "cwd" or none: as written; a relative directory is skipped.
("dir", _) => {
if let Some(d) = self.expand_home(&e.text) {
self.add(d);
}
}
("include", Some("xdg")) => {
if let Some(f) = self.config_home.as_ref().map(|c| c.join(&e.text)) {
self.config(&f, depth + 1);
}
}
("include", Some("relative")) => self.include(&e.text, here.as_deref(), depth + 1),
("include", _) => self.include(&e.text, None, depth + 1),
_ => {}
}
}
true
}
}
struct Element<'a> {
name: &'a str,
prefix: Option<&'a str>,
text: String,
}
/// The `<dir>` and `<include>` elements of a configuration file with text, in order, with their
/// `prefix` attribute; comments are skipped. A bounded scan over the text: fontconfig files are
/// small and regular.
fn elements(xml: &str) -> Vec<Element<'_>> {
let mut out = Vec::new();
let mut rest = xml;
while let Some(i) = rest.find('<') {
let Some(tag) = rest.get(i + 1..) else { break };
if let Some(c) = tag.strip_prefix("!--") {
rest = c.find("-->").and_then(|j| c.get(j + 3..)).unwrap_or("");
continue;
}
let Some(end) = tag.find('>') else { break };
let (head, after) = (tag.get(..end).unwrap_or(""), tag.get(end + 1..).unwrap_or(""));
rest = after;
let (name, attrs) = head.split_once(char::is_whitespace).unwrap_or((head, ""));
if !matches!(name, "dir" | "include") {
continue;
}
let prefix = attribute(attrs, "prefix");
let text = unescape(after.split('<').next().unwrap_or("").trim());
if !text.is_empty() {
out.push(Element { name, prefix, text });
}
if out.len() >= MAX_ELEMENTS {
break;
}
}
out
}
/// The value of the attribute `name` in a start tag's attribute list: name, optional whitespace,
/// `=`, optional whitespace, a single- or double-quoted value, in any order. `None` when absent
/// or not well-formed up to it.
fn attribute<'a>(attrs: &'a str, name: &str) -> Option<&'a str> {
let mut rest = attrs;
loop {
rest = rest.trim_start();
let key_end = rest.find(|c: char| c == '=' || c.is_whitespace())?;
let key = rest.get(..key_end)?;
rest = rest.get(key_end..)?.trim_start().strip_prefix('=')?.trim_start();
let quote = rest.chars().next().filter(|c| matches!(c, '"' | '\''))?;
rest = rest.get(1..)?;
let value_end = rest.find(quote)?;
let value = rest.get(..value_end)?;
if key == name {
return Some(value);
}
rest = rest.get(value_end + 1..)?;
}
}
fn unescape(s: &str) -> String {
if !s.contains('&') {
return s.to_string();
}
s.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&apos;", "'").replace("&amp;", "&")
}
/// Read a configuration file (skipped beyond `MAX_CONFIG_BYTES`) or list a directory's
/// `[0-9]*.conf` files, sorted.
pub(super) fn read_config(path: &Path) -> Option<Include> {
use std::io::Read as _;
if path.is_dir() {
let conf =
|p: &Path| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(|c: char| c.is_ascii_digit()) && n.ends_with(".conf"));
let mut files: Vec<PathBuf> = std::fs::read_dir(path).ok()?.flatten().map(|e| e.path()).filter(|p| conf(p)).take(MAX_CONFIG_FILES).collect();
files.sort();
return Some(Include::Dir(files));
}
let mut xml = String::new();
std::fs::File::open(path).ok()?.take(MAX_CONFIG_BYTES.saturating_add(1)).read_to_string(&mut xml).ok()?;
(xml.len() as u64 <= MAX_CONFIG_BYTES).then_some(Include::File(xml))
}
/// The tests build configurations from POSIX paths such as `/usr/share/fonts`, which only a Unix
/// `Path` takes as absolute, so they run on Unix only; the resolver itself builds everywhere.
#[cfg(all(test, unix))]
mod tests {
use super::*;
fn env_of<'a>(vars: &'a [(&str, &str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v))
}
fn reader<'a>(files: &'a [(&str, &str)], dirs: &'a [(&str, &[&str])]) -> impl Fn(&Path) -> Option<Include> + 'a {
move |p| {
if let Some((_, xml)) = files.iter().find(|(n, _)| Path::new(n) == p) {
return Some(Include::File((*xml).to_string()));
}
dirs.iter().find(|(n, _)| Path::new(n) == p).map(|(_, fs)| Include::Dir(fs.iter().map(PathBuf::from).collect()))
}
}
fn paths(v: &[&str]) -> Vec<PathBuf> {
v.iter().map(PathBuf::from).collect()
}
const XDG: &[&str] = &["/usr/local/share/fonts", "/usr/share/fonts", "/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"];
#[test]
fn xdg_defaults_without_variables() {
let d = font_dirs(env_of(&[("HOME", "/home/u")]), |_| None);
assert_eq!(d, paths(&[&["/home/u/.local/share/fonts", "/home/u/.fonts"], XDG].concat()));
assert_eq!(font_dirs(|_| None, |_| None), paths(XDG), "no HOME: system directories only");
}
#[test]
fn xdg_variables_name_the_font_dirs() {
let env = env_of(&[
("HOME", "/home/u"),
("XDG_DATA_HOME", "/data"),
("XDG_DATA_DIRS", "/nix/profile/share:/run/current-system/sw/share:relative:/usr/share/:"),
]);
let d = font_dirs(env, |_| None);
assert_eq!(
d.get(..6),
Some(
paths(&[
"/data/fonts",
"/home/u/.fonts",
"/nix/profile/share/fonts",
"/run/current-system/sw/share/fonts",
"/usr/share/fonts",
"/usr/local/share/fonts"
])
.as_slice()
)
);
assert_eq!(d.len(), 9, "{d:?}");
}
#[test]
fn fontconfig_dirs_nixos_style() {
let files = [
(
"/etc/fonts/fonts.conf",
"<?xml version=\"1.0\"?>\n<!DOCTYPE fontconfig SYSTEM \"urn:fontconfig:fonts.dtd\">\n<fontconfig>\n\
<!-- Font directory list -->\n<cachedir prefix=\"xdg\">fontconfig</cachedir>\n\
<include ignore_missing=\"yes\">/etc/fonts/conf.d</include>\n<dir prefix=\"xdg\">fonts</dir>\n\
<dir>/nix/store/aaa-dejavu-fonts-minimal-2.37</dir>\n</fontconfig>\n",
),
(
"/etc/fonts/conf.d/00-nixos-cache.conf",
"<fontconfig>\n <!-- Font directories -->\n <dir>/nix/store/bbb-dejavu-fonts-2.37</dir>\n<dir salt=\"x\">/nix/store/ccc-unifont-16.0.03</dir>\n\
<!-- <dir>/commented/out</dir> -->\n <cachedir>/nix/store/ddd-fc-cache</cachedir>\n</fontconfig>\n",
),
(
"/etc/fonts/conf.d/50-user.conf",
"<fontconfig>\n<include ignore_missing=\"yes\" prefix=\"xdg\">fontconfig/conf.d</include>\n</fontconfig>\n",
),
(
"/home/u/.config/fontconfig/conf.d/10-hm-fonts.conf",
"<fontconfig>\n<include ignore_missing=\"yes\">/nix/store/eee-home-manager-path/etc/fonts/conf.d</include>\n\
<dir>/nix/store/eee-home-manager-path/share/fonts</dir>\n<dir>/etc/profiles/per-user/u/share/fonts</dir>\n</fontconfig>\n",
),
];
let dirs: [(&str, &[&str]); 2] = [
("/etc/fonts/conf.d", &["/etc/fonts/conf.d/00-nixos-cache.conf", "/etc/fonts/conf.d/50-user.conf"]),
("/home/u/.config/fontconfig/conf.d", &["/home/u/.config/fontconfig/conf.d/10-hm-fonts.conf"]),
];
let d = font_dirs(env_of(&[("HOME", "/home/u"), ("XDG_DATA_DIRS", "/etc/profiles/per-user/u/share")]), reader(&files, &dirs));
let expect = [
"/home/u/.local/share/fonts",
"/home/u/.fonts",
"/etc/profiles/per-user/u/share/fonts",
"/usr/local/share/fonts",
"/usr/share/fonts",
"/run/host/fonts",
"/run/host/local-fonts",
"/run/host/user-fonts",
"/nix/store/bbb-dejavu-fonts-2.37",
"/nix/store/ccc-unifont-16.0.03",
"/nix/store/eee-home-manager-path/share/fonts",
"/nix/store/aaa-dejavu-fonts-minimal-2.37",
];
assert_eq!(d, paths(&expect));
}
#[test]
fn fontconfig_dirs_debian_style() {
let files = [
(
"/etc/fonts/fonts.conf",
"<fontconfig>\n<dir>/usr/share/fonts</dir>\n<dir>/usr/local/share/fonts</dir>\n<dir prefix=\"xdg\">fonts</dir>\n\
<dir>~/.fonts</dir>\n<dir>/opt/fonts &amp; more</dir>\n<dir>relative/skipped</dir>\n<dir prefix=\"cwd\">also/skipped</dir>\n\
<include ignore_missing=\"yes\">conf.d</include>\n</fontconfig>\n",
),
("/etc/fonts/conf.d/51-local.conf", "<fontconfig><include ignore_missing=\"yes\">local.conf</include></fontconfig>"),
("/etc/fonts/conf.d/52-site.conf", "<fontconfig><include prefix=\"relative\">../site/fonts.conf</include></fontconfig>"),
("/etc/fonts/local.conf", "<fontconfig><dir>/srv/fonts</dir><dir prefix=\"relative\">more</dir></fontconfig>"),
("/etc/fonts/conf.d/../site/fonts.conf", "<fontconfig><dir>/site/fonts</dir></fontconfig>"),
];
let dirs: [(&str, &[&str]); 1] = [("/etc/fonts/conf.d", &["/etc/fonts/conf.d/51-local.conf", "/etc/fonts/conf.d/52-site.conf"])];
let d = font_dirs(env_of(&[("HOME", "/home/u")]), reader(&files, &dirs));
let tail: Vec<PathBuf> = d.iter().skip(7).cloned().collect();
assert_eq!(tail, paths(&["/opt/fonts & more", "/srv/fonts", "/etc/fonts/more", "/site/fonts"]));
assert_eq!(d.len(), 11, "the directories already listed are not repeated: {d:?}");
}
#[test]
fn fontconfig_file_and_path_variables() {
let files = [("/cfg/custom.conf", "<fontconfig><dir>/custom/fonts</dir></fontconfig>")];
let env = env_of(&[("FONTCONFIG_FILE", "custom.conf"), ("FONTCONFIG_PATH", "/nowhere:/cfg")]);
let d = font_dirs(env, reader(&files, &[]));
assert_eq!(d.last(), Some(&PathBuf::from("/custom/fonts")));
let d = font_dirs(env_of(&[("FONTCONFIG_FILE", "/cfg/custom.conf")]), reader(&files, &[]));
assert_eq!(d.last(), Some(&PathBuf::from("/custom/fonts")));
assert_eq!(font_dirs(env_of(&[("FONTCONFIG_FILE", "/cfg/missing.conf")]), reader(&files, &[])), paths(XDG));
}
#[test]
fn fontconfig_path_names_the_default_configuration() {
// FONTCONFIG_PATH alone: its fonts.conf is the configuration, and /etc/fonts still
// follows it in the path, as in fontconfig.
let files = [
("/cfg/fonts.conf", "<fontconfig><dir>/cfg/fonts</dir></fontconfig>"),
("/etc/fonts/fonts.conf", "<fontconfig><dir>/etc/listed</dir></fontconfig>"),
];
let d = font_dirs(env_of(&[("FONTCONFIG_PATH", "/nowhere:/cfg")]), reader(&files, &[]));
assert_eq!(d.last(), Some(&PathBuf::from("/cfg/fonts")), "{d:?}");
let d = font_dirs(env_of(&[("FONTCONFIG_PATH", "/nowhere")]), reader(&files, &[]));
assert_eq!(d.last(), Some(&PathBuf::from("/etc/listed")), "{d:?}");
}
#[test]
fn prefix_attributes_with_whitespace_around_equals() {
// Legal XML: whitespace, newlines included, on either side of '=', attributes in any
// order. /cfg is not on the configuration path, so a relative include or directory is
// found only through its prefix.
let files = [
(
"/cfg/fonts.conf",
"<fontconfig>\n<dir prefix = \"relative\">extra-fonts</dir>\n<dir\n prefix\n =\n 'xdg'\n>more-fonts</dir>\n\
<include ignore_missing = \"yes\" prefix = \"xdg\">fontconfig/fonts.conf</include>\n\
<include\n\tignore_missing=\"yes\"\n\tprefix\n\t=\n\t\"relative\"\n>site.conf</include>\n</fontconfig>\n",
),
("/home/u/.config/fontconfig/fonts.conf", "<fontconfig><dir>/xdg-included</dir></fontconfig>"),
("/cfg/site.conf", "<fontconfig><dir>/site-included</dir></fontconfig>"),
];
let env = env_of(&[("HOME", "/home/u"), ("XDG_DATA_HOME", "/data"), ("FONTCONFIG_FILE", "/cfg/fonts.conf")]);
let d = font_dirs(env, reader(&files, &[]));
let tail: Vec<PathBuf> = d.iter().skip(XDG.len() + 2).cloned().collect();
assert_eq!(tail, paths(&["/cfg/extra-fonts", "/data/more-fonts", "/xdg-included", "/site-included"]));
}
#[test]
fn include_cycles_and_depth_are_bounded() {
let files = [
("/etc/fonts/fonts.conf", "<fontconfig><dir>/d0</dir><include>/etc/fonts/b.conf</include></fontconfig>"),
(
"/etc/fonts/b.conf",
"<fontconfig><dir>/d1</dir><include>/etc/fonts/fonts.conf</include><include>/etc/fonts/b.conf</include></fontconfig>",
),
];
let d = font_dirs(|_| None, reader(&files, &[]));
assert_eq!(d.iter().skip(XDG.len()).cloned().collect::<Vec<_>>(), paths(&["/d0", "/d1"]));
let chain: Vec<(String, String)> = (0..10)
.map(|i| {
(format!("/etc/fonts/{i}.conf"), format!("<fontconfig><dir>/depth{i}</dir><include>/etc/fonts/{}.conf</include></fontconfig>", i + 1))
})
.collect();
let read = |p: &Path| chain.iter().find(|(n, _)| Path::new(n) == p).map(|(_, xml)| Include::File(xml.clone()));
let d = font_dirs(env_of(&[("FONTCONFIG_FILE", "/etc/fonts/0.conf")]), read);
let depths: Vec<&PathBuf> = d.iter().skip(XDG.len()).collect();
assert_eq!(depths.len(), MAX_INCLUDE_DEPTH + 1, "{depths:?}");
assert_eq!(depths.last().map(|p| p.as_path()), Some(Path::new("/depth4")));
}
#[test]
fn many_files_are_bounded() {
let names: Vec<String> = (0..1000).map(|i| format!("/etc/fonts/conf.d/{i:04}.conf")).collect();
let read = |p: &Path| {
if p == Path::new("/etc/fonts/fonts.conf") {
return Some(Include::File("<fontconfig><include>/etc/fonts/conf.d</include></fontconfig>".into()));
}
if p == Path::new("/etc/fonts/conf.d") {
return Some(Include::Dir(names.iter().map(PathBuf::from).collect()));
}
p.starts_with("/etc/fonts/conf.d").then(|| Include::File(format!("<fontconfig><dir>{}</dir></fontconfig>", p.display())))
};
let d = font_dirs(|_| None, read);
assert!(d.len() <= XDG.len() + MAX_CONFIG_FILES, "{}", d.len());
assert!(d.len() > XDG.len() + 200);
}
#[test]
fn elements_survive_odd_markup() {
let xml = "<dir><dir>/unterminated<include>/x</include><dir prefix='relative'>r</dir><dir></dir><!-- never closed <dir>/no</dir>";
let e = elements(xml);
let got: Vec<(&str, Option<&str>, &str)> = e.iter().map(|e| (e.name, e.prefix, e.text.as_str())).collect();
assert_eq!(got, [("dir", None, "/unterminated"), ("include", None, "/x"), ("dir", Some("relative"), "r")]);
assert!(elements("").is_empty());
assert!(elements("<").is_empty());
assert!(elements("<dir").is_empty());
let huge: String = "<dir>/a</dir>".repeat(MAX_ELEMENTS * 2);
assert_eq!(elements(&huge).len(), MAX_ELEMENTS);
}
#[test]
fn attributes_in_any_order_and_spacing() {
let prefix = |xml: &str| elements(xml).first().and_then(|e| e.prefix).map(str::to_string);
assert_eq!(prefix("<dir salt=\"x\" prefix='xdg'>f</dir>"), Some("xdg".into()));
assert_eq!(prefix("<dir prefix=\"relative\" salt=\"x\">f</dir>"), Some("relative".into()));
assert_eq!(prefix("<dir salt = 'prefix=\"xdg\"' prefix = \"cwd\">f</dir>"), Some("cwd".into()), "a value is not an attribute");
assert_eq!(prefix("<include\nignore_missing = \"yes\"\nprefix\n=\n\"xdg\"\n>f</include>"), Some("xdg".into()));
assert_eq!(prefix("<dir prefix=xdg>f</dir>"), None, "an unquoted value is not well-formed");
assert_eq!(prefix("<dir prefix>f</dir>"), None);
assert_eq!(prefix("<dir prefix=\"unterminated>f</dir>"), None);
assert_eq!(prefix("<dir salt=\"x\">f</dir>"), None);
}
#[test]
fn read_config_skips_oversize_files_and_lists_conf_files() {
let dir = std::env::temp_dir().join(format!(
"cadcraft-fontdirs-{}-{}",
std::process::id(),
std::time::UNIX_EPOCH.elapsed().map(|d| d.as_nanos()).unwrap_or(0)
));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("10-small.conf"), "<fontconfig><dir>/small</dir></fontconfig>").unwrap();
std::fs::write(dir.join("05-first.conf"), "<fontconfig/>").unwrap();
std::fs::write(dir.join("README"), "not a config").unwrap();
std::fs::write(dir.join("local.conf"), "<fontconfig/>").unwrap();
std::fs::write(dir.join("99-big.conf"), vec![b' '; (MAX_CONFIG_BYTES + 1) as usize]).unwrap();
match read_config(&dir) {
Some(Include::Dir(files)) => assert_eq!(files, [dir.join("05-first.conf"), dir.join("10-small.conf"), dir.join("99-big.conf")]),
_ => panic!("a directory lists its [0-9]*.conf files"),
}
assert!(matches!(read_config(&dir.join("10-small.conf")), Some(Include::File(x)) if x.contains("/small")));
assert!(read_config(&dir.join("99-big.conf")).is_none(), "oversize file skipped");
assert!(read_config(&dir.join("missing.conf")).is_none());
let small = dir.join("10-small.conf").to_string_lossy().into_owned();
let d = font_dirs(env_of(&[("FONTCONFIG_FILE", &small)]), read_config);
assert_eq!(d.last(), Some(&PathBuf::from("/small")));
std::fs::remove_dir_all(&dir).unwrap();
}
}
+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
}
+106
View File
@@ -0,0 +1,106 @@
//! The angles of a hatch's elliptic boundary edges in the DXF a DWG is read through.
//!
//! A DWG holds an elliptic edge's start and end angles in radians, and so does the DXF the DWG
//! decoder writes (groups 50 and 51 of an edge of type 3). DXF itself keeps them in degrees, which
//! is how [`crate::dxf_read`] reads them: a circle stored as an elliptic edge with the end angle
//! 6.2832 became an arc of 6.28 degrees, and the hatch covered the hole it should have left open.
//! Only the DWG path needs this; a DXF file is read as written.
use std::f64::consts::PI;
/// `dxf` with the start and end angles (groups 50 and 51) of every elliptic hatch edge (edge type
/// 3, group 72) turned from radians to degrees. The text is handled as bytes: a drawing from
/// before 2007 is written in its code page, which is not UTF-8, and every other byte is kept as it
/// was. Binary DXF, and text with no such edge, come back as they were.
pub(crate) fn elliptic_edge_degrees(dxf: Vec<u8>) -> Vec<u8> {
if dxf.starts_with(b"AutoCAD Binary DXF") || !dxf.windows(5).any(|w| w == b"HATCH") {
return dxf;
}
let mut out = Vec::with_capacity(dxf.len());
let mut lines = dxf.split_inclusive(|b| *b == b'\n');
let mut in_hatch = false;
// After an elliptic edge's type, until the next edge or loop: the angles still to convert.
let mut ellipse = false;
let mut changed = false;
while let Some(code_line) = lines.next() {
let Some(value_line) = lines.next() else {
out.extend_from_slice(code_line);
break;
};
let code = code_line.trim_ascii();
let value = value_line.trim_ascii();
match code {
b"0" => {
in_hatch = value == b"HATCH";
ellipse = false;
}
b"72" if in_hatch => ellipse = value == b"3",
b"92" | b"97" if in_hatch => ellipse = false,
b"50" | b"51" if in_hatch && ellipse => {
if let Some(radians) = std::str::from_utf8(value).ok().and_then(|v| v.parse::<f64>().ok()).filter(|v| v.is_finite()) {
let ending = &value_line[value_line.trim_ascii_end().len()..];
out.extend_from_slice(code_line);
out.extend_from_slice(format!("{}", radians * 180.0 / PI).as_bytes());
out.extend_from_slice(ending);
changed = true;
continue;
}
}
_ => {}
}
out.extend_from_slice(code_line);
out.extend_from_slice(value_line);
}
if changed { out } else { dxf }
}
#[cfg(test)]
mod tests {
use super::*;
fn pairs(text: &str) -> Vec<(String, String)> {
let lines: Vec<&str> = text.lines().collect();
lines.chunks(2).filter_map(|c| Some((c.first()?.trim().to_string(), c.get(1)?.trim().to_string()))).collect()
}
const HATCH: &str = "0\r\nHATCH\r\n91\r\n1\r\n92\r\n1\r\n93\r\n2\r\n72\r\n3\r\n10\r\n5.0\r\n20\r\n6.0\r\n11\r\n-55.5\r\n21\r\n0.0\r\n40\r\n1.0\r\n50\r\n0.0\r\n51\r\n6.283185307179586\r\n73\r\n1\r\n72\r\n1\r\n10\r\n1.0\r\n20\r\n2.0\r\n11\r\n3.0\r\n21\r\n4.0\r\n50\r\n7.0\r\n0\r\nLINE\r\n50\r\n9.0\r\n";
#[test]
fn an_elliptic_edge_gets_its_angles_in_degrees_and_nothing_else_changes() {
let out = String::from_utf8(elliptic_edge_degrees(HATCH.as_bytes().to_vec())).unwrap();
let p = pairs(&out.replace("\r\n", "\n"));
let value = |code: &str, n: usize| p.iter().filter(|(c, _)| c == code).nth(n).map(|(_, v)| v.parse::<f64>().unwrap());
assert!((value("51", 0).unwrap() - 360.0).abs() < 1e-9);
assert_eq!(value("50", 0), Some(0.0));
// A line edge's 50 and another entity's are left alone, as is the line ending.
assert_eq!(value("50", 1), Some(7.0));
assert_eq!(value("50", 2), Some(9.0));
assert!(out.contains("\r\n") && !out.replace("\r\n", "").contains('\r'));
}
/// A drawing from before 2007 is written in its code page: an accented letter is one byte that
/// is not valid UTF-8, and it must not stop the angles being converted or change.
#[test]
fn a_code_page_drawing_still_has_its_angles_converted() {
let mut dxf = b"0\r\nTEXT\r\n1\r\ncaf".to_vec();
dxf.push(0xE9);
dxf.extend_from_slice(b"\r\n");
dxf.extend_from_slice(HATCH.as_bytes());
let out = elliptic_edge_degrees(dxf.clone());
assert!(std::str::from_utf8(&dxf).is_err(), "the input is not UTF-8");
assert!(out.windows(4).any(|w| w == b"caf\xE9"), "the accented byte is kept");
let text: String = out.iter().map(|b| char::from(*b)).collect();
assert!(text.contains("51\r\n360"), "the end angle is 360 degrees: {text}");
}
#[test]
fn text_without_a_hatch_ellipse_comes_back_untouched() {
let dxf = b"0\nLINE\n50\n1.5\n".to_vec();
assert_eq!(elliptic_edge_degrees(dxf.clone()), dxf);
let binary = b"AutoCAD Binary DXF\r\n\x1a\x00HATCH".to_vec();
assert_eq!(elliptic_edge_degrees(binary.clone()), binary);
// A hatch with no elliptic edge is left as it is.
let plain = "0\nHATCH\n72\n1\n50\n2.0\n".as_bytes().to_vec();
assert_eq!(elliptic_edge_degrees(plain.clone()), plain);
}
}
+3 -15
View File
@@ -79,24 +79,12 @@ fn has_images(store: &EntityStore) -> bool {
}
/// Fill in each image's definition (path, name, pixel size) from the IMAGEDEF it points to.
pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
/// `refs`: each IMAGE entity's handle in the drawing → its IMAGEDEF handle (upper case), noted
/// as the entity was read, so an image whose repeated handle was reassigned keeps its own.
pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing, refs: &HashMap<Handle, String>) {
if !has_images(&d.model) && !d.layouts.iter().any(|l| has_images(&l.entities)) && !d.blocks.values().any(|b| has_images(&b.entities)) {
return;
}
// IMAGE handle → IMAGEDEF handle.
let mut refs: HashMap<Handle, String> = HashMap::new();
for s in secs.iter().filter(|s| s.name == "ENTITIES" || s.name == "BLOCKS") {
each_record(s.tags, |kind, tags| {
if kind != "IMAGE" {
return;
}
let h = tags.iter().find(|t| t.code == 5).and_then(|t| Handle::parse_hex(&t.str()));
let def = tags.iter().find(|t| t.code == 340).map(|t| key(&t.str()));
if let (Some(h), Some(def)) = (h, def) {
refs.insert(h, def);
}
});
}
// IMAGEDEF objects, and the names dictionaries give them.
let mut defs: HashMap<String, Def> = HashMap::new();
let mut names: HashMap<String, String> = HashMap::new();
+179 -13
View File
@@ -16,9 +16,9 @@ use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number};
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number, proxy_has_string_stream};
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown};
use craft_dxf::{SectionRef, Tag};
use craft_dxf::{SectionRef, Tag, Version};
/// Named object dictionary entries CADCraft writes itself from its model (plus every key that
/// starts with `CADCRAFT`): they are read into the model, not kept raw. A change that starts
@@ -457,6 +457,10 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
if !f.is_empty() {
f.version = file_version(secs);
}
// Added after the version: registered applications alone are no kept objects whose groups
// the DWG writer must read as the file's version, and nearly every file has some (ACAD).
let appids = tables.iter().filter(|(k, _, _)| k == "APPID").filter_map(|(_, _, t)| val(t, 2)).map(|n| n.trim().to_string());
f.appids = appids.take(MAX_OBJECTS).collect();
// The file's handles of the objects CADCraft writes itself (AutoLISP's `handent`).
f.handles = ids.iter().filter(|(h, _)| !ents.contains_key(*h)).filter_map(|(h, k)| Some((handle(h)?, k.clone()))).take(MAX_OBJECTS).collect();
if !f.is_empty() || !f.handles.is_empty() {
@@ -686,6 +690,102 @@ pub(crate) fn data_store(tags: &mut Vec<Tag>, d: &Drawing, modern: bool) {
tags.splice(at..at, out);
}
/// Most constraint nodes, and connections per node, looked at in one constraint group.
const MAX_CONSTRAINT_NODES: usize = 100_000;
/// Put the status of every node of the kept 2D constraint groups (`ACDBASSOC2DCONSTRAINTGROUP`)
/// where a reader of the version the text is read as expects it: AutoCAD 2013 and later
/// (`modern`) write it after the node's connections, earlier versions right after its id. The
/// groups are kept as read, so a 2013+ drawing written in an older version's form had them in the
/// wrong order, and its reader took every node's status from somewhere else: AutoCAD refused the
/// DWG the bridge made from it ("Error Decrypting Data"). A group whose nodes can't all be found
/// is left as it is.
pub(crate) fn constraint_node_order(tags: &mut [Tag], modern: bool) {
let mut i = 0;
while i < tags.len() {
let end = tags.iter().skip(i + 1).position(|t| t.code == 0).map_or(tags.len(), |k| i + 1 + k);
if tags.get(i).is_some_and(|t| t.code == 0 && t.str().trim().eq_ignore_ascii_case("ACDBASSOC2DCONSTRAINTGROUP"))
&& let Some(rec) = tags.get_mut(i + 1..end)
{
constraint_group_order(rec, modern);
}
i = end;
}
}
/// [`constraint_node_order`] for one group's groups after its type.
fn constraint_group_order(rec: &mut [Tag], modern: bool) {
let Some(start) = rec.iter().position(|t| t.code == 100 && t.str().trim().eq_ignore_ascii_case("AcDbAssoc2dConstraintGroup")) else {
return;
};
let end = rec.iter().skip(start + 1).position(|t| t.code == 100 || t.code >= 1000).map_or(rec.len(), |k| start + 1 + k);
let Some(sec) = rec.get_mut(start + 1..end) else { return };
let Some(nodes) = constraint_nodes(sec) else { return };
for (at, len, old) in nodes {
// Old order: id, status, count, connections; modern: id, count, connections, status.
if let Some(head) = sec.get_mut(at + 1..at + len) {
match (old, modern) {
(true, true) => head.rotate_left(1),
(false, false) => head.rotate_right(1),
_ => {}
}
}
}
}
/// Where each non-root node of a constraint group section starts: (index of its id, length of its
/// id, status and connections, whether its status comes right after the id). `None` unless every
/// node the group lists is found.
fn constraint_nodes(sec: &[Tag]) -> Option<Vec<(usize, usize, bool)>> {
let int = |p: usize, code: i32| sec.get(p).filter(|t| t.code == code).and_then(|t| t.str().trim().parse::<i64>().ok());
let count = |p: usize| int(p, 90).and_then(|n| usize::try_from(n).ok()).filter(|n| *n <= MAX_CONSTRAINT_NODES);
// Version, flag and work plane, then the dependency and the actions.
let mut p = sec.iter().position(|t| t.code == 360)? + 1;
p += count(p)? + 1;
// The next node id, then the root node: id, connections, status (290).
int(p, 90)?;
int(p + 1, 90)?;
p += count(p + 2)? + 3;
int(p, 290)?;
p += 1;
// The registry: class name and id of each node.
let n = count(p)?;
p += 1;
let mut ids = Vec::with_capacity(n);
for _ in 0..n {
sec.get(p).filter(|t| t.code == 1)?;
ids.push(int(p + 1, 90)?);
p += 2;
}
let known: HashSet<i64> = ids.iter().copied().collect();
// Groups looked at while searching for headers, capped so a hostile group can't take long.
let budget = std::cell::Cell::new(MAX_CONSTRAINT_NODES.saturating_mul(100));
// A node header at `q`: its length and whether it is in the old order. Connections are ids of
// nodes (or of the root, 0), which keeps a node's data from passing for the next header.
let header = |q: usize, id: i64| -> Option<(usize, bool)> {
int(q, 90).filter(|v| *v == id)?;
let old = sec.get(q + 1)?.code == 70;
let c = q + 1 + usize::from(old);
let n = count(c).filter(|n| *n <= known.len())?;
budget.set(budget.get().checked_sub(n + 1)?);
for k in 0..n {
int(c + 1 + k, 90).filter(|v| *v == 0 || known.contains(v))?;
}
if !old {
int(c + 1 + n, 70)?;
}
Some((n + 3, old))
};
let mut out = Vec::with_capacity(ids.len());
for id in ids {
let at = (p..sec.len()).find(|q| header(*q, id).is_some())?;
let (len, old) = header(at, id)?;
out.push((at, len, old));
p = at + len;
}
Some(out)
}
/// Drop a dictionary's modelled entries (key and handle) from its groups.
fn strip_entries(tags: &mut Vec<RawTag>) {
let mut out = Vec::with_capacity(tags.len());
@@ -941,13 +1041,61 @@ fn unknown_handles(d: &Drawing) -> HashSet<String> {
all_entities(d).filter(|e| matches!(e.kind, EntityKind::Unknown(_))).map(|e| e.handle.hex()).collect()
}
/// Render settings (`RENDERSETTINGS`, `MENTALRAYRENDERSETTINGS`, `RAPIDRTRENDERSETTINGS`) store
/// their `AcDbRenderSettings` class version (the first group 90 after that marker) in the form of
/// the file's version: a 2013+ file stores it one higher, and a 2013 file stores a rapid RT one
/// one lower, as acadrust reads and writes them (`write_render_settings_dxf` in acadrust 0.6.6's
/// `io/dxf/writer/section_writer.rs`, and its DWG class-object reader and writer; the test
/// `render_settings_class_version_matches_what_acadrust_writes` fails if the two drift apart). A
/// kept object carries the form of the file it was read from ([`Foreign::version`], not the
/// drawing's `$ACADVER`, which SAVEAS changes); written into a file read as another version, it
/// takes that version's form. The DWG bridge's R2000 text is read as the version the kept objects
/// came from (craft-dwg's `encode_kept_noted`), so there they stay as read (#907, #2471).
///
/// Only that first group 90 is converted, on purpose: the group 90 that starts a kind's own
/// subclass (`AcDbMentalRayRenderSettings`, `AcDbRapidRTRenderSettings`) is that kind's version,
/// stored the same in every file version, and is left as read.
pub(crate) fn render_settings_versions(tags: &mut [Tag], source: Option<Version>, declared: Version) {
let Some(source) = source.filter(|s| *s != declared) else { return };
let shift = |rapid: bool, v: Version| if rapid { -i64::from(v == Version::R2013) } else { i64::from(v >= Version::R2013) };
let (mut kind, mut in_base) = (String::new(), false);
for t in tags.iter_mut() {
match t.code {
0 => {
kind = up(&t.str());
in_base = false;
}
100 if matches!(kind.as_str(), "RENDERSETTINGS" | "MENTALRAYRENDERSETTINGS" | "RAPIDRTRENDERSETTINGS") => {
in_base = t.str().trim().eq_ignore_ascii_case("AcDbRenderSettings");
}
90 if in_base => {
let rapid = kind == "RAPIDRTRENDERSETTINGS";
let logical = t.i64().saturating_sub(shift(rapid, source));
*t = Tag::i(90, logical.saturating_add(shift(rapid, declared)));
in_base = false;
}
_ => {}
}
}
}
/// Put the drawing's foreign data back into a written file's tags (see the module comment).
pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle, Vec<String>>, modern: bool) {
/// `strings`: whether the file has a form for a proxy's separate string stream (a DXF of 2007 or
/// later, or the DWG bridge); without one such a proxy is left out (#3229). Returns the foreign
/// objects written, by their handles in the drawing (the file gives them new ones).
pub(crate) fn finish(
tags: &mut Vec<Tag>,
d: &Drawing,
reactors: &HashMap<Handle, Vec<String>>,
modern: bool,
target_modern: bool,
strings: bool,
) -> HashSet<Handle> {
let f = d.foreign.as_ref();
let unknown = unknown_handles(d);
let xd: XdataOf = all_entities(d).filter(|e| !e.common.xdata.is_empty()).map(|e| (e.handle, e.common.xdata.as_slice())).collect();
if f.is_empty() && unknown.is_empty() && xd.is_empty() {
return;
return HashSet::new();
}
let recs = written_records(tags);
let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]);
@@ -970,14 +1118,21 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
numbers.entry(n).or_insert(500_i64.saturating_add(i64::try_from(i).unwrap_or(i64::MAX)));
}
let renumber = |old| proxy_class_number(f, &numbers, old);
// A proxy is dropped when its class isn't written, or when its strings have no place here.
let no_room = |t: &[(i32, &str)]| !strings && proxy_has_string_stream(t.iter().copied());
// Entities of types CADCraft doesn't model, placed among the written ones.
let mut planned = plan_unknown(d, &recs, tags, &roles, modern);
let mut planned = plan_unknown(d, &recs, tags, &roles, modern, target_modern);
for list in planned.values_mut() {
list.retain_mut(|(_, t)| {
if !t.first().is_some_and(|z| is_proxy(&z.str())) {
return true;
}
let Some(n) = renumber(class_number(t.iter().map(|x| (x.code, x.str())))) else { return false };
let groups: Vec<(i32, String)> = t.iter().map(|x| (x.code, x.str())).collect();
let groups: Vec<(i32, &str)> = groups.iter().map(|(c, v)| (*c, v.as_str())).collect();
if no_room(&groups) {
return false;
}
let Some(n) = renumber(class_number(groups.iter().copied())) else { return false };
set_class_number(t, n);
true
});
@@ -1015,8 +1170,11 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
// Keep established live paths available to descendants during this pass as well.
let mut alive_memo: HashMap<String, bool> = kept.iter().filter(|(_, live)| **live).map(|(h, &live)| (h.clone(), live)).collect();
let kept = |h: &str| kept.get(h) == Some(&true);
for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none())
{
let dropped = |o: &ForeignObject| {
let groups: Vec<(i32, &str)> = o.tags.iter().map(|r| (r.code, r.value.as_str())).collect();
no_room(&groups) || renumber(class_number(groups.iter().copied())).is_none()
};
for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && dropped(o)) {
alive_memo.insert(o.handle.hex(), false);
}
for o in &f.objects {
@@ -1113,7 +1271,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
join_entries(&map, b, kept, &mut out);
}
}
add_appids(&mut out);
add_appids(&mut out, &f.appids);
let top = max_handle(&out).saturating_add(1);
if let Some(t) = seed_index(&out).and_then(|i| out.get_mut(i))
&& Handle::parse_hex(&t.str()).is_none_or(|h| h.0 < top)
@@ -1121,6 +1279,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
*t = Tag::s(5, format!("{top:X}"));
}
*tags = out;
map.alive.keys().filter_map(|h| handle(h)).collect()
}
/// Kept extension dictionaries of written records: those that go on a record without its own,
@@ -1202,6 +1361,7 @@ fn plan_unknown(
tags: &[Tag],
roles: &HashMap<ForeignKey, String>,
modern: bool,
target_modern: bool,
) -> HashMap<usize, Vec<(String, Vec<Tag>)>> {
let stored = d.foreign.data_store_entities();
let mut out: HashMap<usize, Vec<(String, Vec<Tag>)>> = HashMap::new();
@@ -1241,7 +1401,9 @@ fn plan_unknown(
for e in store.iter() {
match &e.kind {
EntityKind::Unknown(u) => {
if modern && cadcraft_doc::foreign::sat_text_acis(u, e.handle, &stored) {
if (modern && cadcraft_doc::foreign::sat_text_acis(u, e.handle, &stored))
|| (!target_modern && cadcraft_doc::foreign::acis_left_out(u, e.handle, &stored, false))
{
continue;
}
let t = unknown_entity(u, e, &owner, paper);
@@ -1435,9 +1597,13 @@ fn xdata(map: &Map, x: &ForeignExtra, own: &HashSet<String>, out: &mut Vec<Tag>)
}
}
/// APPID records for every application with xdata in the file, added to the APPID table.
fn add_appids(out: &mut Vec<Tag>) {
let used: BTreeMap<String, String> = out.iter().filter(|t| t.code == 1001).map(|t| (up(&t.str()), t.str().trim().to_string())).collect();
/// APPID records for every application with xdata in the file and every one the file read had
/// (`kept`), added to the APPID table.
fn add_appids(out: &mut Vec<Tag>, kept: &[String]) {
let mut used: BTreeMap<String, String> = out.iter().filter(|t| t.code == 1001).map(|t| (up(&t.str()), t.str().trim().to_string())).collect();
for name in kept.iter().filter(|n| !n.is_empty()) {
used.entry(up(name)).or_insert_with(|| name.clone());
}
let recs = written_records(out);
let Some(table) = recs.iter().position(|r| {
r.sec == "TABLES" && r.kind == "TABLE" && val(out.get(r.start + 1..r.end).unwrap_or(&[]), 2).is_some_and(|n| up(&n) == "APPID")
+77 -6
View File
@@ -1,6 +1,6 @@
//! DXF → Drawing.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use cadcraft_color::{Color, Rgb};
use cadcraft_doc::{
@@ -24,8 +24,8 @@ mod tables;
mod text;
use document::{
apply_sortents, count_skipped, dropped_paper_views, outside_sections, parse_entities, place_blocks, place_entities, read_blocks, read_objects,
setup_layouts,
HandlePolicy, apply_sortents, count_skipped, dropped_paper_views, outside_sections, parse_entities, place_blocks, place_entities, read_blocks,
read_objects, setup_layouts,
};
#[cfg(test)]
use entities::acad_table;
@@ -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
@@ -71,6 +74,28 @@ struct Rx {
block: Option<String>,
/// The points HATCH boundary curves may still be sampled into.
curves: hatch::CurvePoints,
/// IMAGE entity handle, as read (a repeated one reassigned) → its IMAGEDEF handle (upper case).
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.
@@ -102,6 +127,18 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
let mut blocks: Vec<BlockDef> = Vec::new();
let mut layout_objs: Vec<LayoutDef> = Vec::new();
let mut entities = Vec::new();
// One set for every list: a generated handle must be unique across blocks and ENTITIES
// (a *MODEL_SPACE block and an ENTITIES record both land in the model space).
let mut seen_handles = HashSet::new();
// Model/paper-space handles retain priority if an in-memory drawing or damaged DXF also
// assigns one to a block entity. This preserves top-level references while letting block
// handles be repaired before their deferred fixups are recorded.
let reserved_entity_handles: HashSet<Handle> = secs
.iter()
.filter(|s| s.name == "ENTITIES")
.flat_map(|s| record_slices(s.tags))
.filter_map(|(_, tags)| common::T(tags).s(5).and_then(|h| Handle::parse_hex(&h)))
.collect();
let mut objs = Objects::default();
// Every handle another program's file already uses is taken before anything gets a new one:
// its $HANDSEED can be lower than its handles, and entities made while reading (the faces of
@@ -145,17 +182,33 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
match s.name {
"HEADER" => header(s.tags, &mut d),
"TABLES" => tables(s.tags, &mut d, &mut rx),
"BLOCKS" => blocks.extend(read_blocks(s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped)),
"BLOCKS" => {
blocks.extend(read_blocks(s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped, &mut seen_handles, &reserved_entity_handles))
}
// A damaged file may split its entities over several ENTITIES sections (#865).
"ENTITIES" => {
let mut n = 0;
entities.extend(parse_entities(&record_slices(s.tags), &mut d, &mut rx, &mut n, &mut table_cells_left));
entities.extend(parse_entities(
&record_slices(s.tags),
&mut d,
&mut rx,
&mut n,
&mut table_cells_left,
&mut HandlePolicy { seen: &mut seen_handles, reserved: &reserved_entity_handles, source_wins: true },
));
count_skipped(&mut skipped, "ENTITIES", n);
}
"OBJECTS" => read_objects(s.tags, &mut objs, &mut layout_objs),
_ => {}
}
}
// 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()));
@@ -165,7 +218,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
number_unknown_viewport_ids(&mut d, &dropped_paper_views(&rx, &paper_block_for, &first_layout));
apply_sortents(&mut d, &objs.sortents, &rx.brs, &paper_block_for, &first_layout);
objs.apply(&mut d, &rx);
crate::dxf_image::resolve(&secs, &mut d);
crate::dxf_image::resolve(&secs, &mut d, &rx.image_defs);
crate::dxf_mline::resolve(&secs, &mut d);
// Keep handles unique against the header's seed.
let seed = d.header.str("HANDSEED", "");
@@ -189,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)
}
@@ -221,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.
+62 -13
View File
@@ -1,14 +1,57 @@
use std::collections::HashSet;
use super::common::T;
use super::entities::{entity_extras, entity_plot_style, entity_with_table_budget, insert_attribs, polyline_entity};
use super::objects::{MAX_OBJECTS, Objects, page_setup};
use super::{Block, BlockDef, Drawing, Entity, EntityKind, Handle, HashMap, Layout, LayoutDef, Rx, Tag, Vec2, record_slices};
/// Allocate an entity handle that is unique within the DXF, including against handles assigned
/// to earlier malformed or generated entities.
fn fresh_entity_handle(d: &mut Drawing, seen: &mut HashSet<Handle>, reserved: &HashSet<Handle>) -> Handle {
// The seed saturates at `u64::MAX`: once a file uses that handle, `new_handle` keeps
// returning it and a plain retry loop would never terminate. Stop as soon as it stops
// advancing.
let mut previous = None;
loop {
let h = d.new_handle();
if !reserved.contains(&h) && seen.insert(h) {
return h;
}
if previous == Some(h) {
break;
}
previous = Some(h);
}
// Every value the seed can still reach is taken, so scan from the bottom: the occupied set
// is finite, which guarantees a free handle within its size plus one candidates.
let limit = seen.len().saturating_add(reserved.len()).saturating_add(1);
let mut candidate = 1u64;
for _ in 0..limit {
let h = Handle(candidate);
if !reserved.contains(&h) && seen.insert(h) {
return h;
}
candidate = candidate.saturating_add(1);
}
// Unreachable in practice (pigeonhole over the finite occupied set); never lose the entity.
d.new_handle()
}
/// How an ENTITIES list assigns handles: the handles already seen anywhere in the file, the
/// ones the block records reserved, and whether a record's own handle beats the reservation.
pub(super) struct HandlePolicy<'a> {
pub seen: &'a mut HashSet<Handle>,
pub reserved: &'a HashSet<Handle>,
pub source_wins: bool,
}
pub(super) fn parse_entities(
recs: &[(String, &[Tag])],
d: &mut Drawing,
rx: &mut Rx,
skipped: &mut usize,
table_cells_left: &mut usize,
hp: &mut HandlePolicy<'_>,
) -> Vec<(Option<String>, bool, Entity)> {
let mut out = Vec::new();
let mut i = 0;
@@ -58,13 +101,18 @@ pub(super) fn parse_entities(
// A file's handles keep their identity, however high they are (#913, #939).
Some(h) => {
d.bump_handseed(h);
h
// A file's own handle wins when it is the first copy on a source list that
// keeps them (ENTITIES); block copies yield to the reserved top-level ones.
let kept = if hp.source_wins { hp.seen.insert(h) } else { !hp.reserved.contains(&h) && hp.seen.insert(h) };
if kept { h } else { fresh_entity_handle(d, hp.seen, hp.reserved) }
}
None => d.new_handle(),
None => fresh_entity_handle(d, hp.seen, hp.reserved),
};
entity_extras(kind, tags, h, &mut k, rx);
let more: Vec<_> =
extra.into_iter().map(|f| (owner.clone(), paper, Entity { handle: d.new_handle(), common: c.clone(), kind: f })).collect();
let more: Vec<_> = extra
.into_iter()
.map(|f| (owner.clone(), paper, Entity { handle: fresh_entity_handle(d, hp.seen, hp.reserved), common: c.clone(), kind: f }))
.collect();
out.push((owner, paper, Entity { handle: h, common: c, kind: k }));
out.extend(more);
} else if kind == "HATCH" {
@@ -73,14 +121,6 @@ pub(super) fn parse_entities(
*skipped = skipped.saturating_add(1);
}
}
// Assign fresh handles to duplicates (hostile files).
let mut seen = std::collections::HashSet::new();
for (_, _, e) in &mut out {
if !seen.insert(e.handle) {
e.handle = d.new_handle();
seen.insert(e.handle);
}
}
out
}
@@ -91,6 +131,8 @@ pub(super) fn read_blocks(
rx: &mut Rx,
table_cells_left: &mut usize,
skipped: &mut std::collections::BTreeMap<String, usize>,
seen_handles: &mut HashSet<Handle>,
reserved_handles: &HashSet<Handle>,
) -> Vec<BlockDef> {
let recs = record_slices(tags);
for (k, tg) in &recs {
@@ -116,7 +158,14 @@ pub(super) fn read_blocks(
}
let body = recs.get(i + 1..j).unwrap_or(&[]);
rx.block = Some(name.to_ascii_uppercase());
let ents = parse_entities(body, d, rx, &mut n, table_cells_left);
let ents = parse_entities(
body,
d,
rx,
&mut n,
table_cells_left,
&mut HandlePolicy { seen: seen_handles, reserved: reserved_handles, source_wins: false },
);
rx.block = None;
blocks.push((name, base, description, ents, xref));
i = j + 1;
+40 -6
View File
@@ -88,6 +88,7 @@ fn lwpolyline(tags: &[Tag], c: &mut Common, t: &T) -> Option<EntityKind> {
// In a tilted plane: drawn as seen from above, at the vertices' mean height, its
// vertices now plan coordinates.
(verts, elevation) = plan_of_tilted(c.extrusion, elevation, &verts, flags & 1 != 0);
thickness_along_z(c);
c.extrusion = Vec3::Z;
} else if c.extrusion.z < 0.0 {
for v in &mut verts {
@@ -328,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))
@@ -487,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);
@@ -515,6 +521,13 @@ pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityK
rx.table_style_fix.push((h, t.s(342).map(|sh| sh.trim().to_ascii_uppercase()).unwrap_or_default()));
}
}
// Keyed by the handle the entity was given, so an IMAGE whose repeated handle was
// reassigned still finds its own IMAGEDEF.
("IMAGE", EntityKind::Image(_)) => {
if let Some(def) = tags.iter().find(|t| t.code == 340) {
rx.image_defs.insert(h, def.str().trim().to_ascii_uppercase());
}
}
("INSERT", EntityKind::Insert(ins)) => {
rx.inserted.insert(ins.block.to_ascii_uppercase());
}
@@ -570,7 +583,7 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
break;
}
}
let c = common(t);
let mut c = common(t);
let mut extra: Vec<EntityKind> = Vec::new();
let k = if flags & 64 != 0 {
// Face records that name a missing vertex (or fewer than three) are dropped: they draw
@@ -592,13 +605,26 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
} else if flags & 8 != 0 {
EntityKind::Polyline3d(Polyline3d { points: pts.iter().map(|p| p.0).collect(), closed: flags & 1 != 0 })
} else {
// A 2D polyline's vertices are in its OCS: mirrored like LWPOLYLINE.
let m = if c.extrusion.z < 0.0 { -1.0 } else { 1.0 };
// A 2D polyline's vertices are in its OCS, at the elevation of the POLYLINE's own point:
// in a tilted plane drawn as seen from above like LWPOLYLINE, else mirrored like it.
let closed = flags & 1 != 0;
let mut vertices: Vec<PolyVertex> = pts.iter().map(|p| PolyVertex { p: p.0.xy(), bulge: p.1, start_width: p.2, end_width: p.3 }).collect();
let mut elevation = t.p(10).z;
if tilted(c.extrusion, run_points(&vertices, elevation, closed)) {
(vertices, elevation) = plan_of_tilted(c.extrusion, elevation, &vertices, closed);
thickness_along_z(&mut c);
c.extrusion = Vec3::Z;
} else if c.extrusion.z < 0.0 {
for v in &mut vertices {
v.p.x = -v.p.x;
v.bulge = -v.bulge;
}
}
EntityKind::LwPolyline(LwPolyline {
vertices: pts.iter().map(|p| PolyVertex { p: Vec2::new(m * p.0.x, p.0.y), bulge: m * p.1, start_width: p.2, end_width: p.3 }).collect(),
closed: flags & 1 != 0,
vertices,
closed,
const_width: t.fd(40, 0.0).min(t.fd(41, 0.0)).max(0.0),
elevation: t.p(10).z,
elevation,
plinegen: flags & 128 != 0,
})
};
@@ -707,3 +733,11 @@ fn helix(tags: &[Tag]) -> Helix {
}
.sanitized()
}
/// A polyline drawn as seen from above gets the normal +Z: its thickness keeps the side of Z it
/// extruded toward, which the normal it is losing said.
fn thickness_along_z(c: &mut Common) {
if c.extrusion.z < 0.0 {
c.thickness = -c.thickness;
}
}
+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 {
+9
View File
@@ -421,6 +421,8 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
// Plot layout flags: 2 display plot styles, 4 centred, 16 standard scale (75 = 0: scaled
// to fit), 128 lineweights.
if let Some(flags) = t.i(70) {
// Kept to be written back (a 16-bit group: only those bits).
p.file_plot_flags = Some(flags & 0xFFFF);
p.show_plot_styles = flags & 2 != 0;
p.center = flags & 4 != 0;
p.lineweights = flags & 128 != 0;
@@ -432,6 +434,13 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
if let Some(s) = pos(ratio).or_else(|| pos(t.f(147))) {
p.scale = s;
}
// A standard scale (flag 16, group 75 above 0: 0 is scaled to fit, the DXF Reference lists
// 1 to 32), kept with the scale it stands for so a save can tell it was not changed.
if t.i(70).is_some_and(|f| f & 16 != 0)
&& let Some(code) = t.i(75).filter(|c| (1..=32).contains(c))
{
p.file_standard_scale = Some((code, p.scale));
}
p.plot_area = match t.i(74) {
Some(0) => "display",
Some(1) => "extents",
+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 => {
+61 -4
View File
@@ -24,6 +24,8 @@ mod entity;
mod header;
mod layout;
mod objects;
mod proxy;
pub use proxy::proxies_lost;
mod sections;
#[cfg(test)]
@@ -149,15 +151,70 @@ pub fn write(d: &Drawing) -> String {
/// The drawing's DXF tags, declaring `version` in `$ACADVER`.
pub fn tags(d: &Drawing, version: Version) -> Vec<Tag> {
tags_for(d, version, version, version < Version::R2004)
tags_kept(d, version).0
}
/// [`tags`], with the foreign objects the file keeps, by their handles in the drawing.
fn tags_kept(d: &Drawing, version: Version) -> (Vec<Tag>, std::collections::HashSet<cadcraft_doc::Handle>) {
let (mut tags, kept) = sections::tags_kept_for(d, version, version, version < Version::R2004, false);
// Kept proxies in this version's layout (#3229). Not for the DWG bridge, whose writer reads
// them in the layout of the DWG they came from.
proxy::proxy_layout(&mut tags, version);
(tags, kept)
}
/// 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.
+21 -6
View File
@@ -2,13 +2,15 @@ use super::{
Block, Color, Common, Dimension, Drawing, Entity, EntityKind, EntityStore, Handle, HashMap, Line, MText, Solid, Table, Vec2, Vec3, dxf_ext,
};
/// What happens to the anonymous `*D` blocks read from a file (#495): a dimension that still
/// names its block regenerates its geometry under that name, keeping the block's entity
/// handles, and `*D` blocks nothing else references are not written again.
/// What happens to the dimension blocks read from a file (#495): a dimension that still names
/// its block is written with that block, under its name, and `*D` blocks nothing else
/// references are not written again. The block a dimension names may have any name: other
/// programs don't always use `*D` (#3299).
pub(super) struct DimBlockPlan {
/// Dimension (model or paper space) → the read block whose name and handles it reuses.
pub(super) reuse: HashMap<Handle, std::sync::Arc<Block>>,
/// Upper-case names of `*D` blocks not written as ordinary blocks.
/// Upper-case names of blocks not written as ordinary blocks: `*D` blocks and the blocks
/// dimensions name, when nothing else uses them.
pub(super) skip: std::collections::HashSet<String>,
}
@@ -16,6 +18,12 @@ fn is_dim_block(name: &str) -> bool {
name.get(..2).is_some_and(|p| p.eq_ignore_ascii_case("*D"))
}
/// The read block, not named `*D`, that a dimension block definition named `name` is written
/// from (#3299): its record and block properties are written as read.
pub(super) fn kept_named_dim_block<'a>(d: &'a Drawing, name: &str) -> Option<&'a Block> {
d.block(name).filter(|_| !is_dim_block(name)).map(|b| b.as_ref())
}
pub(super) fn dim_block_plan(d: &Drawing) -> DimBlockPlan {
let spaces: Vec<&EntityStore> = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).collect();
// Block names other objects use: inserts and multileader contents anywhere, and dimensions
@@ -35,12 +43,19 @@ pub(super) fn dim_block_plan(d: &Drawing) -> DimBlockPlan {
for e in d.blocks.values().flat_map(|b| b.entities.iter()) {
note(e, true, &mut used);
}
let skip = d.blocks.keys().filter(|n| is_dim_block(n)).map(|n| n.to_ascii_uppercase()).filter(|n| !used.contains(n)).collect();
// Blocks the dimensions of model and paper space still name, whatever their names.
let named: std::collections::HashSet<String> = spaces
.iter()
.flat_map(|s| s.iter())
.filter_map(|e| if let EntityKind::Dimension(dm) = &e.kind { dm.block.as_ref().map(|n| n.to_ascii_uppercase()) } else { None })
.collect();
let skip =
d.blocks.keys().map(|n| n.to_ascii_uppercase()).filter(|n| is_dim_block(n) || named.contains(n)).filter(|n| !used.contains(n)).collect();
let mut plan = DimBlockPlan { reuse: HashMap::new(), skip };
let mut claimed = std::collections::HashSet::new();
for e in spaces.iter().flat_map(|s| s.iter()) {
let EntityKind::Dimension(dm) = &e.kind else { continue };
let Some(b) = dm.block.as_deref().filter(|n| is_dim_block(n)).and_then(|n| d.block(n)) else { continue };
let Some(b) = dm.block.as_deref().and_then(|n| d.block(n)) else { continue };
let key = b.name.to_ascii_uppercase();
if plan.skip.contains(&key) && claimed.insert(key) {
plan.reuse.insert(e.handle, b.clone());
+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

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