Compare commits

...
Author SHA1 Message Date
Tanish Manku e2cd875560 Merge #1752: Dynamic blocks: base point and alignment parameters; lookups of angles, flips, XY and positions 2026-11-23 12:50:36 -07:00
Tanish Manku b418e68372 Merge #993: Block reference grips: none on locked or invisible attributes; a moved multiline attribute moves its text 2026-11-23 12:50:24 -07:00
Tanish Manku d1a4809b2b Merge #963: Dynamic blocks: a stretch or move carries a multiline attribute's text along 2026-11-23 12:50:18 -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
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
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
Cody Vogt b92da359bd Merge storytold/cadcraft main into feat/dynblock-params
# Conflicts:
#	crates/engine/src/snap.rs
2026-11-21 11:02:42 -06: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
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
dotCooCoo 4d2381a5ca Merge main into chore/craft-libs-3af2280 2026-11-17 20:17:59 -08: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
Cody VogtandClaude Opus 5.5 95aefd183d Tests: block references built in tests give the clip main added
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:27:37 -06:00
Cody VogtandClaude Opus 5.5 105930e79d Merge storytold/cadcraft main into feat/dynblock-params
prompt.rs: main's takes_block and this branch's angle field both stay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 16:43:46 -06: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
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
Vincent Cloutier c421d2005b PR #2979: refresh shared DXF dependency imports 2026-11-11 21:01:36 -05: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
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 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
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
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
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 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 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
Cody Vogt e789f77ba9 Merge commit 'e28ebc6958feb5990178b0ea9d3b6230e3b4a25d' into HEAD 2026-11-03 22:52:41 -06:00
Cody Vogt e28ebc6958 Merge remote-tracking branch 'origin/feat/dynblock-array' into feat/dynblock-scale 2026-11-03 22:52:07 -06:00
Cody Vogt 72fafd2807 Merge branch 'main' of https://github.com/storytold/cadcraft into feat/dynblock-scale
# Conflicts:
#	crates/engine/src/session/interactive.rs
2026-11-03 22:52:06 -06:00
Cody Vogt 84c3243d23 Merge branch 'main' of https://github.com/storytold/cadcraft into HEAD
# Conflicts:
#	crates/engine/src/session/interactive.rs
2026-11-03 22:39:40 -06: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
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
Cody VogtandClaude Sonnet 5.5 4d872f87d0 Merge #1723's fixes into feat/dynblock-params
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 22:43:19 -06:00
Cody Vogt eb87758abf Merge commit '858e1146e78fbb0ff266777c85091f23eec283c1' into HEAD
# Conflicts:
#	crates/doc/src/dynblock.rs
2026-11-02 22:38:01 -06:00
Cody Vogt 7f3687f506 Merge commit 'bb32810f' into HEAD 2026-11-02 22:31:28 -06:00
Cody Vogt 797b83b413 Merge branch 'main' of https://github.com/storytold/cadcraft into HEAD
# Conflicts:
#	crates/doc/src/dynblock/apply.rs
2026-11-02 22:15:39 -06:00
Cody Vogt 858e1146e7 Merge branch 'main' of https://github.com/storytold/cadcraft into feat/dynblock-scale
# Conflicts:
#	crates/doc/src/dynblock/apply.rs
2026-11-02 22:14:03 -06:00
Cody VogtandClaude Sonnet 5.5 bb32810f3e Merge main into feat/dynblock-scale; the DWG scale action test matches the struct variant
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 22:07:10 -06: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
Cody VogtandClaude Sonnet 5.5 34d889619c Tests: the DWG scale action test matches the Scale struct variant
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 16:18:48 -06:00
Cody Vogt d11c7f36ca Merge branch 'main' of https://github.com/storytold/cadcraft into feat/dynblock-scale 2026-11-02 16:07:05 -06:00
Cody Vogt cec1d2b9da Merge commit 'f4fd603acf4449f8943b5860264421ad85c502c1' into HEAD 2026-11-02 16:03:28 -06:00
Cody Vogt f4fd603acf Merge remote-tracking branch 'origin/feat/dynblock-array' into feat/dynblock-scale
# Conflicts:
#	crates/doc/src/dynblock/apply.rs
2026-11-02 16:03:04 -06:00
Cody Vogt 2d5988c13f Merge branch 'main' of https://github.com/storytold/cadcraft into feat/dynblock-scale
# Conflicts:
#	crates/doc/src/dynblock/apply.rs
2026-11-02 15:51:45 -06:00
Cody Vogt a17af990c8 Merge branch 'main' of https://github.com/storytold/cadcraft into HEAD
# Conflicts:
#	crates/doc/src/dynblock/apply.rs
2026-11-02 15:48:05 -06: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
Cody Vogt 843ee072d8 Merge commit '8aea81d682f248b711acc6ad5ec3d940f840fe25' into HEAD 2026-11-02 05:07:23 -06:00
Cody Vogt 8aea81d682 Merge remote-tracking branch 'origin/feat/dynblock-array' into feat/dynblock-scale
# Conflicts:
#	crates/doc/src/dynblock/apply.rs
2026-11-02 05:07:00 -06:00
Cody Vogt 9df1e11656 Merge branch 'main' of https://github.com/storytold/cadcraft into feat/dynblock-scale
# Conflicts:
#	crates/doc/src/dynblock/apply.rs
2026-11-02 04:54:36 -06:00
Cody Vogt 8428fbb4e7 Merge branch 'main' of https://github.com/storytold/cadcraft into HEAD
# Conflicts:
#	crates/doc/src/dynblock/apply.rs
2026-11-02 04:52:05 -06: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 309c902329 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:19:04 -06:00
Cody VogtandClaude Sonnet 5.5 2513204737 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:43 -06:00
Cody VogtandClaude Sonnet 5.5 41d20af874 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:39 -06: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
Cody Vogt c0005803e8 Merge commit '7050d6dc2d49214162e2d93c2de591db35af3472' into HEAD
# Conflicts:
#	docs/file-format-parity.md
#	docs/gaps.md
2026-10-31 09:01:03 -06:00
Cody Vogt 2c775694d4 Merge branch 'main' of https://github.com/storytold/cadcraft into HEAD
# Conflicts:
#	crates/engine/tests/it/main.rs
2026-10-31 09:00:27 -06:00
Cody Vogt 7050d6dc2d Merge branch 'main' of https://github.com/storytold/cadcraft into feat/dynblock-scale
# Conflicts:
#	crates/engine/tests/it/main.rs
2026-10-31 08:53:46 -06:00
Cody Vogt 9f7440ce94 Merge branch 'main' of https://github.com/storytold/cadcraft into feat/dynblock-scale
# Conflicts:
#	docs/file-format-parity.md
#	docs/gaps.md
2026-10-30 20:36:06 -06: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
Cody VogtandClaude Sonnet 5.5 5e8d4e7f39 Snap: gather_in takes the object to skip, like its siblings' argument lists
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-29 22:29:46 -06:00
Cody VogtandClaude Opus 5.5 db3e14f494 Tests: the base point, alignment and lookup tests join the io test binary
Upstream (#1989) builds each crate's tests as one binary; dynblock_params.rs moves into tests/it, and dynamic_grips.rs's new fixture path is one level deeper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:29:46 -06:00
Cody VogtandClaude Opus 5.5 241cc6a9d4 Docs: the dynamic block data row names the fixed-base rotate and scale limit
A rotate or scale action with a fixed base point still acts about where the
dynamic block has it after a base point parameter has moved the reference;
AutoCAD replays the whole history instead. The PR said so; the row now does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:29:46 -06:00
Cody VogtandClaude Opus 5.5 e265c5cadd Docs: the dynamic block data row lists base point, alignment and lookup changes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:29:46 -06:00
Cody VogtandClaude Opus 5.5 fc82a2f903 Dynamic blocks: base point and alignment parameters; lookups of angles, flips, XY distances and positions
- An action that moves a base point parameter moves the reference's insertion point with it and
  the block's objects and parameters back, as AutoCAD saves it.
- Alignment parameters: type read, a grip at the base point; dragged next to an object the
  reference moves onto it and turns along it, its right side toward the cursor (measured in AutoCAD).
- Lookup columns UpdatedAngle, UpdatedFlip, UpdatedDistanceX/Y, UpdatedX/Y (and polar distance
  and angle) set and read, including the reverse lookup; any changed parameter re-evaluates the
  lookups that read it.
- A distance of 0 is taken, as AutoCAD takes it.
- A first-time flip value is saved with its state after its points and the flip grip's record
  without a point; AutoCAD dropped the reference's dynamic properties otherwise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:29:46 -06:00
Cody VogtandClaude Opus 5.5 dc55e72d49 Tests: scale and polar stretch tests join the io test binary; Scale's doc says diagonal
Upstream gathered each crate's integration tests into one binary (tests/it); the scale and polar
stretch tests move there. The scale action's doc now says an XY parameter scales by its diagonal,
as the code does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:29:06 -06:00
Cody VogtandClaude Opus 5.5 e74cac535b Docs: DWG save of drawings with scale actions needs #1725
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:29:06 -06:00
Cody VogtandClaude Opus 5.5 50060af67d Docs: the dynamic block data row lists scale and polar stretch actions
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:29:06 -06:00
Cody VogtandClaude Opus 5.5 fc8caca7b3 Dynamic blocks: polar stretch actions; scale by an XY parameter's diagonal
A polar stretch action turns its objects about the polar parameter's base by the change of its
angle and moves the vertices in its frame (and the objects it doesn't stretch) with the end, as
AutoCAD does; its rotate-only objects just turn. Parameters in its selection are carried.

A scale action driven by an XY parameter scales uniformly by the parameter's diagonal, as AutoCAD
does (the X-only and Y-only choices live only in DWG data that isn't read).

Stretch and move actions on polar and XY parameters were checked against AutoCAD: they already
match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:29:05 -06:00
Cody VogtandClaude Opus 5.5 b471e5974a Dynamic blocks: scale actions
A scale action scales its objects about its base point by how much the distance it follows grew
(an XY parameter's horizontal and vertical distances each on their own axis), as AutoCAD does,
carrying the parameters in its selection. Factors that would scale to nothing or overflow are
refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:28:14 -06:00
Cody VogtandClaude Opus 5.5 201b5688a4 Tests: the array and rotate/flip tests join the io and engine test binaries
Upstream (#1989) builds each crate's tests as one binary, tests/it/main.rs; these files moved with their fixture paths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:59 -06:00
Cody VogtandClaude Opus 5.5 e6fce40d6e Dynamic blocks: an angle just short of a full turn shows as 0, not 360
Custom angle properties were formatted to AUPREC decimals straight from
the value, so 359.7 degrees with no decimals showed as "360". They are now
rounded first and wrapped back into 0 to 360.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:59 -06:00
Cody VogtandClaude Opus 5.5 5721b77933 Docs: the dynamic block data row lists polar, XY and array changes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:59 -06:00
Cody VogtandClaude Opus 5.5 7cd5ef36dc Dynamic block grips: list XY corner parts as a drag takes them
blocks.reference.grips listed an XY parameter's corner grips as baseXEndY
and baseYEndX (serde's camelCase), but blocks.reference.grip takes
basex-endy and basey-endx, so a caller passing a listed grip back was
refused. The corners are now listed by the names a drag takes, and the
command's params doc names them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:59 -06:00
Cody VogtandClaude Opus 5.5 46acac72eb Dynamic blocks: array actions, polar and XY parameters
A dynamic block reference now repeats its arrayed objects as AutoCAD does:
along a linear or polar parameter one copy per whole column offset in its
distance, across an XY parameter a whole number of columns by rows (just the
object when either is short of one), following the parameter's base point.
Copies after the first carry AutoCAD's AcDbBlockArrayActionTag; without it
AutoCAD can't change the reference again ("Invalid input").

Polar parameters show Distance1 and Angle1, XY parameters X Distance1 and
Y Distance1, in Properties (editable, value sets applied; an XY distance
below its minimum is refused as AutoCAD refuses it), with square grips at
the base and end and an XY parameter's two other corners.

Checked against AutoCAD with a linear, a polar and an XY array block: copy
counts and positions match for each value tried, AutoCAD reads CADCraft's
saved values and geometry, and changes them again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:59 -06:00
Cody VogtandClaude Opus 5.5 4f671b7759 Dynamic blocks: an angle's tick marks are where its grip will be
The rotation grip is drawn where its grip object is, which can be off the
radius' end; its stops are now marked there too (the grip object's angle and
distance from the base added to each value), not at the radius' end.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:27 -06:00
Cody VogtandClaude Opus 5.5 eeb213dccd Dynamic blocks: a grip on a value list or increments marks its stops while dragged
A distance or angle whose values are a list, or go by an increment, stops
only at those values; while its grip is dragged, the preview marks each stop
with a short tick across the grip's travel (a few pixels, whatever the zoom),
as AutoCAD does. `dynblock::grip_stops` gives the stops: along a distance from
the point that stays, or from its midpoint, and round an angle's circle (a
full turn being no turn).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:27 -06:00
Cody VogtandClaude Sonnet 5.5 28d240ca67 Dynamic blocks: the actions' bookkeeping moves into ActionRun
main now denies cognitive_complexity over 30: apply() was at 35 with the
rotate and flip actions. The action loop becomes ActionRun, one method per
kind of action (rotate and flip, stretch and move), and the carrying of a
parameter by a stretch is shifted(). No change in what the actions do.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-29 22:27:14 -06:00
Cody VogtandClaude Opus 5.5 7f6033c0aa Dynamic blocks: a rotate or flip selection that repeats an object turns or mirrors it once
A repeated handle queued the transform twice: a flip mirrored the object back
while its value recorded the flip. Repeats are skipped, as the stretch and
move path does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:14 -06:00
Cody VogtandClaude Opus 5.5 ca56d0097e Prompt: the picker's doc stays on picker, the angle's on angle
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:14 -06:00
Cody VogtandClaude Opus 5.5 b19fa36396 Dynamic blocks: a flip value's state is written after both its points
A new flip value from a one-point record had its state (70) written before
the end point was added, between the two points.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:14 -06:00
Cody VogtandClaude Opus 5.5 cae6f75b4e Docs: the dynamic block data row says what can be changed now
It still said only visibility states and lookups could be changed and
that only stretch and lookup actions were read. Distances and positions
(stretch, move), angles (rotate) and flip states (flip) can be changed,
and their value records are saved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 7f85a5473a Dynamic blocks: a value record takes its shape from its parameter
A flip record was told from another two-point record by a group 70 after
its points. A stray 70 on a linear or rotation record made its value a
flip (and ignored), and a flip record without its state was read as
plain points. The parameter the record is keyed by now decides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 74498ff4b0 Dynamic blocks: the rotation grip's Dynamic Input shows one angle box
At a rotation grip AutoCAD's Dynamic Input asks for the angle alone; CADCraft
showed a distance and an angle from the grip. A prompt can now say it asks for
an angle about its base (`Prompt::angle`), and a command can give the value
the cursor would give (`Interactive::live_value`, under the crash guard;
`Session::live_value`). The rotation grip does both, with the angle as
Properties will show it, and the canvas draws one box: what was typed, else
that live value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 98db1164ff Dynamic blocks: flipped text keeps its mirrored footprint, as AutoCAD draws it
A flip mirrors text and attributes but AutoCAD draws them readable (MIRRTEXT
0): the text keeps the mirrored footprint, so text that ran away from the
symbol still runs away from it on the other side. CADCraft mirrored only the
text's anchor, so flipped text ran back across the block. Text carried by an
action that mirrors now reads in whichever mirrored direction is nearer its
own, and swaps left and right justification when its footprint is reversed
along it (AutoCAD keeps the justification and moves the start back by the
text's width, which draws the same; it re-derives attributes from the block
when it next changes them), top and bottom when reversed across it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 84310182ca Dynamic blocks: the flip grip is a block arrow, as AutoCAD draws it
The flip grip was a narrow triangle; AutoCAD draws a block arrow, a short
shaft and a head about as wide as a square grip. Its shaft and head are filled
apart (the painter fills convex shapes) and outlined as one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 95f7f6687a Dynamic blocks: an angle parameter shows and is typed as the drawing measures angles
AutoCAD shows an angle parameter's value as it shows any angle: from ANGBASE,
clockwise when ANGDIR is 1. In a drawing measured clockwise from north it shows
an Angle1 of 0 as 90, and 0.5 rad as 61.35 (checked in AutoCAD). Properties and
typed values (blocks.reference.set, a value typed at the rotation grip) now
convert the same way; the stored value is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 e0fa2af3b0 Dynamic blocks: the rotation grip is where its grip object is, and a drag turns by the cursor's turn
AutoCAD draws a rotation parameter's grip where the block's grip object is,
which need not be the radius' end (a well-centre symbol has it a quarter turn
round), and turns it with the angle. CADCraft drew it at the radius' end. The
grip is now placed from its grip object, kept along and across the radius as
it turns (as the flip grip already was), and dragging it subtracts the grip's
offset from the radius, so the block turns by the cursor's turn instead of
jumping to the cursor's direction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 6977a58a59 Dynamic blocks: rotation test compares with a plain bound, not an approximate TAU
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 ebeb263874 Dynamic blocks: rotation and flip grips, flip state after the points, tests
A rotation parameter's grip (a circle at the radius' end) turns the angle when
dragged (a typed number sets it, in degrees); a flip grip (an arrow across the
reflection line, placed from its grip object and turning with the line) flips
at a click. A flip value record keeps its state after its points, also in a
record CADCraft writes without a template. A synthetic Symbol fixture covers
reading, turning, flipping, grips and bad values. Also: #967's test
expectation counts positions from 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:13 -06:00
Cody VogtandClaude Opus 5.5 ee0697955c Dynamic block references: rotation and flip parameters and their rotate and flip actions
Angle1 (degrees, as Properties shows them) turns the rotate action's objects
about its base point; Flip state1 mirrors the flip action's objects across
the current reflection line (text stays readable). Parameters in the
selection are carried along, attributes follow, the flip grip's record and
the history are written as AutoCAD writes them. Checked against AutoCAD's own
output for the same changes: value records, history and geometry match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:27:13 -06: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 VogtandClaude Opus 5.5 d35ee3ae71 Block reference grips: none on locked or invisible attributes; a moved multiline attribute moves its text
Every attribute of a block reference had a grip, also those locked in
position and invisible ones, which AutoCAD gives none. Dragging a multiline
attribute's grip moved its position but not its multiline text, so the grip
moved and the text stayed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 09:08:04 -06:00
Cody VogtandClaude Opus 5.5 b6cd6667ca Test: a stretched multiline attribute survives a save
The moved attribute's insertion and its multiline text's are checked
again after saving to DXF (in the drawing's version; R2000 DXF has no
multiline attributes) and reopening.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 09:06:23 -06:00
Cody VogtandClaude Opus 5.5 cc0e3c7add Dynamic blocks: a stretch or move carries a multiline attribute's text along
The reference's attribute moved with its definition, but a multiline
attribute's text (its embedded MTEXT) stayed behind; the grip preview drew it
as one line. Both landed before multiline attributes (#854) and couldn't use
them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 09:06:23 -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
238 changed files with 14447 additions and 1043 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 }}
+3 -1
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 |
|---|---|---|---|---|
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| {
+246 -47
View File
@@ -22,7 +22,7 @@ use crate::{Drawing, Handle, RawTag};
mod apply;
mod grips;
mod reference;
pub use apply::{drag_grip, set_property};
pub use apply::{align_grip, drag_grip, grip_stops, set_property};
pub use grips::{DynGrip, GripPart, GripShape, grips};
pub use reference::{CustomProperty, Reference, Value, custom_properties, reference};
@@ -52,6 +52,13 @@ pub struct DynamicBlock {
/// the grips shown in them by object).
#[serde(skip)]
pub grip_objects: Vec<(i32, Handle)>,
/// Where each grip object is in the dynamic block, by graph id (a flip grip's place along its
/// reflection line).
#[serde(skip)]
pub grip_points: Vec<(i32, Vec3)>,
/// The block's base point (where a base point parameter is in the block).
#[serde(skip)]
pub base: Vec3,
}
/// One parameter: a property a reference to the block can change.
@@ -87,16 +94,41 @@ pub enum ParameterKind {
/// The value changes the end point (`false`) or both points from the midpoint (`true`).
from_midpoint: bool,
},
/// A distance and an angle from a base point.
Polar { base: Vec3, end: Vec3 },
/// Horizontal and vertical distances from a base point.
Xy { base: Vec3, end: Vec3 },
/// An angle about a base point.
Rotation { base: Vec3, end: Vec3 },
/// Aligns the reference with nearby geometry.
Alignment { base: Vec3, end: Vec3 },
/// Mirrors the objects about a reflection line.
Flip { base: Vec3, end: Vec3 },
/// A distance and an angle from a base point (Distance1, Angle1): the end point's distance
/// from the base and its direction (counterclockwise from the X axis of the block).
Polar {
base: Vec3,
end: Vec3,
label: String,
description: String,
angle_label: String,
angle_description: String,
values: ValueSet,
angle_values: ValueSet,
},
/// Horizontal and vertical distances from a base point (X Distance1, Y Distance1): how far
/// the end point is from the base along the block's X and Y axes.
Xy {
base: Vec3,
end: Vec3,
x_label: String,
y_label: String,
x_description: String,
y_description: String,
x_values: ValueSet,
y_values: ValueSet,
},
/// An angle about a base point (Angle1): the end point turns about the base. The angle is
/// measured from the direction the dynamic block has from base to end.
Rotation { base: Vec3, end: Vec3, label: String, description: String, values: ValueSet },
/// Aligns the reference with nearby geometry: dragged next to an object, its base point lands
/// on the object and the direction from base to end runs along it. `perpendicular` is the
/// parameter's type (perpendicular, else tangent); AutoCAD aligned both types the same way in
/// every case measured.
Alignment { base: Vec3, end: Vec3, perpendicular: bool },
/// Mirrors the objects about the reflection line from base to end (Flip state1); the names
/// of its two states, not flipped and flipped.
Flip { base: Vec3, end: Vec3, label: String, description: String, states: [String; 2] },
/// A position (Position1).
Point { at: Vec3, label: String, description: String },
/// Named sets of visible objects.
@@ -110,7 +142,9 @@ pub enum ParameterKind {
},
/// A named value chosen from a lookup table.
Lookup { at: Vec3, label: String, description: String },
/// Moves the block's base point.
/// The block's base point: the reference's insertion point is here, and an action that moves
/// it moves the reference's insertion point. `at` is where the block editor showed it; the
/// block itself has it at its base point (AutoCAD moves the block's objects to put it there).
BasePoint { at: Vec3 },
/// A parameter type not modelled yet.
Other { dxf_type: String },
@@ -122,11 +156,23 @@ impl ParameterKind {
match self {
ParameterKind::Linear { label, .. }
| ParameterKind::Point { label, .. }
| ParameterKind::Rotation { label, .. }
| ParameterKind::Flip { label, .. }
| ParameterKind::Visibility { label, .. }
| ParameterKind::Lookup { label, .. } => Some(label),
_ => None,
}
}
/// Every property name a reference shows for the parameter: a polar parameter's distance
/// and angle, an XY parameter's two distances, else its one label.
pub fn labels(&self) -> Vec<&str> {
match self {
ParameterKind::Polar { label, angle_label, .. } => vec![label, angle_label],
ParameterKind::Xy { x_label, y_label, .. } => vec![x_label, y_label],
other => other.label().into_iter().collect(),
}
}
}
/// One visibility state: its name and the objects shown in it (the parameter's other controlled
@@ -205,24 +251,46 @@ pub enum ActionKind {
angle_offset: f64,
},
/// A table: each row sets the listed parameter values together.
Lookup {
columns: Vec<LookupColumn>,
rows: Vec<Vec<String>>,
},
Lookup { columns: Vec<LookupColumn>, rows: Vec<Vec<String>> },
/// Moves the objects by the change of the parameter values it follows.
Move {
Move { multiplier: f64, angle_offset: f64 },
/// Scales the objects about its base point by how much the distance it follows grew (a linear
/// or polar parameter's distance, an XY parameter's diagonal). Its connections name what each
/// reads ("Scale", "XScale", "YScale").
Scale { base: ActionBase },
/// Turns the objects about its base point by the change of a rotation parameter's angle.
Rotate { base: ActionBase },
/// Mirrors the objects across a flip parameter's reflection line when its state changes.
Flip,
/// Repeats the objects as far as the parameter it follows reaches: along a distance (linear
/// or polar parameter) every `column` units, or in a grid of columns and rows across an XY
/// parameter's distances. The objects follow the parameter's base point.
Array { column: f64, row: f64 },
/// Follows a polar parameter: turns its objects about the parameter's base point by the change
/// of its angle, and moves the vertices inside `frame` of the objects listed (all of an object
/// not listed) along the parameter's new direction by the change of its distance. The
/// `rotate_only` objects (outside the selection) only turn.
PolarStretch {
frame: Vec<Vec2>,
#[serde(serialize_with = "hex_vertices")]
vertices: Vec<(Handle, Vec<i32>)>,
#[serde(serialize_with = "hexes")]
rotate_only: Vec<Handle>,
multiplier: f64,
angle_offset: f64,
},
Scale,
Rotate,
Flip,
Array,
PolarStretch,
/// An action type not modelled yet.
Other {
dxf_type: String,
},
Other { dxf_type: String },
}
/// Where an action that turns or scales its objects has its base point.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionBase {
/// It follows the parameter's base point, at `offset` from it; else it stays at `at`.
pub dependent: bool,
pub offset: Vec3,
pub at: Vec3,
}
/// A lookup table column: the parameter value it reads or sets.
@@ -383,7 +451,7 @@ pub fn is_dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -
/// [`dynamic_block`] with the drawing's [`ObjectIndex`] already built.
pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> Option<DynamicBlock> {
let xdict = block_xdict(d, name)?;
let mut out = DynamicBlock::default();
let mut out = DynamicBlock { base: d.block(name.trim()).map(|b| b.base).unwrap_or_default(), ..Default::default() };
for o in graph_members(&objects.0, xdict)? {
let secs = sections(&o.tags);
let node = Cursor::new(section(&secs, "AcDbEvalExpr")).int(90);
@@ -398,6 +466,7 @@ pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> O
} else {
if kind.ends_with("GRIP") {
out.grip_objects.push((node, o.handle));
out.grip_points.push((node, Cursor::new(section(&secs, "AcDbBlockGrip")).point(1010)));
}
out.other.push(o.kind.clone());
}
@@ -406,15 +475,21 @@ pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> O
}
/// A parameter's grip ids: after a two-point parameter's points, the grip count (170) and the
/// base and end grips (91); after a one-point parameter's point, its grip (93).
/// base and end grips (91), then an XY parameter's corner grips (base X and end Y, base Y and end
/// X); after a one-point parameter's point, its grip (93).
fn grip_ids(secs: &[(&str, &[RawTag])]) -> Vec<i32> {
let two = section(secs, "AcDbBlock2PtParameter");
if !two.is_empty() {
let mut c = Cursor::new(two);
c.point(1010);
c.point(1011);
let n = c.count(170).min(2);
return (0..n).map(|_| c.int(91)).collect();
let n = c.count(170).min(4);
let mut ids: Vec<i32> = (0..n).map(|_| c.int(91)).collect();
// Corner grips only an XY parameter has (the others write 0 for them).
while ids.len() > 2 && ids.last() == Some(&0) {
ids.pop();
}
return ids;
}
let mut c = Cursor::new(section(secs, "AcDbBlock1PtParameter"));
c.point(1010);
@@ -446,15 +521,49 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind {
ParameterKind::Lookup { at: one(), label: c.string(303), description: c.string(304) }
}
"BLOCKBASEPOINTPARAMETER" => ParameterKind::BasePoint { at: one() },
"BLOCKPOLARPARAMETER" | "BLOCKXYPARAMETER" | "BLOCKROTATIONPARAMETER" | "BLOCKALIGNMENTPARAMETER" | "BLOCKFLIPPARAMETER" => {
// Its name and description (305, 306), the base angle point (1011) and angle (140), then
// the value set.
"BLOCKROTATIONPARAMETER" => {
let (base, end) = two();
match kind {
"BLOCKPOLARPARAMETER" => ParameterKind::Polar { base, end },
"BLOCKXYPARAMETER" => ParameterKind::Xy { base, end },
"BLOCKROTATIONPARAMETER" => ParameterKind::Rotation { base, end },
"BLOCKALIGNMENTPARAMETER" => ParameterKind::Alignment { base, end },
_ => ParameterKind::Flip { base, end },
}
let mut c = Cursor::new(section(secs, "AcDbBlockRotationParameter"));
let (label, description) = (c.string(305), c.string(306));
ParameterKind::Rotation { base, end, label, description, values: value_set(&mut c) }
}
// Its name and description (305, 306) and its states' names (307 not flipped, 308 flipped).
"BLOCKFLIPPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockFlipParameter"));
let (label, description) = (c.string(305), c.string(306));
let states = [c.string(307), c.string(308)];
ParameterKind::Flip { base, end, label, description, states }
}
// The distance's name and description (305, 306), the angle's (307, 308), the label
// offset (140), then the distance's value set (309, 96, 141–144, 175) and the angle's
// (410, 97, 145–148, 176).
"BLOCKPOLARPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockPolarParameter"));
let (label, description, angle_label, angle_description) = (c.string(305), c.string(306), c.string(307), c.string(308));
let values = value_set_at(&mut c, [309, 96, 141, 175]);
let angle_values = value_set_at(&mut c, [410, 97, 145, 176]);
ParameterKind::Polar { base, end, label, description, angle_label, angle_description, values, angle_values }
}
// The vertical distance's name (305) before the horizontal's (306), then their
// descriptions (307, 308), label offsets (141, 140), the vertical value set (309, 97,
// 146–149, 176) and the horizontal one (410, 96, 142–145, 175).
"BLOCKXYPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockXYParameter"));
let (y_label, x_label, y_description, x_description) = (c.string(305), c.string(306), c.string(307), c.string(308));
let y_values = value_set_at(&mut c, [309, 97, 146, 176]);
let x_values = value_set_at(&mut c, [410, 96, 142, 175]);
ParameterKind::Xy { base, end, x_label, y_label, x_description, y_description, x_values, y_values }
}
// Its type (280): 1 perpendicular, 0 tangent.
"BLOCKALIGNMENTPARAMETER" => {
let (base, end) = two();
let perpendicular = Cursor::new(section(secs, "AcDbBlockAlignmentParameter")).int(280) != 0;
ParameterKind::Alignment { base, end, perpendicular }
}
other => ParameterKind::Other { dxf_type: other.to_string() },
}
@@ -463,11 +572,17 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind {
/// A value set after a parameter's name and description: description (307), flags (96),
/// minimum, maximum and increment (141–143), then the listed values (175 count, 144 each).
fn value_set(c: &mut Cursor) -> ValueSet {
c.next(307);
let flags = c.int(96);
let (minimum, maximum, increment) = (c.real(141), c.real(142), c.real(143));
let n = c.count(175);
let list = (0..n).filter_map(|_| c.next(144).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())).collect();
value_set_at(c, [307, 96, 141, 175])
}
/// A value set written with codes `[description, flags, minimum, count]`: the maximum and
/// increment follow the minimum's code, each listed value is the code after the increment's.
fn value_set_at(c: &mut Cursor, [description, flags, min, count]: [i32; 4]) -> ValueSet {
c.next(description);
let flags = c.int(flags);
let (minimum, maximum, increment) = (c.real(min), c.real(min + 1), c.real(min + 2));
let n = c.count(count);
let list = (0..n).filter_map(|_| c.next(min + 3).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())).collect();
ValueSet { flags, minimum, maximum, increment, list }
}
@@ -507,16 +622,56 @@ fn action(handle: Handle, node: i32, name: String, kind: &str, secs: &[(&str, &[
let (multiplier, angle_offset) = (c.real(140), c.real(141));
(two_connections(tags), ActionKind::Move { multiplier, angle_offset })
}
"BLOCKSCALEACTION" => (Vec::new(), ActionKind::Scale),
"BLOCKROTATEACTION" => (Vec::new(), ActionKind::Rotate),
"BLOCKFLIPACTION" => (Vec::new(), ActionKind::Flip),
"BLOCKARRAYACTION" => (Vec::new(), ActionKind::Array),
"BLOCKPOLARSTRETCHACTION" => (Vec::new(), ActionKind::PolarStretch),
// The base point's two connections (as a rotate action's), then the scale's three: the
// parameters (94-96) and what each reads (303-305, "Scale", "XScale", "YScale").
"BLOCKSCALEACTION" => {
let with_base = section(secs, "AcDbBlockActionWithBasePt");
let mut connections = two_connections(with_base);
let tags = section(secs, "AcDbBlockScaleAction");
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
connections.extend((0..3).map(|i| (first(94 + i).trim().parse().unwrap_or(0), first(303 + i))));
(connections, ActionKind::Scale { base: action_base(with_base) })
}
"BLOCKROTATEACTION" => {
let mut connections = two_connections(section(secs, "AcDbBlockActionWithBasePt"));
let mut c = Cursor::new(section(secs, "AcDbBlockRotationAction"));
connections.push((c.int(94), c.string(303)));
(connections, ActionKind::Rotate { base: action_base(section(secs, "AcDbBlockActionWithBasePt")) })
}
// Its four connections: the parameter (92-95) and the values it reads (301-304).
"BLOCKFLIPACTION" => {
let tags = section(secs, "AcDbBlockFlipAction");
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
let connections = (0..4).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
(connections, ActionKind::Flip)
}
// Its four connections (92-95 with 301-304, as a flip action's), then the row (140) and
// column (141) offsets.
"BLOCKARRAYACTION" => {
let tags = section(secs, "AcDbBlockArrayAction");
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
let connections = (0..4).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
let mut c = Cursor::new(tags);
let (row, column) = (c.real(140), c.real(141));
(connections, ActionKind::Array { column, row })
}
"BLOCKPOLARSTRETCHACTION" => polar_stretch(section(secs, "AcDbBlockPolarStretchAction")),
other => (Vec::new(), ActionKind::Other { dxf_type: other.to_string() }),
};
Action { node, handle, name, at, selection, connections, kind }
}
/// The base point of an action that has one: after its two connections (92/93, 301/302), the
/// offset from the parameter's base point (1011), whether it follows that point (280), and the
/// point it stays at when it doesn't (1012).
fn action_base(tags: &[RawTag]) -> ActionBase {
let mut c = Cursor::new(tags);
c.next(302);
let offset = c.point(1011);
let dependent = c.int(280) != 0;
ActionBase { dependent, offset, at: c.point(1012) }
}
/// Two connections: parameter ids (92, 93) and the values they read (301, 302). Writers order
/// these groups differently (92 93 301 302, or 92 301 93 302), so each is read on its own.
fn two_connections(tags: &[RawTag]) -> Vec<(i32, String)> {
@@ -551,6 +706,42 @@ fn stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) {
(connections, ActionKind::Stretch { frame, vertices, multiplier, angle_offset })
}
/// A polar stretch action: its six connections (92-97 with 301-306), the frame (73 count,
/// 1011/1021 points), the objects it only turns (72 count, 331 each), the objects whose vertices it
/// moves (74 count; each a 332 handle, a 75 count and 76 vertex indices), more vertex lists (78
/// count; each a 98 code, a 79 count and 76 indices), then the distance multiplier (141) and angle
/// offset (140).
fn polar_stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) {
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
let connections = (0..6).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
let mut c = Cursor::new(tags);
let n = c.count(73);
let frame = (0..n)
.map(|_| {
let x = c.real(1011);
Vec2::new(x, c.real(1021))
})
.collect();
let n = c.count(72);
let rotate_only = c.handles(331, n);
let objects = c.count(74);
let vertices = (0..objects)
.filter_map(|_| {
let h = c.handle(332)?;
let n = c.count(75);
Some((h, (0..n).map(|_| c.int(76)).collect()))
})
.collect();
for _ in 0..c.count(78) {
c.next(98);
for _ in 0..c.count(79) {
c.next(76);
}
}
let (multiplier, angle_offset) = (c.real(141), c.real(140));
(connections, ActionKind::PolarStretch { frame, vertices, rotate_only, multiplier, angle_offset })
}
/// A lookup table: rows (92) and columns (93), the cells row by row (302, after a 301 header),
/// then each column: unmatched name (303 then 305), parameter id (94), lookup flag (282) and the
/// parameter value it stands for (304).
@@ -598,5 +789,13 @@ mod tests {
let (_, ActionKind::Stretch { vertices, .. }) = stretch(&tags) else { panic!("a stretch action") };
let ints: usize = vertices.iter().map(|(_, v)| v.len()).sum();
assert!(ints <= 16 * tags.len() + 1024, "{ints}");
let mut tags = vec![tag(74, &n.to_string())];
tags.extend((0..n).flat_map(|_| [tag(332, "1F"), tag(75, &n.to_string())]));
tags.push(tag(78, &n.to_string()));
tags.extend((0..n).map(|_| tag(79, &n.to_string())));
let (_, ActionKind::PolarStretch { vertices, .. }) = polar_stretch(&tags) else { panic!("a polar stretch action") };
let ints: usize = vertices.iter().map(|(_, v)| v.len()).sum();
assert!(ints <= 16 * tags.len() + 1024, "{ints}");
}
}
File diff suppressed because it is too large Load Diff
+151 -3
View File
@@ -1,7 +1,11 @@
//! The grips of a dynamic block reference, as AutoCAD shows them on a selected reference: an
//! arrow at each end of a distance (linear parameter), a square at a position (point parameter)
//! and a down-pointing triangle for a list (visibility states, lookup values). Dragging an arrow
//! or square is [`super::drag_grip`]; a list grip offers its property's choices.
//! arrow at each end of a distance (linear parameter), a square at a position (point parameter),
//! a circle at the end of an angle (rotation parameter), a flip arrow across a reflection line
//! (flip parameter), a down-pointing triangle for a list (visibility states, lookup values) and a
//! pentagon pointing across the alignment direction at an alignment's base point (alignment
//! parameter; dragged next to an object it aligns the reference with it, [`super::align_grip`]).
//! Dragging an arrow, square or circle is [`super::drag_grip`]; a flip grip flips at a click; a
//! list grip offers its property's choices.
//!
//! With a visibility parameter, a state lists the grips shown in it; the others are hidden.
@@ -26,6 +30,13 @@ pub enum GripPart {
End,
/// A one-point parameter's point (a position, a visibility or lookup grip).
At,
/// An XY parameter's corner at the base's X and the end's Y (listed as `blocks.reference.grip`
/// takes it, as [`GripPart::name`] names it).
#[serde(rename = "basex-endy")]
BaseXEndY,
/// An XY parameter's corner at the end's X and the base's Y.
#[serde(rename = "basey-endx")]
BaseYEndX,
}
impl GripPart {
@@ -34,6 +45,8 @@ impl GripPart {
GripPart::Base => "base",
GripPart::End => "end",
GripPart::At => "at",
GripPart::BaseXEndY => "basex-endy",
GripPart::BaseYEndX => "basey-endx",
}
}
pub fn from_name(s: &str) -> Option<GripPart> {
@@ -41,11 +54,28 @@ impl GripPart {
"base" => Some(GripPart::Base),
"end" => Some(GripPart::End),
"at" => Some(GripPart::At),
"basex-endy" => Some(GripPart::BaseXEndY),
"basey-endx" => Some(GripPart::BaseYEndX),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::GripPart;
/// A grip is listed with the part name `blocks.reference.grip` takes back.
#[test]
fn listed_part_names_are_the_names_a_drag_takes() {
for p in [GripPart::Base, GripPart::End, GripPart::At, GripPart::BaseXEndY, GripPart::BaseYEndX] {
let listed = serde_json::to_value(p).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
assert_eq!(listed, p.name());
assert_eq!(GripPart::from_name(&listed), Some(p));
}
}
}
/// How a grip looks and what it does.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -56,6 +86,13 @@ pub enum GripShape {
Point,
/// A down-pointing triangle: click it for the property's choices.
List,
/// A circle at the end of an angle: drag it to turn the angle.
Rotation,
/// An arrow across a reflection line: click it to flip (its choices are the two states).
Flip,
/// A pentagon pointing to the left of an alignment's direction: drag it next to an object to
/// align the reference with it.
Alignment,
}
/// One grip of a dynamic block reference.
@@ -102,6 +139,15 @@ fn ends_used(m: &DynamicBlock, node: i32) -> Option<(bool, bool)> {
used
}
/// Where a grip object at `g` (from its parameter's base, in the dynamic block) is when the
/// parameter's line `home` (base to end, in the block) is now `now` from `base`: kept along and
/// across the line as it turns, moves or stretches. `home` and `now` aren't zero.
fn carried(g: Vec2, home: Vec2, base: Vec2, now: Vec2) -> Vec2 {
let (u0, u) = (home * (1.0 / home.len()), now * (1.0 / now.len()));
let (along, across) = (g.dot(u0) / home.len(), u0.x * g.y - u0.y * g.x);
base + now * along + u.perp() * across
}
fn point<S: serde::Serializer>(p: &Vec2, s: S) -> Result<S::Ok, S::Error> {
[p.x, p.y].serialize(s)
}
@@ -120,6 +166,7 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
};
// The grips the current visibility state shows (all of them without visibility states).
let objects: HashMap<i32, Handle> = m.grip_objects.iter().copied().collect();
let points: HashMap<i32, Vec3> = m.grip_points.iter().copied().collect();
let mut shown_in_state: Option<HashSet<Handle>> = None;
let mut visibility_node = None;
for p in &m.parameters {
@@ -171,6 +218,87 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
}
}
}
ParameterKind::Rotation { base: hb, end: he, label, .. } => {
let (b, e) = match r.values.get(&p.node) {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*hb, *he),
};
let id = grip(1);
let (home, now) = ((*he - *hb).xy(), (e - b).xy());
if shown(p.node, id) && home.len() > 1e-12 && now.len() > 1e-12 {
// The grip object's place (AutoCAD draws the circle there, not at the radius'
// end), turned and moved with the radius.
let at = carried(points.get(&id).copied().unwrap_or(*he).xy() - hb.xy(), home, b.xy(), now);
let at = Vec3::new(at.x, at.y, b.z);
let u = at - b;
let u = if u.len() > 1e-12 { u * (1.0 / u.len()) } else { Vec3::new(1.0, 0.0, 0.0) };
let (at, dir) = (world(at), toward(at, u));
out.push(DynGrip {
node: p.node,
part: GripPart::End,
shape: GripShape::Rotation,
at,
dir,
property: label.clone(),
choices: Vec::new(),
});
}
}
ParameterKind::Flip { base: hb, end: he, label, states, .. } => {
let (b, e, flipped) = match r.values.get(&p.node) {
Some(Value::Flip { base, end, flipped }) => (*base, *end, *flipped),
_ => (*hb, *he, false),
};
let id = grip(0);
let (home, now) = ((*he - *hb).xy(), (e - b).xy());
if shown(p.node, id) && home.len() > 1e-12 && now.len() > 1e-12 {
// The grip object's place, kept along and across the reflection line as the
// line turns or moves with other actions.
let g = points.get(&id).copied().unwrap_or(*hb).xy() - hb.xy();
let at = carried(g, home, b.xy(), now);
let u = now * (1.0 / now.len());
let across_dir = if flipped { -u.perp() } else { u.perp() };
let (at3, dir) = (Vec3::new(at.x, at.y, b.z), toward(Vec3::new(at.x, at.y, b.z), across_dir.to3(0.0)));
out.push(DynGrip {
node: p.node,
part: GripPart::Base,
shape: GripShape::Flip,
at: world(at3),
dir,
property: label.clone(),
choices: states.to_vec(),
});
}
}
// Squares at the base and the end (a polar parameter), and at the two other corners of
// the rectangle they span (an XY parameter), for the grips the parameter has; an end
// no action follows has none.
ParameterKind::Polar { base, end, label, .. } | ParameterKind::Xy { base, end, x_label: label, .. } => {
let (b, e) = match r.values.get(&p.node) {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*base, *end),
};
let used = ends_used(&m, p.node).map_or([true, true], |(base, end)| [base, end]);
let mut corners = vec![(0, GripPart::Base, b, used[0]), (1, GripPart::End, e, used[1])];
if matches!(p.kind, ParameterKind::Xy { .. }) {
let both = used[0] && used[1];
corners.push((2, GripPart::BaseXEndY, Vec3::new(b.x, e.y, b.z), both));
corners.push((3, GripPart::BaseYEndX, Vec3::new(e.x, b.y, b.z), both));
}
for (i, part, at, used) in corners {
if used && shown(p.node, grip(i)) {
out.push(DynGrip {
node: p.node,
part,
shape: GripShape::Point,
at: world(at),
dir: Vec2::ZERO,
property: label.clone(),
choices: Vec::new(),
});
}
}
}
ParameterKind::Point { at, label, .. } => {
let at = match r.values.get(&p.node) {
Some(Value::Point { at }) => *at,
@@ -189,6 +317,26 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
});
}
}
// At the base point, pointing to the left of the direction (as AutoCAD draws it).
ParameterKind::Alignment { base, end, .. } => {
let (b, e) = match r.values.get(&p.node) {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*base, *end),
};
let u = (e - b).xy();
if shown(p.node, grip(0)) && u.len() > 1e-12 {
let (at, dir) = (world(b), toward(b, u.perp().to3(0.0)));
out.push(DynGrip {
node: p.node,
part: GripPart::Base,
shape: GripShape::Alignment,
at,
dir,
property: String::new(),
choices: Vec::new(),
});
}
}
ParameterKind::Visibility { at, label, .. } | ParameterKind::Lookup { at, label, .. } => {
let Some(list) = choices.get(&label.to_ascii_uppercase()).filter(|c| !c.is_empty()) else { continue };
if shown(p.node, grip(0)) {
+106 -29
View File
@@ -29,6 +29,8 @@ pub enum Value {
Point { at: Vec3 },
/// A two-point parameter's points.
Points { base: Vec3, end: Vec3 },
/// A flip parameter's reflection line and whether it is flipped.
Flip { base: Vec3, end: Vec3, flipped: bool },
}
/// A dynamic block reference.
@@ -51,8 +53,8 @@ pub struct CustomProperty {
/// The values it may be set to, when it is a choice (visibility states, lookup values, a
/// distance's list).
pub choices: Vec<String>,
/// CADCraft can change it ([`super::set_property`]): a visibility state, a distance, a
/// position, or a lookup whose tables set only those.
/// CADCraft can change it ([`super::set_property`]): a visibility state, a distance, an angle,
/// a position, a flip state, or a lookup whose tables set only those.
pub editable: bool,
}
@@ -91,7 +93,9 @@ fn entries(objects: &HashMap<Handle, &ForeignObject>, dict: Handle) -> Vec<(Stri
out
}
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30).
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30); a flip
/// parameter's also has its state, a group 70 after its points (the header's `70 25`, `70 104`
/// come before them).
fn value(o: &ForeignObject) -> Option<Value> {
if let Some(t) = o.tags.iter().find(|t| t.code == 1) {
return Some(Value::Text { value: t.value.clone() });
@@ -100,7 +104,10 @@ fn value(o: &ForeignObject) -> Option<Value> {
o.tags.iter().filter(|t| t.code == code).nth(i).and_then(|t| t.value.trim().parse::<f64>().ok()).filter(|v| v.is_finite())
};
let point = |i: usize| Some(Vec3::new(num(10, i)?, num(20, i)?, num(30, i).unwrap_or(0.0)));
let first_point = o.tags.iter().position(|t| t.code == 10).unwrap_or(o.tags.len());
let state = o.tags.get(first_point..).unwrap_or_default().iter().rev().find(|t| t.code == 70).map(|t| t.value.trim() == "1");
match (point(0), point(1)) {
(Some(base), Some(end)) if state.is_some() => Some(Value::Flip { base, end, flipped: state == Some(true) }),
(Some(base), Some(end)) => Some(Value::Points { base, end }),
(Some(at), None) => Some(Value::Point { at }),
_ => None,
@@ -122,17 +129,52 @@ pub fn reference(d: &Drawing, insert: Handle) -> Option<Reference> {
let target = data.tags.iter().find(|t| t.code == 340).and_then(|t| Handle::parse_hex(&t.value))?;
let (kind, name) = d.foreign.targets.get(&target)?;
let definition = d.block(name).filter(|_| kind == "BLOCK_RECORD")?.name.clone();
dynamic_block(d, &definition)?;
let m = dynamic_block(d, &definition)?;
let mut values = BTreeMap::new();
let cache = entry(&objects, rep, "AppDataCache").and_then(|c| entry(&objects, c, "ACAD_ENHANCEDBLOCKDATA"));
for (key, h) in cache.map(|c| entries(&objects, c)).unwrap_or_default().into_iter().take(MAX_VALUES) {
if let (Ok(node), Some(v)) = (key.trim().parse::<i32>(), objects.get(&h).and_then(|o| value(o))) {
// The record's groups alone can't tell a flip from another two-point parameter (a stray
// 70, or a flip without its state): the parameter it belongs to decides.
let flip = m.parameters.iter().any(|p| p.node == node && matches!(p.kind, ParameterKind::Flip { .. }));
let v = match (flip, v) {
(false, Value::Flip { base, end, .. }) => Value::Points { base, end },
(true, Value::Points { base, end }) => Value::Flip { base, end, flipped: false },
(_, v) => v,
};
values.insert(node, v);
}
}
Some(Reference { definition, values })
}
/// An angle (radians) as Properties shows it: degrees with AUPREC decimals.
/// An angle parameter's value `a` (radians, counterclockwise) as the drawing shows angles: from
/// ANGBASE, clockwise when ANGDIR is 1 (AutoCAD shows a 0 angle as 90 in a drawing measured
/// clockwise from north, and 0.5 rad as 61.35).
pub(super) fn angle_shown(d: &Drawing, a: f64) -> f64 {
let base = d.header.f64("ANGBASE", 0.0);
let shown = if d.header.i64("ANGDIR", 0) == 1 { base - a } else { a - base };
shown.rem_euclid(std::f64::consts::TAU)
}
/// The value of an angle parameter shown (or typed) as `v` (radians): the inverse of
/// [`angle_shown`].
pub(super) fn angle_from_shown(d: &Drawing, v: f64) -> f64 {
let base = d.header.f64("ANGBASE", 0.0);
let a = if d.header.i64("ANGDIR", 0) == 1 { base - v } else { v + base };
a.rem_euclid(std::f64::consts::TAU)
}
fn angle_text(d: &Drawing, a: f64) -> String {
let prec = usize::try_from(d.header.i64("AUPREC", 0).clamp(0, 8)).unwrap_or(0);
// Rounded to the shown decimals first: an angle just short of a full turn shows as 0, not 360.
let step = 10f64.powi(i32::try_from(prec).unwrap_or(0));
let shown = (angle_shown(d, a).to_degrees() * step).round() / step;
let shown = if shown >= 360.0 { shown - 360.0 } else { shown };
format!("{:.prec$}", shown + 0.0)
}
/// A number as the drawing shows lengths (LUPREC decimals).
fn number(d: &Drawing, v: f64) -> String {
let prec = usize::try_from(d.header.i64("LUPREC", 4).clamp(0, 8)).unwrap_or(4);
@@ -156,26 +198,7 @@ struct Current<'a> {
impl Current<'_> {
/// Parameter `node`'s value of property `property`, as table cells write it.
fn property(&self, node: i32, property: &str) -> Option<String> {
let p = self.m.parameters.iter().find(|p| p.node == node)?;
let v = self.values.get(&node);
match (&p.kind, property.to_ascii_lowercase().as_str()) {
(ParameterKind::Visibility { states, .. }, "visibilitystate") => match v {
Some(Value::Text { value }) => Some(value.clone()),
_ => states.first().map(|s| s.name.clone()),
},
(ParameterKind::Linear { base, end, .. }, "updateddistance" | "distance") => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*base, *end),
};
Some(format!("{}", (e - b).len()))
}
(ParameterKind::Lookup { .. }, "lookupstring") => match v {
Some(Value::Text { value }) => Some(value.clone()),
_ => None,
},
_ => None,
}
super::apply::property_text(self.m, self.values, node, property)
}
/// Lookup parameter `node`'s value: the value every lookup table that sets it gives for the
@@ -239,6 +262,27 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
let choices = if values.is_list() { values.list.iter().map(|x| number(d, x * sx)).collect() } else { Vec::new() };
out.push(CustomProperty { name: label.clone(), value: number(d, (e - b).len() * sx), choices, editable: true });
}
// The distance from the base to the end, and the end's direction (AutoCAD measures it
// from the block's X axis, not from where the dynamic block has it).
ParameterKind::Polar { base: b, end: e, label, angle_label, values, .. } => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*b, *e),
};
let choices = if values.is_list() { values.list.iter().map(|x| number(d, x * sx)).collect() } else { Vec::new() };
out.push(CustomProperty { name: label.clone(), value: number(d, (e - b).len() * sx), choices, editable: true });
let a = (e - b).xy().angle().rem_euclid(std::f64::consts::TAU);
out.push(CustomProperty { name: angle_label.clone(), value: angle_text(d, a), choices: Vec::new(), editable: true });
}
// How far the end is from the base along X and along Y.
ParameterKind::Xy { base: b, end: e, x_label, y_label, .. } => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*b, *e),
};
out.push(CustomProperty { name: x_label.clone(), value: number(d, (e.x - b.x) * sx), choices: Vec::new(), editable: true });
out.push(CustomProperty { name: y_label.clone(), value: number(d, (e.y - b.y) * sy), choices: Vec::new(), editable: true });
}
ParameterKind::Point { at, label, .. } => {
let at = match v {
Some(Value::Point { at }) => *at,
@@ -247,6 +291,21 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
out.push(CustomProperty { name: format!("{label} X"), value: number(d, (at.x - base.x) * sx), choices: Vec::new(), editable: true });
out.push(CustomProperty { name: format!("{label} Y"), value: number(d, (at.y - base.y) * sy), choices: Vec::new(), editable: true });
}
ParameterKind::Rotation { base: hb, end: he, label, .. } => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*hb, *he),
};
let now = (e - b).xy();
let zero = (*he - *hb).xy();
let a = (now.y.atan2(now.x) - zero.y.atan2(zero.x)).rem_euclid(std::f64::consts::TAU);
out.push(CustomProperty { name: label.clone(), value: angle_text(d, a), choices: Vec::new(), editable: true });
}
ParameterKind::Flip { label, states, .. } => {
let flipped = matches!(v, Some(Value::Flip { flipped: true, .. }));
let value = states[usize::from(flipped)].clone();
out.push(CustomProperty { name: label.clone(), value, choices: states.to_vec(), editable: true });
}
ParameterKind::Visibility { label, states, .. } => {
let value = cur.property(p.node, "VisibilityState").unwrap_or_default();
out.push(CustomProperty { name: label.clone(), value, choices: states.iter().map(|s| s.name.clone()).collect(), editable: true });
@@ -263,7 +322,8 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
}
/// Whether every lookup table that sets lookup parameter `node` sets only what
/// [`super::set_property`] can apply with it: visibility states and distances.
/// [`super::set_property`] can apply with it: visibility states, distances, angles, positions and
/// flip states.
fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool {
let mut any = false;
for a in &m.actions {
@@ -272,12 +332,29 @@ fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool {
continue;
}
any = true;
if !columns
.iter()
.all(|c| matches!(c.property.to_ascii_lowercase().as_str(), "lookupstring" | "visibilitystate" | "updateddistance" | "distance"))
{
let settable = |c: &super::LookupColumn| {
m.parameters.iter().find(|p| p.node == c.node).is_some_and(|p| super::apply::column(&p.kind, &c.property).is_some())
};
if !columns.iter().all(settable) {
return false;
}
}
any
}
#[cfg(test)]
mod tests {
use super::angle_text;
use crate::Drawing;
#[test]
fn an_angle_just_short_of_a_full_turn_shows_as_zero() {
let mut d = Drawing::new_imperial();
d.header.set_i64("AUPREC", 0);
assert_eq!(angle_text(&d, 359.7f64.to_radians()), "0");
assert_eq!(angle_text(&d, 359.4f64.to_radians()), "359");
d.header.set_i64("AUPREC", 2);
assert_eq!(angle_text(&d, 359.996f64.to_radians()), "0.00");
assert_eq!(angle_text(&d, 90f64.to_radians()), "90.00");
}
}
+1 -1
View File
@@ -617,7 +617,7 @@ impl EntityKind {
EntityKind::Text(t) => vec![t.justify_point()],
EntityKind::MText(t) => vec![t.insert.xy()],
EntityKind::AttDef(a) => vec![a.text.justify_point()],
EntityKind::Insert(i) => std::iter::once(i.insert.xy()).chain(i.attribs.iter().map(|a| a.text.justify_point())).collect(),
EntityKind::Insert(i) => std::iter::once(i.insert.xy()).chain(i.grip_attribs().map(|(_, a)| a.text.justify_point())).collect(),
EntityKind::Dimension(d) => vec![d.p13.xy(), d.p14.xy(), d.defpt.xy(), d.text_mid.xy()],
EntityKind::MLine(m) => m.points(),
EntityKind::Leader(l) => l.vertices.iter().map(|v| v.xy()).collect(),
+6
View File
@@ -191,6 +191,12 @@ fn one_u() -> u32 {
}
impl Insert {
/// The attributes that have a grip of their own (grips 1, 2… after the insertion point), with
/// their index in `attribs`: those shown and not locked in position, as AutoCAD offers them.
pub fn grip_attribs(&self) -> impl Iterator<Item = (usize, &Attrib)> {
self.attribs.iter().enumerate().filter(|(_, a)| !a.invisible && !a.modes.lock_position)
}
/// Block-to-world transform (2D part).
pub fn transform(&self, base: Vec2) -> Mat3 {
Mat3::translate(self.insert.xy())
+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")]
+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]
+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.
+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,
}
}
}
+3 -3
View File
@@ -70,14 +70,14 @@ pub fn specs() -> Vec<CommandSpec> {
.enabled(has_doc)
.noundo(),
CommandSpec::new("blocks.reference.set", "Set Dynamic Property", run_reference_set)
.params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance or \"Position1 X\"), value (lengths in drawing units)} → {properties}")
.params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance, \"Position1 X\", an angle or a flip state), value (lengths in drawing units, angles in degrees; a flip state by name or 0/1)} → {properties}")
.enabled(has_doc),
CommandSpec::new("blocks.reference.grips", "Dynamic Block Grips", dyngrip::run_grips)
.params("{handle} → [{node, part: base|end|at, shape: linear|point|list, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)")
.params("{handle} → [{node, part: base|end|at|basex-endy|basey-endx, shape: linear|point|list|rotation|flip, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)")
.enabled(has_doc)
.noundo(),
CommandSpec::new("blocks.reference.grip", "Drag Dynamic Grip", dyngrip::run_grip)
.params("{handle, node (the parameter's graph id), part: base|end|at, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it")
.params("{handle, node (the parameter's graph id), part: base|end|at|basex-endy|basey-endx, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it, a rotation's circle turns its angle, a polar or XY parameter's squares move its base, end or corners")
.enabled(has_doc),
CommandSpec::new("purge", "Purge", purge::run)
.alias(&["pu", "-purge"])
+72 -22
View File
@@ -1,7 +1,7 @@
//! Grips of dynamic block references: `blocks.reference.grips` lists them, `blocks.reference.grip`
//! drags one (one undo step), and [`Session::start_dyn_grip`] starts the drag the UI's click on a
//! grip begins, with the reference re-evaluated under the cursor as its preview. Typing a number
//! at a distance's grip sets the distance.
//! at a distance's grip sets the distance, at a rotation grip the angle (degrees).
use cadcraft_doc::color::Color;
use cadcraft_doc::dynblock::{self, GripPart, GripShape};
@@ -30,7 +30,8 @@ pub(super) fn run_grip(s: &mut Session, p: &Value) -> Result<Value> {
.and_then(Value::as_i64)
.and_then(|n| i32::try_from(n).ok())
.ok_or_else(|| bad(cmd, "`node` (a parameter's graph id) is required"))?;
let part = str_param(p, "part").and_then(GripPart::from_name).ok_or_else(|| bad(cmd, "`part` must be base, end or at"))?;
let part =
str_param(p, "part").and_then(GripPart::from_name).ok_or_else(|| bad(cmd, "`part` must be base, end, at, basex-endy or basey-endx"))?;
let to = point_param(p, "to").ok_or_else(|| bad(cmd, "`to` [x, y] is required"))?;
drag(s, h, node, part, to).map_err(|e| bad(cmd, e))?;
let properties = dynblock::custom_properties(s.doc()?, h).map(|(_, p)| p).unwrap_or_default();
@@ -46,11 +47,25 @@ fn drag(s: &mut Session, h: Handle, node: i32, part: GripPart, to: Vec2) -> std:
return Err("the reference is on a locked layer".into());
}
let mut d = s.doc().map_err(|e| e.to_string())?.clone();
dynblock::drag_grip(&mut d, h, node, part, to)?;
drag_in(s, &mut d, h, node, part, to)?;
*s.doc_mut().map_err(|e| e.to_string())? = d;
Ok(())
}
/// Drag grip (`node`, `part`) of reference `h` to `to` in drawing `d`; an alignment grip aligns
/// the reference with the object at the cursor (within the aperture), as AutoCAD does.
fn drag_in(s: &Session, d: &mut Drawing, h: Handle, node: i32, part: GripPart, to: Vec2) -> std::result::Result<(), String> {
let alignment = dynblock::reference(d, h)
.and_then(|r| dynblock::dynamic_block(d, &r.definition))
.is_some_and(|m| m.parameters.iter().any(|p| p.node == node && matches!(p.kind, dynblock::ParameterKind::Alignment { .. })));
if !alignment {
return dynblock::drag_grip(d, h, node, part, to);
}
let aperture = s.pixel_size() * s.settings.aperture.max(1.0);
let near = crate::snap::nearest_with_direction(d, &s.space(), to, aperture, h);
dynblock::align_grip(d, h, node, to, near)
}
/// The properties an object of a block draws with in reference `r`: on layer 0 it is on the
/// reference's layer, and its ByBlock colour, linetype, lineweight and transparency are the
/// reference's (as the renderer draws a block's contents).
@@ -102,7 +117,11 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
_ => None,
});
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
Entity { handle: Handle(0), common, kind: EntityKind::Text(a.text.clone()) }
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
None => EntityKind::Text(a.text.clone()),
};
Entity { handle: Handle(0), common, kind }
}));
out
}
@@ -114,11 +133,16 @@ struct DynGripEdit {
part: GripPart,
/// Where the grip is (the rubber band's start).
from: Vec2,
/// The property it changes, and whether it is a distance (a typed number sets it).
/// The property it changes, and the grip's shape (a typed number sets a distance or angle).
property: String,
distance: bool,
shape: GripShape,
/// Where the grip can stop (a value list or increments): tick marks across its travel.
stops: Vec<(Vec2, Vec2)>,
}
/// Half a tick mark's length, in pixels.
const TICK_PX: f64 = 6.0;
impl Interactive for DynGripEdit {
fn name(&self) -> &'static str {
"GRIP"
@@ -129,19 +153,22 @@ impl Interactive for DynGripEdit {
}
fn prompt(&self, _s: &Session) -> Prompt {
let (msg, accept) = if self.distance {
("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER)
} else {
("** STRETCH ** Specify stretch point", Accept::POINT)
let (msg, accept) = match self.shape {
GripShape::Linear => ("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER),
GripShape::Rotation => ("** ROTATE ** Specify rotation point or angle", Accept::POINT_OR_NUMBER),
GripShape::Alignment => ("Specify point location", Accept::POINT),
_ => ("** STRETCH ** Specify stretch point", Accept::POINT),
};
Prompt::new(msg, accept).kw(&["eXit"]).base(self.from)
let p = Prompt::new(msg, accept).kw(&["eXit"]).base(self.from);
// A rotation grip asks for an angle: Dynamic Input shows one angle box.
if self.shape == GripShape::Rotation { p.angle() } else { p }
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let to = match i {
Input::Point(p) => p,
Input::Deferred(d) => d.at,
Input::Text(t) if self.distance => {
Input::Text(t) if matches!(self.shape, GripShape::Linear | GripShape::Rotation) => {
let mut d = s.doc()?.clone();
dynblock::set_property(&mut d, self.handle, &self.property, t.trim()).map_err(EngineError::Other)?;
*s.doc_mut()? = d;
@@ -155,9 +182,30 @@ impl Interactive for DynGripEdit {
Ok(Step::Done)
}
/// The rubber band from the grip.
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
vec![crate::cmd::helpers::line(self.from, c)]
/// The rubber band from the grip, and ticks at the stops of a value list or increments.
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
let half = TICK_PX * s.pixel_size();
let mut out: Vec<EntityKind> = self
.stops
.iter()
.map(|(at, way)| {
let n = way.perp() * half;
crate::cmd::helpers::line(*at - n, *at + n)
})
.collect();
out.push(crate::cmd::helpers::line(self.from, c));
out
}
/// A rotation grip's angle at the cursor, as Properties will show it.
fn live_value(&self, s: &Session, c: Vec2) -> Option<String> {
if self.shape != GripShape::Rotation {
return None;
}
let mut d = s.doc().ok()?.clone();
dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c).ok()?;
let (_, props) = dynblock::custom_properties(&d, self.handle)?;
props.into_iter().find(|p| p.name.eq_ignore_ascii_case(&self.property)).map(|p| format!("{}°", p.value))
}
/// The reference re-evaluated at the cursor, drawn as it will look (its own colours, so
@@ -165,7 +213,7 @@ impl Interactive for DynGripEdit {
fn preview_objects(&self, s: &Session, c: Vec2) -> Vec<Entity> {
let Ok(d) = s.doc() else { return Vec::new() };
let mut d = d.clone();
match dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c) {
match drag_in(s, &mut d, self.handle, self.node, self.part, c) {
Ok(()) => drawn(&d, self.handle),
Err(_) => Vec::new(),
}
@@ -174,8 +222,8 @@ impl Interactive for DynGripEdit {
impl Session {
/// Start dragging grip `part` of parameter `node` of dynamic block reference `handle` (the
/// UI's click on a dynamic grip). A list grip (visibility, lookup) has no drag: the UI offers
/// its choices and sets them with `blocks.reference.set`.
/// UI's click on a dynamic grip). A list grip (visibility, lookup) or a flip grip has no
/// drag: the UI offers the choices, or flips, with `blocks.reference.set`.
pub fn start_dyn_grip(&mut self, handle: Handle, node: i32, part: GripPart) -> Result<()> {
if self.running.is_some() {
self.cancel();
@@ -184,17 +232,19 @@ impl Session {
.into_iter()
.find(|g| g.node == node && g.part == part)
.ok_or_else(|| EngineError::Other("no such grip".into()))?;
if g.shape == GripShape::List {
return Err(EngineError::Other("a list grip is chosen from, not dragged".into()));
if matches!(g.shape, GripShape::List | GripShape::Flip) {
return Err(EngineError::Other("a list or flip grip is clicked, not dragged".into()));
}
let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, distance: g.shape == GripShape::Linear };
let label = if g.shape == GripShape::Rotation { "** ROTATE **" } else { "** STRETCH **" };
let stops = dynblock::grip_stops(self.doc()?, handle, node, part);
let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, shape: g.shape, stops };
let machine = crate::guard::Guarded::wrap(Box::new(edit));
let st = self.state()?;
let (before, selection_before) = (st.doc.clone(), st.selection.clone());
self.running = Some(Running { id: "grip".into(), machine, before, selection_before });
self.pending_window = None;
self.point_mods.clear();
self.echo("** STRETCH **");
self.echo(label);
Ok(())
}
}
+19 -16
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};
@@ -44,13 +44,13 @@ 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(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 +61,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 +76,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 +109,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 +338,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 +349,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)> {
+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),
+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,6 +235,7 @@ pub const NO_FILES: &[&str] = &[
"boundary",
"region",
"hatchedit",
"hatchgenerateboundary",
"hatchpick",
"overkill",
"block",
+4 -1
View File
@@ -170,13 +170,16 @@ pub fn stretch_grip(kind: &EntityKind, index: usize, to: Vec2) -> Option<EntityK
if index == 0 {
return Some(translated(kind, delta));
}
let a = i.attribs.get_mut(index - 1)?;
let k = i.grip_attribs().nth(index - 1).map(|(k, _)| k)?;
let a = i.attribs.get_mut(k)?;
let ip = a.text.insert.xy() + delta;
set_xy(&mut a.text.insert, ip);
if let Some(al) = &mut a.text.align_pt {
let q = al.xy() + delta;
set_xy(al, q);
}
// A multiline attribute is drawn from its multiline text: it moves too.
a.transform_multiline(&Mat3::translate(delta));
}
EntityKind::Dimension(d) => {
match index {
+18
View File
@@ -92,6 +92,15 @@ impl Interactive for Guarded {
Vec::new()
})
}
fn live_value(&self, s: &Session, cursor: Vec2) -> Option<String> {
if self.broken.get().is_some() {
return None;
}
catch_unwind(AssertUnwindSafe(|| self.inner.live_value(s, cursor))).unwrap_or_else(|_| {
self.broken.set(Some("panic in preview"));
None
})
}
fn drag(&self, s: &Session, cursor: Vec2) -> Option<crate::prompt::Drag> {
if self.broken.get().is_some() {
return None;
@@ -110,6 +119,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;
+1 -1
View File
@@ -54,7 +54,7 @@ pub use cadcraft_geom as geom;
pub use cadcraft_render as render;
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;
+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.
+48 -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
@@ -103,6 +103,10 @@ pub struct Prompt {
/// the routine writes, so it cannot be read for the word "Select" (#1598).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub picks_one: bool,
/// The value asked for is an angle about the base (a rotation grip): Dynamic Input shows one
/// angle box, with the command's live value ([`Interactive::live_value`]).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub angle: bool,
/// The prompt takes a block's name as well as its keywords: a Greek word that is an existing
/// block's name is that block, not a keyword read from its Latin keys.
#[serde(skip_serializing_if = "std::ops::Not::not")]
@@ -154,6 +158,11 @@ impl Prompt {
self.grip = Some(g);
self
}
/// An angle about the base is asked for (the `angle` field).
pub fn angle(mut self) -> Self {
self.angle = true;
self
}
/// The visual chooser the UI can show (the `picker` field).
pub fn picker(mut self, p: Picker) -> Self {
self.picker = Some(p);
@@ -326,6 +335,11 @@ pub trait Interactive: Send {
fn preview_objects(&self, _s: &Session, _cursor: Vec2) -> Vec<cadcraft_doc::Entity> {
Vec::new()
}
/// The value the cursor would give, as the prompt asks for it (an angle as the drawing
/// shows angles): what Dynamic Input shows in its box before anything is typed.
fn live_value(&self, _s: &Session, _cursor: Vec2) -> Option<String> {
None
}
/// The preview as existing objects under one transform, when it is that (MOVE, COPY,
/// ROTATE, SCALE). The UI then draws them from geometry uploaded once instead of rebuilding
/// the transformed copies every frame; `None` falls back to [`Interactive::preview`].
@@ -338,6 +352,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 +375,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,
+2 -1
View File
@@ -722,7 +722,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 +788,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 != ' ');
+11
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);
@@ -603,6 +608,12 @@ impl Session {
out
}
/// The value the cursor would give at the active command's prompt (see
/// [`Interactive::live_value`]).
pub fn live_value(&self, cursor: Vec2) -> Option<String> {
self.running.as_ref()?.machine.live_value(self, cursor)
}
/// What the drawing area shows in place of the drawing while a command runs (DVIEW's preview
/// set, see [`Interactive::display_only`]), also while a transparent command interrupts it.
/// `None`: the drawing.
+189 -63
View File
@@ -7,7 +7,7 @@ mod viewport;
pub use viewport::ViewportPoint;
use cadcraft_doc::{Drawing, EntityKind, Insert, MAX_BLOCK_DEPTH, Prim, Space};
use cadcraft_doc::{Drawing, EntityKind, Handle, Insert, MAX_BLOCK_DEPTH, Prim, Space};
use cadcraft_geom::{Bounds2, Circle, EPS, Ellipse, Mat3, PI, Segment, Vec2, intersect_ext};
use serde::Serialize;
@@ -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,8 +384,8 @@ fn osnap_in_with_prims(
deferred: bool,
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<(Option<SnapHit>, Vec<Prim>)> {
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?;
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?;
// Intersections between nearby primitives; Apparent Intersection also where their extensions
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
// that don't reach each other).
@@ -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> {
@@ -398,9 +475,50 @@ pub(crate) fn gather(
aperture: f64,
osmode: u32,
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
gather_in(d, space, ix, cursor, aperture, osmode, &[])
gather_in(d, space, ix, cursor, aperture, osmode, &[], None)
}
/// The point nearest `cursor` within `aperture` on the visible objects of `space` other than
/// `skip` (and on the objects inside block references), with the object's direction there (a unit
/// vector; a circle's or arc's runs counterclockwise): what an alignment grip aligns a dynamic
/// block reference with.
pub(crate) fn nearest_with_direction(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, skip: Handle) -> Option<(Vec2, Vec2)> {
let ix = crate::spatial::index(d, space);
let (_, prims) = gather_in(d, space, &ix, cursor, aperture, 0, &[], Some(skip))?;
let mut best: Option<(f64, Vec2, Vec2)> = None;
let mut consider = |at: Vec2, dir: Vec2| {
let dd = at.dist(cursor);
if at.is_finite() && dir.len() > 1e-12 && dir.is_finite() && dd <= aperture && best.is_none_or(|(bd, _, _)| dd < bd) {
best = Some((dd, at, dir * (1.0 / dir.len())));
}
};
for p in prims.iter().take(2000) {
if let Prim::Circle(c) = p {
let at = c.closest(cursor);
consider(at, (at - c.center).perp());
continue;
}
if let Prim::Infinite { base, dir, .. } = p {
let len = dir.len();
if len > 1e-12 {
let u = *dir * (1.0 / len);
consider(*base + u * (cursor - *base).dot(u), u);
}
continue;
}
for seg in prim_segments(p) {
let seg = fix_circle(&seg);
let at = seg.closest(cursor);
match seg {
Segment::Line(l) => consider(at, l.b - l.a),
Segment::Arc { arc, .. } => consider(at, (at - arc.center).perp()),
}
}
}
best.map(|(_, at, dir)| (at, dir))
}
#[allow(clippy::too_many_arguments)]
fn gather_in(
d: &Drawing,
space: &Space,
@@ -409,6 +527,7 @@ fn gather_in(
aperture: f64,
osmode: u32,
frozen: &[String],
skip: Option<Handle>,
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
let probe = Bounds2::new(cursor, cursor).expand(aperture);
let mut cands: Vec<(u32, Vec2)> = Vec::new();
@@ -416,7 +535,7 @@ fn gather_in(
let mut count = 0usize;
let mut budget = MAX_BLOCK_LEAVES;
for (e, known) in crate::select::candidates(d, space, ix, &probe.expand(aperture), true, false)? {
if !d.is_visible(e) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)) {
if !d.is_visible(e) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)) || Some(e.handle) == skip {
continue;
}
let inf = crate::select::is_infinite(e);
@@ -458,7 +577,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 +589,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 +627,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 +650,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 +959,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 +972,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 +1230,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)),
+9
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();
+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());
}
+64 -1
View File
@@ -4,7 +4,7 @@
use std::sync::Arc;
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, Text};
use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, MText, MultilineAttrib, Text};
use cadcraft_engine::geom::Vec3;
use serde_json::json;
@@ -45,3 +45,66 @@ fn references_take_lock_position_from_the_definition() {
let Some(EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| e.kind.clone()) else { panic!("no reference") };
assert_eq!(i.attribs[0].modes, AttribModes { verify: false, preset: false, lock_position: true });
}
/// A definition at `x` with `modes`, invisible or not, multiline or not.
fn definition(tag: &str, x: f64, modes: AttribModes, invisible: bool, multiline: bool) -> Attrib {
let text = Text {
insert: Vec3::new(x, 0.0, 0.0),
align_pt: None,
height: 2.0,
value: tag.into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
};
let multiline = multiline.then(|| {
let mtext = MText {
insert: Vec3::new(x, 0.0, 0.0),
height: 2.0,
width: 0.0,
attach: 7,
rotation: 0.0,
style: "Standard".into(),
contents: format!("{tag}\\PTWO"),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
};
MultilineAttrib { mtext, read_as: format!("{tag}\nTWO") }
});
Attrib { tag: tag.into(), text, invisible, constant: false, prompt: tag.into(), props: Default::default(), multiline, modes }
}
#[test]
fn only_shown_unlocked_attributes_have_grips_and_a_multiline_one_moves_its_text() {
let mut d = cadcraft_engine::doc::Drawing::new_imperial();
let locked = AttribModes { lock_position: true, ..AttribModes::default() };
let mut b = Block::new("TAG");
for a in [
definition("FREE", 0.0, AttribModes::default(), false, false),
definition("LOCKED", 10.0, locked, false, false),
definition("HIDDEN", 20.0, AttribModes::default(), true, false),
definition("NOTE", 30.0, AttribModes::default(), false, true),
] {
let h = d.new_handle();
b.entities.push(Entity::new(h, EntityKind::AttDef(a)));
}
d.blocks.insert("TAG".into(), Arc::new(b));
let mut s = Session::empty();
s.open_drawing(d, "tags", None);
let r = s.execute("insert", &json!({ "name": "TAG", "at": [100, 0] })).unwrap();
let h = cadcraft_engine::doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
// The insertion point, FREE and NOTE: no grip for the locked or the invisible attribute.
let g = s.grips_of(h).unwrap();
assert_eq!(g.iter().map(|p| p.x).collect::<Vec<_>>(), [100.0, 100.0, 130.0]);
// NOTE's grip (index 2) dragged up 5: its multiline text moves with it.
s.execute("grip.stretch", &json!({ "handle": h.hex(), "index": 2, "to": [130, 5] })).unwrap();
let Some(EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| e.kind.clone()) else { panic!("no reference") };
let note = i.attribs.iter().find(|a| a.tag == "NOTE").unwrap();
assert_eq!((note.text.insert.y, note.multiline.as_ref().unwrap().mtext.insert.y), (5.0, 5.0));
let free = i.attribs.iter().find(|a| a.tag == "FREE").unwrap();
assert_eq!(free.text.insert.y, 0.0, "the others stay");
}
@@ -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();
+53
View File
@@ -145,3 +145,56 @@ fn a_grip_drag_previews_the_reference_in_its_own_colours() {
let blue = cadcraft_engine::doc::color::Color::True(cadcraft_engine::doc::color::Rgb(0x2f, 0x6b, 0xff));
assert!(preview[n..].iter().all(|e| e.common.color == blue));
}
#[test]
fn a_grip_with_a_value_list_marks_its_stops_while_dragged() {
let (mut s, h) = session();
// Width is a list (30, 32, 36) from (0, -4): its end can stop 30, 32 or 36 along it.
let stops = cadcraft_engine::doc::dynblock::grip_stops(s.doc().unwrap(), h, 2, GripPart::End);
let at: Vec<(f64, f64)> = stops.iter().map(|(p, _)| (p.x, p.y)).collect();
assert_eq!(at, [(130.0, -4.0), (132.0, -4.0), (136.0, -4.0)]);
assert!(stops.iter().all(|(_, way)| (way.x - 1.0).abs() < 1e-12 && way.y.abs() < 1e-12));
// A grip that isn't on a list or increments has none; nor a list grip.
assert!(cadcraft_engine::doc::dynblock::grip_stops(s.doc().unwrap(), h, 1, GripPart::At).is_empty());
// The preview marks each stop with a tick across the travel, a few pixels long.
s.start_dyn_grip(h, 2, GripPart::End).unwrap();
let half = 6.0 * s.pixel_size();
let ticks: Vec<(f64, f64)> = s
.preview(Vec2::new(133.0, 0.0))
.into_iter()
.filter_map(|e| match e.kind {
cadcraft_engine::doc::EntityKind::Line(l) if (l.a.x - l.b.x).abs() < 1e-9 && ((l.b.y - l.a.y).abs() - 2.0 * half).abs() < 1e-9 => {
Some((l.a.x, (l.a.y + l.b.y) / 2.0))
}
_ => None,
})
.collect();
assert_eq!(ticks, [(130.0, -4.0), (132.0, -4.0), (136.0, -4.0)]);
}
/// An alignment grip dragged onto a line (the synthetic Align block of the io tests, a line at
/// 30° from (120, 100)): the reference moves onto the line and turns along it, as AutoCAD does;
/// away from objects it only moves.
#[test]
fn an_alignment_grip_aligns_with_the_line_at_the_cursor() {
let src = include_str!("../../../io/tests/data/dynblock_params.txt").replace("\r\n", "\n");
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
let mut s = Session::empty();
s.open_drawing(d, "params", None);
let r = s.execute("insert", &json!({ "name": "Align", "at": [100, 100] })).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
let g = s.execute("blocks.reference.grips", &json!({ "handle": h.hex() })).unwrap();
assert_eq!(g[0]["shape"], "alignment");
// A point on the line, a little below it.
let (c, sn) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
let to = [120.0 + 10.0 * c + 0.01 * sn, 100.0 + 10.0 * sn - 0.01 * c];
s.execute("blocks.reference.grip", &json!({ "handle": h.hex(), "node": 1, "part": "base", "to": to })).unwrap();
let Some(cadcraft_engine::doc::EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| &e.kind) else { panic!("a reference") };
assert!((i.rotation.to_degrees() - 30.0).abs() < 1e-6, "{}", i.rotation.to_degrees());
assert!((i.insert.x - (120.0 + 10.0 * c)).abs() < 1e-6 && (i.insert.y - (100.0 + 10.0 * sn)).abs() < 1e-6, "{:?}", i.insert);
// Far from anything: it only moves.
s.execute("blocks.reference.grip", &json!({ "handle": h.hex(), "node": 1, "part": "base", "to": [0, -50] })).unwrap();
let Some(cadcraft_engine::doc::EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| &e.kind) else { panic!("a reference") };
assert!((i.rotation.to_degrees() - 30.0).abs() < 1e-6 && i.insert.x.abs() < 1e-9 && (i.insert.y + 50.0).abs() < 1e-9);
}
+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);
}
+3
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;
@@ -145,6 +147,7 @@ mod refedit;
mod region;
mod rename_cmdline;
mod rotate_reference;
mod rotation_grip_input;
mod scale_offset_z;
mod select_keywords;
mod select_similar;
@@ -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();
@@ -0,0 +1,44 @@
//! The rotation grip of a dynamic block asks for an angle: Dynamic Input shows one angle box,
//! holding the angle the cursor would give as Properties will show it. The drawing is the
//! synthetic Symbol block of the io tests (Angle1 about its base, its grip at the radius' end).
use cadcraft_engine::Session;
use cadcraft_engine::doc::Handle;
use cadcraft_engine::doc::dynblock::GripPart;
use cadcraft_engine::geom::Vec2;
use serde_json::json;
fn dxf(src: &str) -> String {
src.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(|l| {
let (code, value) = l.split_once(' ').unwrap_or((l, ""));
format!("{code}\n{value}\n")
})
.collect()
}
/// A session with Symbol and a reference to it at (100, 100).
fn session() -> (Session, Handle) {
let src = include_str!("../../../io/tests/data/dynblock_symbol.txt").replace("\r\n", "\n");
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
let mut s = Session::empty();
s.open_drawing(d, "symbol", None);
let r = s.execute("insert", &json!({ "name": "Symbol", "at": [100, 100] })).unwrap();
(s, Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap())
}
#[test]
fn the_rotation_grip_asks_for_an_angle_and_shows_it_live() {
let (mut s, h) = session();
s.start_dyn_grip(h, 15, GripPart::End).unwrap();
assert!(s.current_prompt().is_some_and(|p| p.angle), "{:?}", s.current_prompt());
// The grip is at (102, 100); straight above the base is a quarter turn.
assert_eq!(s.live_value(Vec2::new(100.0, 102.0)).as_deref(), Some("90°"));
assert_eq!(s.live_value(Vec2::new(98.0, 100.0)).as_deref(), Some("180°"));
// Nothing is changed by looking.
let props = s.execute("blocks.reference", &json!({ "handle": h.hex() })).unwrap();
let angle = props["properties"].as_array().unwrap().iter().find(|p| p["name"] == "Angle1").unwrap()["value"].clone();
assert_eq!(angle, json!("0"));
}
@@ -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] {
@@ -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] {
+118 -4
View File
@@ -268,19 +268,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 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 +310,109 @@ 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(),
})
}
/// 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");
}
+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")
+47 -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;
@@ -71,6 +71,8 @@ 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>,
}
/// Read a DXF file into a drawing.
@@ -102,6 +104,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,11 +159,20 @@ 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),
@@ -165,7 +188,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 +212,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 +245,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;
+35 -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 {
@@ -515,6 +516,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 +578,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 +600,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 +728,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",
+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