Compare commits

...
Author SHA1 Message Date
dependabot[bot] 37d94bd492 ci(deps): bump the actions group across 1 directory with 3 updates
Bumps the actions group with 3 updates in the / directory: [storytold/craft-common-actions/.github/workflows/nightly-release.yml](https://github.com/storytold/craft-common-actions), [storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml](https://github.com/storytold/craft-common-actions) and [step-security/harden-runner](https://github.com/step-security/harden-runner).


Updates `storytold/craft-common-actions/.github/workflows/nightly-release.yml` from 605d58766e8f536564da8fc81d3676ac86816dea to 1754016e67ca9b74dfa4cf4678b2ac3548e9840f
- [Commits](https://github.com/storytold/craft-common-actions/compare/605d58766e8f536564da8fc81d3676ac86816dea...1754016e67ca9b74dfa4cf4678b2ac3548e9840f)

Updates `storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml` from 605d58766e8f536564da8fc81d3676ac86816dea to 1754016e67ca9b74dfa4cf4678b2ac3548e9840f
- [Commits](https://github.com/storytold/craft-common-actions/compare/605d58766e8f536564da8fc81d3676ac86816dea...1754016e67ca9b74dfa4cf4678b2ac3548e9840f)

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

---
updated-dependencies:
- dependency-name: storytold/craft-common-actions/.github/workflows/nightly-release.yml
  dependency-version: 1754016e67ca9b74dfa4cf4678b2ac3548e9840f
  dependency-type: direct:production
  dependency-group: actions
- dependency-name: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml
  dependency-version: 1754016e67ca9b74dfa4cf4678b2ac3548e9840f
  dependency-type: direct:production
  dependency-group: actions
- dependency-name: step-security/harden-runner
  dependency-version: 2.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-25 00:40:31 +00:00
Dylan M. Taylor 7e95cfc864 packaging(linux): support co-installable nightly packages (#3450)
Linux nightly packaging by @dylanmtaylor, with the per-app Nightly flavor commits stacked on his branch.

Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
2026-11-24 18:38:19 -06:00
Tanish Manku 2ce75fcb03 Merge pull request #3456 from storytold/stack/n1
Land #3444, #3446, #3431, #3151, #3152, #2972, #3453, #2977, #2969, #3097, #2903, #3445: spline prompts, DIMSPACE, image limits, mitred wide polylines, DIMASSOC, mirror hatch, selection
2026-11-24 15:55:39 -07:00
Tanish Manku 63a5a321dd Merge #3366 again: the author's fix and test for a paste bound to another key 2026-11-24 15:32:25 -07:00
Tanish Manku 94b1174806 Merge main (after #3454, #3455); a block's image is hit on the outline of what it shows 2026-11-24 15:32:15 -07:00
Tanish Manku d538a468e4 Merge pull request #3455 from storytold/stack/u10
Land #3368, #3390, #3399, #3405, #3392, #3411, #3366: Thai PDF text, layout plot settings, Polish strings, dimension inline editor, table cell text, ATTDIA, system clipboard paste
2026-11-24 15:31:19 -07:00
Tanish Manku f80dbb461a Merge pull request #3454 from storytold/stack/p1
Land #3425, #3426, #3095, #3435, #3439, #3437: hatch edge, dependency prune, tilt check, proxy graphics follow-ups, kept dimensions
2026-11-24 15:23:27 -07:00
Tanish Manku c1f771d5cd Merge pull request #3424 from storytold/stack/b1
Land #963, #993, #1752 (with #1030, #1098, #1699, #1723): dynamic block references rotate, flip, array, scale, align and look up
2026-11-24 15:04:29 -07:00
moandClaude Fable 5.2 57c1d36fc0 fix(ui-egui): a paste bound to another key reads the system clipboard first
The shortcut loop ran every paste command as already read, but only the
ones from this frame's clipboard events are. A paste command the user
bound to a key of its own fired from the key press with nothing read, so
it pasted what this window held. It is now held like a menu paste.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 17:04:19 -05:00
Tanish Manku d71f2b9584 Crossing selection: a block's image is tested by what it shows, not by its unclipped corners 2026-11-24 14:36:50 -07:00
Tanish Manku 8d3e176aa8 Merge #3445: Select block references by drawn geometry in crossing windows 2026-11-24 14:36:33 -07:00
Tanish Manku 5d8bfff1d4 Merge #2903: Select: a blank MTEXT is picked inside its box (fixes #2810) 2026-11-24 14:36:31 -07:00
Tanish Manku f16fb24b40 Merge #3097: Options: turn off the update check at start 2026-11-24 14:36:29 -07:00
Tanish Manku 59e7a0b178 Merge #2969: fix(engine): preserve hatch direction when mirroring 2026-11-24 14:36:27 -07:00
Tanish Manku df624b7a49 Merge #2977: fix(engine): respect DIMASSOC1 for new dimensions 2026-11-24 14:36:25 -07:00
Tanish Manku fc09368b69 Merge #3453: Wide polylines: mitre the corners instead of leaving notches (#3443) 2026-11-24 14:36:23 -07:00
Tanish Manku 5b4bbd933c Merge #2972: test: make non-Unicode filename fixtures portable on macOS 2026-11-24 14:36:21 -07:00
Tanish Manku 6deb10f4a8 Merge #3152: Images: IMAGEATTACH refuses a wrongly typed at, scale, rotation or name 2026-11-24 14:36:19 -07:00
Tanish Manku b2c35cd100 Merge #3151: Images: loaders start a file only while its largest size still fits the loaded-image limit 2026-11-24 14:36:17 -07:00
Tanish Manku 137c8e8a08 Merge #3431: Use dimension text height for DIMSPACE Auto 2026-11-24 14:36:15 -07:00
Tanish Manku 7f5750dc1f Merge #3446: SPLINE: handle Method and Object at the CV first-point prompt 2026-11-24 14:36:14 -07:00
Tanish Manku ef59bd8251 Merge #3444: SPLINE: ask again when the CV degree is fractional 2026-11-24 14:36:12 -07:00
Tanish Manku fe5b66d163 Paste: a paste command fired by a user-bound key asks for the system clipboard, like the menu 2026-11-24 14:35:51 -07:00
Tanish Manku 6d5bc58b72 Merge #3366: Edit > Paste and typed PASTECLIP read the system clipboard, like Ctrl+V (#3320) 2026-11-24 14:35:31 -07:00
Tanish Manku 603852d47e Merge #3411: INSERT: ATTDIA and the Edit Attributes dialog (repair of #2376) 2026-11-24 14:35:28 -07:00
Tanish Manku c35d323fe9 Merge #3392: DXF: preserve table cell text in 2007 and later saves 2026-11-24 14:35:26 -07:00
Tanish Manku 4ab5a56dc6 Merge #3405: Dynamic dimension inline editor: claim pointer drag, select text on open, commit on focus loss 2026-11-24 14:35:24 -07:00
Tanish Manku 4562fcbc44 Merge #3399: i18n(pl): translate the 218 strings added since #218 2026-11-24 14:35:23 -07:00
Tanish Manku 7cb911dbd4 Merge #3390: Save: every layout keeps its plot settings, the Model layout included 2026-11-24 14:35:21 -07:00
Tanish Manku d1fa21d798 Merge #3368: PDF text: Thai sara am reads after its tone mark (น้ำ, not นำ้); builds on #3090 (#2899) 2026-11-24 14:35:19 -07:00
Tanish Manku 6db635aadb Merge #3437: keep proxy graphics on their layers when the layer table changes (#3094) 2026-11-24 14:34:57 -07:00
Tanish Manku a6995acce4 Merge #3439: draw kept dimensions from their *D block and keep it on save (#3438) 2026-11-24 14:34:17 -07:00
Tanish Manku 21d295d671 Landing fixes: the two new tests join the tests/it binary; the POLYLINE caller of tilted() passes a closure 2026-11-24 14:33:56 -07:00
Tanish Manku 71527f87a7 Merge #3435: fix(doc): proxy graphics fill as a trait, ellipses under uneven matrices, size group after the marker (#2697 follow-ups) 2026-11-24 14:33:41 -07:00
Tanish Manku a329b3963a Merge #3095: fix(io): skip sampling arcs for the tilt check when the extrusion is on the Z axis 2026-11-24 14:33:40 -07:00
Tanish Manku 787d4e70b8 Merge #3426: DXF/DWG: prune kept ACDBASSOCDEPENDENCY objects whose target handle is unmapped 2026-11-24 14:33:40 -07:00
Tanish Manku f3959d65f9 Merge #3425: DXF/DWG: elliptic HATCH boundary edges deduplicate the shared start vertex 2026-11-24 14:33:39 -07:00
Tanish Manku 8fb4d81338 Merge #1752 again: the six review fixes (array budget, alignment grips, frozen layers) 2026-11-24 14:28:29 -07:00
Franz Ferdinand Tritschel 4370e61c17 Wide polylines: mitre the corners instead of leaving notches (#3443)
Each segment's band was built with that segment's own normal, so a wide
polyline showed a notch at every vertex. Each vertex now gets a corner on
the outer side of the turn: the two outer edges are extended until they
meet, or bevelled past the miter limit plot style joins already use.
Tapered segments meet where their own edges do; closed polylines get the
corner at their first vertex; repeated vertices don't stop it; straight
runs get nothing extra.

Wide polylines with a linetype (wide.rs) follow after #2487.
2026-11-24 22:20:40 +01:00
STE1200andClaude Opus 5.5 9f245800ee DXF/DWG: classify unknown assoc actions once
The prune guard parsed a dependency owner's action list again for each
dependency in each pass. finish now collects the handles of the kept
actions of unknown shape once, beside the handles they reference, and
the guard tests the owner against that set. The exemption is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 21:09:35 +01:00
moandClaude Fable 5.2 2ecbc112cc style: wrap the two changed lines as rustfmt asks
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 13:57:53 -05:00
mo 09eb871e38 Merge main into pdf-thai-order
# Conflicts:
#	crates/io/tests/pdf_text.rs
2026-11-24 13:49:35 -05:00
moandClaude Fable 5.2 dc143302ee fix(ui-egui): the command line's recent commands offer a paste the same way
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 13:49:14 -05:00
mo 0f62df0b35 Merge main into paste-os-clipboard
# Conflicts:
#	apps/cadcraft/src/native_menu.rs
2026-11-24 13:48:55 -05:00
moandClaude Fable 5.2 08b68e8c51 fix(macos): the menu bar offers Paste when the system clipboard may hold objects
The native menu bar refreshed enablement with the command's own check,
so Edit > Paste stayed disabled there until something was copied in this
window. It now asks clipboard::offered, like the in-window menus and the
context menu.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 13:48:45 -05:00
Yohanes Yuen afb53d5357 Fix block ray and clipped image crossing selection 2026-11-25 01:15:21 +08:00
Cody VogtandClaude Opus 5.5 ced6984630 Alignment grips: targets stay on a ray and off layers frozen in the viewport
The alignment search projected the cursor onto a ray as if it were an
xline, so a point behind the ray's base could be the target; behind it the
base is now the nearest point. It also passed no frozen layers, so an object
on a layer frozen in the active MSPACE viewport (not drawn there) could be
aligned with; `nearest_with_direction` now takes the viewport's frozen
layers, as the osnap search does.

Review of #3424 (CodeRabbit).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 10:46:32 -06:00
Cody VogtandClaude Opus 5.5 522ed59680 Dynamic blocks: an XY distance past the number range is refused; a polar end grip snaps its angle
With a tiny reference scale a finite typed XY distance became infinite in
block units and was stored, so the saved end point couldn't be read back as
the parameter's points. The distance and the end point must now be finite.

Dragging a polar parameter's end grip applied the distance value set but not
the angle one: the angle now snaps to its value set as typing it does, and
goes where it is dragged when the set has no limits.

Review of #3424 (CodeRabbit).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 10:36:37 -06:00
Cody VogtandClaude Opus 5.5 c862f8ac09 Dynamic blocks: the array budget is taken before offsets are kept; a repeated hatch follows its own outline
The arrays' copies were counted only after every selected object's offsets
had been cloned, so one array of 99,999 offsets over 1,000 objects held
nearly 100 million offsets before it was refused. `keep_array` now takes
each object's share of `MAX_ARRAY` before its offsets are kept.

A repeated associative hatch kept the first copy's outline handle, so
`refill_hatches` put every repeat's boundary back on the first square. Each
arrayed object's copies get their handles first, by place in the array
(in the same order as before, so the handles are unchanged), and a
repeated hatch's loop names the copy of its outline at the same place.

Review of #3424 (CodeRabbit).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 10:30:30 -06:00
Walter Haslbeck de1fb50043 proxy layers: the same marker on another layer is a conflict 2026-11-24 17:07:40 +01:00
Walter Haslbeck ebda56eab5 proxy graphics: fill hatches stay out of picking and snaps; three-point tests on their own 2026-11-24 17:07:38 +01:00
Walter Haslbeck 8c2852fd2d Snaps: dimensions inside blocks reach their block; the block moves with group 12 as drawn 2026-11-24 16:11:26 +01:00
Walter Haslbeck 4c7b64d37b proxy layers: indices above 65,535 resolve through the file's table 2026-11-24 16:11:24 +01:00
Walter Haslbeck 85e0fca6b4 proxy graphics: a circle or arc seen edge-on draws as the line it covers 2026-11-24 16:11:22 +01:00
Walter Haslbeck ec31dad772 proxy layers: a kept layer isn't a conflict; name indices around ones above 65,535 2026-11-24 14:59:34 +01:00
Walter Haslbeck 72f0dddc81 proxy graphics: fit three-point chunks in their own plane, collinearity relative to the triangle 2026-11-24 14:59:28 +01:00
Walter Haslbeck a4b15ec5f1 Kept dimensions: place the block reference at its base point, ByBlock transparency and plot style; snaps follow it 2026-11-24 14:59:21 +01:00
bic98andOpenAI Codex 1a0363905b SPLINE: handle Method and Object at the CV first-point prompt
Co-authored-by: OpenAI Codex <noreply@openai.com>
2026-11-24 22:04:03 +09:00
Yohanes Yuen 15d2a63b45 Use block geometry for crossing selection 2026-11-24 20:36:48 +08:00
bic98andOpenAI Codex 877ce87557 SPLINE: ask again when the CV degree is fractional
Co-authored-by: OpenAI Codex <noreply@openai.com>
2026-11-24 21:32:04 +09:00
Walter Haslbeck f33fa1ee0f proxy layers: name indices by the record's own graphics; read only the declared size
Review: a proxy copied from another drawing was remapped against the wrong
table; its indices are now named by its own decoded graphics (decoded again
with marker names), the file's table only as fallback. Only the 310 groups
holding the declared size are read and rewritten; names are looked up once.
2026-11-24 12:21:09 +01:00
Walter Haslbeck 80470c03e3 proxy graphics: axes through the linear part only; fill under a filled ellipse
Review: a tiny scale under a large translation lost the circle's axes to
cancellation; a filled circle that becomes an ellipse lost its fill.
2026-11-24 12:21:08 +01:00
Walter Haslbeck 3ac368c013 Kept dimensions reference their *D block instead of copying it
Review: copying block contents into the graphics multiplied nested
dimensions exponentially, missed nested pictures and the block's draw
order. One reference to the block lets the renderer's depth and size
limits, nesting and SORTENTS apply as for any block reference. PURGE keeps
the block a kept dimension names; picking uses the drawn block.
2026-11-24 12:08:09 +01:00
Walter Haslbeck f297806c43 fix: draw kept dimensions from their *D block and keep it on save (#3438, #1161)
A LARGE_RADIAL_DIMENSION or ARC_DIMENSION CADCraft keeps as read draws the
*D block its AcDbDimension part names, as AutoCAD does; without one, the
proxy graphics in its AcDbEntity part (the decoder learns POLYLINE_WITH_NORMAL,
chunk 32). Saving counts that block as used, so it is written and AutoCAD
reads the dimension again. cadcraft-cli no longer counts unknown entities
that draw graphics as not drawn.
2026-11-24 10:23:30 +01:00
Walter Haslbeck a4aa6cfa68 fix: keep proxy graphics on their layers when the layer table changes (#3094)
Proxy graphics name layers by their index in the file's LAYER table.
- Layers proxy graphics draw on count as used for PURGE and layer.delete,
  as in AutoCAD.
- Drawing::proxy_layers keeps the file's layer order under current names;
  saving turns each ATTRIBUTE_LAYER index into the written table's, so
  purging a layer before them no longer moves the graphics (AutoCAD itself
  saves the old indices).
- RENAME, LAYMRG and LAYDEL update the decoded graphics and that list.
- A LAYER or LTYPE record without a handle or name keeps its place in the
  index lists, so the records after it don't shift (review of #3423).
2026-11-24 09:25:46 +01:00
STE1200andClaude Opus 5.5 10a493d24c DXF/DWG: rewrite assoc action lists with non-owned dependencies
acadrust writes each AcDbAssocAction dependency entry as group 360
(owned) or 330 (not owned). The list rewrite accepted only 360 entries,
so an action with a 330 entry kept a stale count and a null entry after
a dependency was pruned. The rewrite now accepts both codes, keeps each
surviving entry's code, keeps input-null entries, and drops only
entries whose object is gone.

A dependency is no longer pruned when an action of unknown header
shape owns it or names it in any group 330 or 360, so that action's
count and list stay consistent. The prune loop runs until nothing
changes instead of at most 64 passes, and the cascade finds owners
through owner_of, so a null-owner body goes with its pruned hard owner
and stays while another live object holds it.

Tests: assoc_dependency_prune gains a mixed 330/360 list, a null-owner
body with one and with two hard owners, an unknown action header, and
an unknown action that lists a dependency of a known action by 330.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:06:12 +01:00
Walter Haslbeck bc6e0010eb fix(doc): proxy graphics: fill as a trait, ellipses under uneven matrices, size after the marker
Follow-ups to #2697 from the review in #3423:
- ATTRIBUTE_FILL is an AcGiFillType trait (1 always, 2 never) in force
  until the next one, for polygons and circles; a filled shape keeps its
  outline. Before, a 2 turned fill on, and only for the next polygon.
- A circle or arc under a matrix that scales its plane unevenly is an
  ellipse or elliptical arc; 3-point chunks are fitted in their plane.
- The size group is the first 92/160 after the AcDbProxyEntity marker.
- Only what the 310 groups hold is reserved, not the size claimed.
2026-11-24 08:05:57 +01:00
cloutier a888218786 fix(engine): use dimension text height for DIMSPACE Auto (#3429) 2026-11-23 22:36:37 -05:00
code-compliant 2017653a14 Correct the ATTDIA default in the system variable table comment 2026-11-24 11:26:49 +08:00
code-compliant d759668ff6 INSERT: a point does not answer an attribute prompt; ATTDIA defaults to 1
A canvas click reaches INSERT as Input::Point while the attribute prompts wait. The Attribs arm treated any non-text input as the default and advanced, so the dialog closed and the first attribute took its default. Ignore Input::Point and keep prompting, as Verify does; Enter still keeps the default.

Set ATTDIA's session default to 1, AutoCAD 2026's initial value, and update tests that assumed 0 to set it explicitly. Add tests for a point at the plain command line and a canvas click with the dialog open.
2026-11-24 11:16:51 +08:00
Jon Breen 661d0776a3 Keep saved pixel paper units on kept plot settings
The inherited-unit repair for group 72 now applies only to saved inch or
millimeter values (0 or 1). A layout saved in pixels (2) keeps 2 when its
units are unchanged, including after a device-only edit; an explicit unit
edit still writes its unit.
2026-11-23 20:31:49 -06:00
Zhan Zhancheng 1d28c3ef32 ui-egui: prevent inline dimcon Enter/Escape from leaking to command line 2026-11-24 09:08:41 +08:00
Zhan Zhancheng 34777543d9 ui-egui: guard inline dimcon edit across drawings and LISP prompts 2026-11-24 08:00:12 +08:00
Jon Breen 0611bad380 Review: Model flag on kept plot settings; shade groups only where the version defines them
write_plot_settings takes the layout's model flag and passes it to the baseline
call. Kept group 70 always has bit 1024 set for Model and cleared for paper
layouts. Plot groups 76 to 78 are written from AC1018 and 333 from AC1021, and
333 only when the object it names is saved.
2026-11-23 15:50:38 -06:00
Jarek Jastrzębski 08dfe1ed8d i18n(pl): translate the 218 strings added upstream
Dimension Style Manager (lines and arrowheads, text, fit, primary and
alternate units, tolerances), Blocks palette and block libraries, icon
sizes and a few prompts. translation_gaps reports nothing missing for pl.
Terms follow the existing catalog: linia pomocnicza / wymiarowa, grot,
odnośnik, rodzaj linii, grubość linii, LUW.
2026-11-23 22:49:40 +01:00
STE1200andLetta Code 99a83201b5 DXF/DWG: prune kept ACDBASSOCDEPENDENCY objects whose target handle is unmapped
When dxf_raw::finish remaps handles on kept associative objects, a
dangling dependentOnObject pointer (group 330 inside the
AcDbAssocDependency subclass) was rewritten to "0" while the dependency
remained active and stayed listed in its owning ACDBASSOCACTION 360
dependency list.

dxf_raw::finish now drops any kept AcDbAssocDependency whose non-null
dependentOnObject handle does not resolve to a written object/entity
(along with kept objects owned only by it), while leaving originally
unbound dependencies (330 = 0 in the input) untouched. In Map::object,
AcDbAssocAction filters dropped handles out of its 360 dependency list
and updates its 90 dependency count.

Tests: assoc_dependency_prune::{orphaned_assoc_dependency_is_pruned_along_with_action_entry_and_body,originally_unbound_assoc_dependency_with_null_target_is_kept}.

👾 Generated with [Letta Code](https://letta.com)

Co-Authored-By: Letta Code <noreply@letta.com>
2026-11-23 22:19:37 +01:00
STE1200andLetta Code 008d538e28 DXF/DWG: elliptic HATCH boundary edges deduplicate the shared start vertex
When dxf_read::hatch converts an edge-based HATCH boundary loop into a
HatchLoop polyline, line_edge, circular_edge, and spline_edge each skip
the incoming first vertex when it coincides with the previous end vertex
(last.p.near(point, 1e-9)). elliptic_edge did not, emitting consecutive
duplicate vertices whenever an elliptic edge met a neighbouring edge.

elliptic_edge now applies the same skip check as spline_edge (after
reversing points for !ccw).

Tests: hatch_elliptic_edge_dedup::{ccw,cw}_elliptic_edge_does_not_duplicate_shared_start_vertex.

👾 Generated with [Letta Code](https://letta.com)

Co-Authored-By: Letta Code <noreply@letta.com>
2026-11-23 22:19:33 +01:00
Jon Breen ff0e4173d3 Review: inherited paper units follow a changed MEASUREMENT
A layout that inherits its paper units wrote back the file's group 72 after
MEASUREMENT changed, so it reopened with the old unit. Group 72 is now
rewritten when it no longer matches the unit the drawing applies.
2026-11-23 15:14:16 -06:00
Jon Breen 94d9e3542f Save: every layout keeps its plot settings, the Model layout included
See the pull request description for the cause, the change and the tests.
2026-11-23 15:14:16 -06:00
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
code-compliant df5063f5cd INSERT: a cancel handler's command never takes the person's dialog origin
Session::start_from recorded the incoming origin and command number, then
cancelled the running command. Cancellation can abort a paused LISP routine
and run its *error* handler; a handler that starts a command records that
command's Program origin through its own Session::start_from. The new
command's factory then ran after that cancellation, and the INSERT and
MINSERT factories read the overwritten field, so a person's '-INSERT T …
replacing a waiting routine was taken for a program's and ATTDIA 1 opened
no dialog.

The origin and number are now recorded after the cancellation, so they
describe this start and the factory sees the origin this command was
started with; a handler's own commands keep their Program origin. The
handler's command also keeps its own number, which the dialog identity and
the Blocks palette's placing test use.

Regression tests replace (command "LINE" "0,0" pause), whose *error*
handler starts LINE, with a person's '-INSERT or '-MINSERT under ATTDIA 1:
both fail before the change (command_origin Program, no attribute entry),
in the engine and in the UI harness, and the handler's LINE is still drawn
as the program's. The UI test comment that called a fresh OK an old
confirmation now says what the test does.
2026-11-23 22:26:26 +08:00
Jon Breen 3c70690990 Review: covered table cells write empty values in DXF 2007 and later
A covered cell that still held text wrote it into the typed and formatted
values. The modern value block is now empty for covered cells; the legacy
groups are unchanged. The test keeps text in a covered cell.
2026-11-23 08:20:59 -06:00
Zhan Zhancheng b23eaa591c Dynamic dimension inline editor: claim pointer drag, select text on open, commit on focus loss 2026-11-23 21:18:42 +08:00
code-compliant b244b59ec2 INSERT: a LISP token that replaces a running command never opens the dialog
A command a routine started was the program's only through
Session::start_programmatic, which (command …) uses for a start at Command:.
A token it feeds while a command runs takes the typed-input path instead
(Session::typed → typed_token), and that path called Session::start, which
records Origin::Person outside a script. With ATTDIA 1, the INSERT that
(command "LINE" "0,0" "'-INSERT" …) starts to replace LINE asked for the Edit
Attributes dialog, which the routine could never answer. MINSERT, COMMAND-S
and VL-CMDF reach the same path.

Session::lisp_drive now marks its slice as program input (Session::program_input,
saved and restored around the slice, a panic in it included), and Session::start
records Origin::Program for a command it starts then, as it does in a script. A
person typing the same tokens at the command line still gets the dialog.
2026-11-23 20:42:26 +08:00
code-compliant d3419d156a INSERT: only a command a person started opens the Edit Attributes dialog
A script's flag was the only origin INSERT consulted, and only Session::script
set it. A LISP (command "-INSERT" …) — in a LISP file, APPLOAD, or
engine.execute {"command":"lisp"} — started INSERT outside a script, so a
routine that ended before the first attribute answer left ATTDIA 1 to open a
dialog it could never answer; a routine resumed after a yield had the same gap.

Commands now record who started them for their whole life
(Session::command_origin(): a person at the command line or from a menu,
toolbar or palette, or a program), and INSERT opens the dialog only for a
person's command. Session::start_programmatic marks an AutoLISP (command …)
start, and Session::start takes a script's commands as the program's, so the
scripted INSERT still asks at the command line. A typed or menu INSERT keeps
the dialog.
2026-11-23 20:42:26 +08:00
code-compliant 21cd284434 Edit Attributes: a confirmation for the old dialog never finishes its replacement
One drained control batch can cancel the dialog's command and start another
INSERT of the same block before the next frame. The draft filter gave the
replacement its own defaults, but the window, its fields and OK kept the same
ids, and a click or Enter queued for the old dialog (ui.click and ui.key wait
in the app's synthetic input, one pointer event a frame) confirmed the
replacement with defaults nobody had seen.

The window and every widget in it now carry the drawing and command they
belong to, so a press on the old OK never ends on the new one and no focus or
keyboard state carries over; input queued before a dialog appeared is dropped
instead of handed to its replacement; and no answer is taken on the frame a
new owner's dialog first draws.
2026-11-23 20:42:19 +08:00
code-compliant ed012ca376 INSERT: a command a script starts never opens the Edit Attributes dialog
INSERT copied ATTDIA into the command without asking who started it. A
script that ends before the first attribute answer leaves INSERT waiting,
so a scripted -INSERT with ATTDIA 1 exposed the Edit Attributes dialog,
which a script cannot answer.

InsertM now records whether a script started it (Session::script_running)
for its whole life, and ATTDIA opens the dialog only for a command the
user started. A typed INSERT with ATTDIA 1 still asks in the dialog.
2026-11-23 20:42:04 +08:00
code-compliant 5b00e36200 Edit Attributes: a dialog draft belongs to the drawing and command that asked for it
The dialog kept its draft by block name and row count alone. A cancel
through the control channel runs before the dialog frame, so a second
INSERT of the same block could reach its attribute prompts in the same
drained batch and then inherit the cancelled draft; OK, or a queued
confirmation, submitted those values to the new command. A redefined block
with the same name and row count got values meant for other tags.

Session::attribute_entry now stamps each entry with the active drawing's
uid and the command's number in Session::commands_started, and the dialog
shows its draft only while both still match. A replacement command starts
from its own defaults, so a confirmation left over from the old dialog can
only submit what the new one shows.
2026-11-23 20:42:04 +08:00
code-compliant bd7b7b77b0 Merge main into pr/insert-attrib-modes
Main gained ATTREQ, Preset and Verify prompts (#2535) while this branch was
open, so what is new here is ATTDIA and the Edit Attributes dialog: the
setting and its SETVAR registration, Session::attribute_entry and its guard
hook, the dialog, and the tests. Main's prompt flow is kept as it is: every
attribute value at the command line (or in the dialog), then the Verify
attributes asked again.

INSERT counts its attribute answers per definition (`asked`) instead of by
tag, as main still does: a block with two definitions of one tag stopped
asking until the map grew, which it never did. The duplicate-tag test fails
without it.

docs/gaps.md and docs/ui-parity.md keep main's rows; the affected rows are
named in the pull request instead.
2026-11-23 13:21:47 +08:00
Jon Breen 807085159d DXF: preserve table cell text in 2007 and later saves
Write modern table cell value blocks and keep merged anchors
content-bearing. Read formatted cell text when typed text is absent.
2026-11-22 17:15:42 -06:00
Vincent Cloutier a1b77015b6 Refresh MIRROR hatch direction against current main 2026-11-21 14:04:42 -05:00
Vincent Cloutier fbcebf3392 Refresh DIMASSOC mode handling against current main 2026-11-21 13:53:54 -05:00
moandClaude Sonnet 5.5 f581688caf fix(ui-egui): tie a held paste to its own clipboard request
A cancelled request's answer could complete a newer held paste, whose
own answer was then dropped. Each RequestPaste now has an identity kept
with the held command, and a Paste completes the command only when it
answers that request; otherwise it is a stale answer that pastes
nothing (its text still becomes the clipboard, being the system
clipboard's) and the command keeps waiting for its own answer or
deadline.

Where the window answers in the next frame or not at all (X11, Windows,
macOS), a request is answerable for that one frame, counted in frames,
so a paste with no answer falls back at once and a later Ctrl+V is never
taken for it. Only native Wayland, which reads asynchronously with a 3 s
budget, keeps the time bound, now 5 s. The app tells the interface which
case applies from the display handle.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 13:48:41 -05:00
moandClaude Sonnet 5.5 a91650376f fix(ui-egui): attribute each Paste to the paste request it answers
A typed UI command such as quickcalc left a held paste waiting, and the
one-second window for ignoring a late Paste could be consumed by a real
Ctrl+V or missed by a slow answer, so one request could paste twice.

Typed commands now drop a held paste before the UI-command branch. Each
RequestPaste is remembered for 3.5 s, the delivery budget egui-winit
gives its asynchronous Wayland read (elsewhere the answer arrives in the
next frame's input, and nothing arrives when the clipboard has no text).
A Paste is the answer to the oldest request still remembered, so one
whose command was escaped or gave up pastes nothing, while a Paste with
no request outstanding is an ordinary Ctrl+V. This replaces the time
window that swallowed a Paste.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 13:18:51 -05:00
moandClaude Sonnet 5.5 f24468f2a1 fix(ui-egui): a held paste is cancelled by Escape and runs once
A paste waiting for the system clipboard kept running after Escape, and
a wait that ran out in the same frame as the Paste event, or a Paste that
answered a request already given up on, started a second paste.

Escape (command line and cmdline.key) and starting any other command now
drop a held paste. A Paste event in the frame the wait expires completes
the held command instead of the timeout running it first. After a
timeout or a cancel of a request already sent to the window, one Paste
within one second is treated as that request's late answer and ignored;
a real Ctrl+V inside that second is swallowed once, and pressing it
again pastes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 12:53:24 -05:00
moandClaude Opus 5.5 d3baf2e9e7 PDF text test: one glyph that shows sara aa in one word and sara am in another reads right in both
After the typed-order change of issue #2899, the sara aa glyph shows ำ in น้ำ and า in นา.
The PDF writer gives a glyph one ToUnicode entry, taken from its first use; krilla wraps a
later use with other text in its own /ActualText span. The test plots นา and น้ำ in one
drawing, in both orders, and reads the page glyph by glyph (ActualText where there is one,
else ToUnicode), which must give the typed words.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 12:52:00 -05:00
moandClaude Opus 5.5 1fa0a8b18c Complex text shaping: typed order never costs a character its own glyph in the text layer
The typed-order assignment of a cluster's characters to its glyphs could put a character
second on a glyph where the previous assignment gave every character a glyph of its own.
With น typed before the tone mark and then sara u, the shaper draws sara u before the
tone mark (FreeSerif shapes นุ้ as no, sara u, mai tho): the typed pass matched sara u to its
glyph, so the tone mark went with no and its own glyph showed nothing. Render and the PDF
writer keep a glyph's first character only, so the tone mark dropped out of the PDF text,
where the previous assignment kept all three, out of order.

glyph_chars now takes the typed assignment only when it leaves at least as many glyphs
showing a character as the plain one, and the plain one otherwise. น้ำ, ฐ with sara u as
one glyph and the Devanagari vowel sign before its consonant come out as before; the unit
test gains the unusual order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 12:52:00 -05:00
moandClaude Opus 5.5 5e01c3bb81 PDF text: Thai sara am reads after its tone mark, the glyphs of a shaped cluster show their characters in typed order
A TEXT or MTEXT with น้ำ plotted to PDF in a font such as FreeSerif or Garuda read
นำ้ in its text layer (the first part of issue #2899). The shaper splits sara am into
nikhahit and sara aa and draws the nikhahit before the tone mark. glyph_chars in
crates/fonts/src/complex.rs then gave sara am to the first glyph without a character of
its own, the nikhahit, so in drawing order, which is the order the PDF writes the glyphs
in, sara am came before the tone mark. Fonts that substitute the tone mark (Noto Sans
Thai raises it over the nikhahit) only read right because no glyph matched its own
character.

Within a cluster, own glyphs are now matched only in typed order, the other glyphs take
the remaining characters between them, and a character with no glyph of its own there
goes with the glyph before it, as a ligature's characters already go with the
ligature. In น้ำ the sara aa shows ำ after the tone mark and the nikhahit is drawn as an
outline; ฐ with sara u as one glyph still shows both. Where typed order would need a
character on a glyph before every glyph that shows one (a vowel sign drawn before its
consonant, as in Devanagari), the assignment stays as before: render and the PDF writer
take the first character of a glyph only, so moving a character onto another glyph
would drop it from the text. What is drawn does not change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 12:27:58 -05:00
moandClaude Sonnet 5.5 2d95af7d7b fix(ui-egui): Edit > Paste and PASTECLIP read the system clipboard
Only Ctrl+V reached load_system_text, so a copy made in another CADCraft
window could not be pasted from the Edit menu, the context menu or by
typing PASTECLIP, PASTEBLOCK or PASTEORIG (issue #3320).

A paste started from a menu or typed on the command line is now held for
a frame while the window is asked for the system clipboard
(ViewportCommand::RequestPaste). The resulting Paste event goes through
the same path as Ctrl+V, so the newest of this window's clipboard and
the system's wins, and then the held command runs. If no text arrives
within half a second (the clipboard holds an image or nothing), or a text
field has the keyboard, the command runs at once with what this window
holds. The web build gets a Paste only from the browser's own gesture, so
it keeps its behaviour.

The paste items are offered while a drawing is open and nothing was
copied in this window, instead of being disabled; they report an empty
clipboard when it turns out to be empty. The engine is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 12:20:10 -05: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 5c4a7ce5ed Merge remote-tracking branch 'origin/main' into thai-shaper
crates/fonts/src/complex.rs takes main's pedantic-lint style (#2568) with
this branch's glyph_chars that gives a ligature glyph every character of
its cluster.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:17:00 -05:00
tirael 3554e906e6 Merge current main into startup update preference 2026-11-17 11:04:51 +01: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
KvasExpert edf0a52640 Merge branch 'main' into update-check-option 2026-11-15 09:46:59 +01:00
dotCooCoo 7c580ec8cc Images: IMAGEATTACH refuses a wrongly typed scale when width is given
placement read `scale` only when `width` was omitted, so a call with
both a valid `width` and `"scale": "big"` attached the image. `scale`
is now checked first; a valid `width` still takes precedence.
2026-11-13 21:06:28 -08:00
dotCooCoo f833ab96f5 Images: IMAGEATTACH refuses a wrongly typed at, scale, rotation or name
A value of the wrong type for `at`, `scale`, `rotation` or `name` was
taken as omitted, so `"scale": "big"` attached an image one drawing unit
wide and `"at": "nowhere"` put it at 0,0. Each is now refused with an
error. An omitted or null value still takes its default.
2026-11-13 20:45:26 -08:00
dotCooCoo 1f56cef64e fix(engine): image loaders start a file only while its largest size still fits the loaded-image limit
When a drawing opened, each image loader checked the decoded total against
the 2 GB limit before decoding and added the image's size only after, so up
to four images of up to 512 MB each could decode at once past the limit.

A loader now starts a file only while the images decoded so far, plus the
largest image each file being decoded can become, fit under the limit, and
otherwise waits for a file to finish. With no other file being decoded one
file always starts, so the total runs past the limit by one image at most,
as it does with a single loader. A file that fails to decode counts nothing.
2026-11-13 20:36:47 -08:00
tiraelandClaude Opus 5.5 a1964aa9c5 Options: turn off the update check at start
Options ▸ User Preferences gets "Check for updates when CADCraft starts"
(on by default, desktop only). Off, the startup check and its "Update and
Restart" prompt never run; Help ▸ Check for Updates… still checks. The
choice is the OPTIONS JSON key `checkUpdatesAtStart`, kept in the profile and
restored by Reset to Defaults, for people who manage updates themselves (an
offline machine, a package manager, a pinned version).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:28:41 +01:00
Walter Haslbeck ad596f1e41 fix(io): skip sampling arcs for the tilt check when the extrusion is on the Z axis
`tilted` took its points eagerly, so every bulged edge of every LWPOLYLINE and HATCH loop was
tessellated on read, also with extrusion +Z or -Z, where no point can move and the answer is
always "not tilted". It now takes the points as a closure and returns before gathering them
when the normal's x and y are exactly 0. For such a normal `Mat4::ocs` is the identity or
(-x, y, -z), so the result is the same as before.
2026-11-12 07:48:07 +01:00
moandClaude Opus 5.5 e09870949d fix(fonts): a Thai ligature keeps every character it stands for as text
A font may draw a consonant and its below vowel as one ligature glyph:
GNU FreeSerif's Thai liga lookup replaces tho than + sara u with a
single tailless form. glyph_chars gave each glyph of a cluster at most
one character, so the characters left over in the cluster were
dropped and sara u was missing from the shaped text records.

glyph_chars now returns the characters each glyph shows, and the
cluster's last glyph takes any that are left over. push_glyph records
one text glyph per character against the same outline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:19:38 -05:00
SBaksa 086bd8a865 Select: say why a blank MTEXT frame is upright, and when its insertion points keep it a snap candidate (#2810) 2026-11-12 00:24:17 +11:00
SBaksa 72f07e5cd1 Select: a blank MTEXT's frame follows layout orientation, and its insertion points keep it a snap candidate only when INS is on and within the aperture (#2810)
A top-level MTEXT with a non-zero AcadAnnoPO value is drawn upright, so its pick frame no longer turns with the stored rotation. Insertion points now keep a blank frame in the snap pool only when INS is enabled and the point is within the aperture circle, not just the square probe.
2026-11-12 00:05:58 +11:00
SBaksa cf9f3a7ea3 Select: a blank MTEXT's bounds stay what it draws, and only the insertion points snap offers keep it a snap candidate (#2810) 2026-11-11 20:33:58 +11:00
SBaksa 2697456c9c Select: a blank MTEXT frame is only scaled for blank text, and its snap check uses the drawn insertion point (#2810) 2026-11-11 18:39:38 +11:00
SBaksa a0ce65ef06 Select: a blank MLEADER text box also catches a crossing window; share the annotation scaling (#2810)
Blank MTEXT frames use cadcraft_doc::anno_scaled, is_blank_mtext no longer allocates, and
the crossing test accepts the frame. Out-of-reach blank frames no longer use up snap
candidate or intersection slots. Adds tests for each.
2026-11-11 15:04:12 +11:00
Vincent Cloutier 71f77aca60 Merge official main font-test correction into PR2969 2026-11-10 10:36:15 -05:00
Vincent Cloutier c6ee9801b6 Merge official main font-test correction into PR2977 2026-11-10 10:10:36 -05:00
Vincent Cloutier 73c5232360 Merge official main font-test correction into PR2972 2026-11-10 09:36:05 -05:00
Vincent Cloutier 0ef5093530 PR2969: document mirror fill policy and regression coverage 2026-11-09 16:04:33 -05:00
Vincent Cloutier 4f51d0c655 PR2977: document dimension associativity policy and tests 2026-11-09 15:57:12 -05:00
Vincent Cloutier 57e32b0cdd fix(engine): honor non-associative DIMASSOC mode 2026-11-09 13:32:08 -05:00
Vincent Cloutier fb9a833144 test: handle macOS rejection of non-Unicode filenames 2026-11-09 12:42:59 -05:00
Vincent Cloutier bb36fab20e fix(engine): retain hatch direction in mirror commands and previews 2026-11-09 12:11:19 -05:00
SBaksa 2ef9cf67cf Select: a blank MLEADER text is picked inside its box (#2810)
Share the blank MTEXT frame with multileader picking and extend the
candidate bounds used by both scans and the spatial index.
Cover empty and whitespace boxes and preserve normal text picking.
2026-11-09 13:08:36 +11:00
SBaksa f04ca5144e Size a blank MTEXT's pick box at the current annotation scale
An annotative blank MTEXT is picked in the box it draws at CANNOSCALE,
and not at all while that scale hides it, as its drawn bounds already are.
2026-11-08 14:03:57 +11:00
SBaksa 89817444f2 Select: a turned blank MTEXT is picked in its turned box (#2810)
A click on a blank MTEXT is tested in its box turned with the text, not the
axis-aligned box around it (the spatial index and windows keep the larger box).
One helper holds the frame geometry for both.
2026-11-08 11:16:01 +11:00
SBaksa bc7f41d538 Select: a blank MTEXT is picked inside its box (#2810)
A blank or whitespace-only MTEXT has no glyph strokes and empty drawn bounds, so
a click inside it, and the spatial index, missed it. It is now picked (and
window/crossing selected) in its width x text-height box, placed by its
attachment point and rotation.
2026-11-08 00:25:32 +11: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
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
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
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
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 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
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
Francesco BVandClaude Opus 5.5 d3ec8efe19 INSERT: ATTDIA defaults to 0, the command line, as in AutoCAD
AutoCAD's published system variable reference gives ATTDIA an initial
value of 0: a typed INSERT asks for attribute values at the command line,
which also keeps scripts and agents typing through the command line as
before. ATTDIA 1 still opens the Edit Attributes dialog. The dialog tests
set ATTDIA 1 themselves; a new check shows the default opens no dialog.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-29 10:37:59 +01: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
Francesco BVandClaude Opus 5.5 0332836238 INSERT: Verify and Preset attributes, ATTREQ and ATTDIA with the Edit Attributes dialog (F17)
A typed or menu INSERT asks a Verify attribute's value twice and gives
Preset (and constant) attributes their defaults without asking. ATTREQ 0
gives every attribute its default; ATTDIA 1 (the default) asks for the
values in an Edit Attributes dialog, typed answers still working. Both are
user settings, as DWG keeps them in its header only before R2000. Answers
are counted per prompt, so two definitions with one tag no longer ask the
second for ever. The JSON form never asks.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-27 22:31:35 +01:00
173 changed files with 18189 additions and 661 deletions
+16
View File
@@ -0,0 +1,16 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
ga/qCA==
=3wGQ
-----END PGP PUBLIC KEY BLOCK-----
+107
View File
@@ -0,0 +1,107 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/cadcraft",
"repository_id": 1408289866,
"producer_workflow_id": null,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
"echelon",
"FredApps",
"skylartaylor"
],
"max_age_seconds": 86400,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": "cadcraft-nightly-20261124-initial",
"repository": "storytold/cadcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 380135820,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_cadcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_cadcraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_coverage",
"comparator": "LT",
"error_threshold": "80"
},
{
"metric": "new_duplicated_lines_density",
"comparator": "GT",
"error_threshold": "3"
},
{
"metric": "new_security_hotspots_reviewed",
"comparator": "LT",
"error_threshold": "100"
}
],
"debt": []
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
+42
View File
@@ -0,0 +1,42 @@
name: CADCraft release-ref nightly signer
# Enabled for supervised manual dispatch on release. Main/release contents must match.
# A reusable callee does not change context; this must be a real top-level release dispatch.
on:
workflow_dispatch:
inputs:
producer_run_id:
description: Exact untrusted producer Actions run ID
required: true
type: string
producer_run_attempt:
description: Exact untrusted producer Actions run attempt
required: true
type: string
permissions: {}
concurrency:
group: cadcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real release branch.
if: >-
github.repository == 'storytold/cadcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@1754016e67ca9b74dfa4cf4678b2ac3548e9840f
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment and export keys in its signing step.
+34
View File
@@ -0,0 +1,34 @@
name: CADCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
on:
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/cadcraft' &&
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
# no OIDC, attestation write, release environment or platform secrets in compilation.
permissions:
contents: read
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@1754016e67ca9b74dfa4cf4678b2ac3548e9840f
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
app-name: cadcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
+31 -3
View File
@@ -5,9 +5,9 @@ name: Packaging lint
on:
push:
branches: [main, release]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
pull_request:
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
workflow_dispatch:
permissions:
@@ -28,7 +28,7 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -49,3 +49,31 @@ jobs:
- name: Build and check non-executable installer fixtures
shell: pwsh
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
nightly-source-contract:
name: Nightly source contracts (no build or signing)
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check the nightly scripts without running them
run: |
for script in packaging/nightly-common.sh packaging/linux/nightly.sh packaging/macos/nightly.sh \
packaging/macos/nightly-lib.sh packaging/macos/nightly-sign.sh packaging/macos/nightly-verify.sh; do
bash -n "$script"
done
shellcheck --version
shellcheck -x -P packaging packaging/nightly-common.sh packaging/linux/nightly.sh \
packaging/macos/nightly.sh packaging/macos/nightly-lib.sh packaging/macos/nightly-sign.sh packaging/macos/nightly-verify.sh
- name: Enforce the nightly serialization and synthetic packaging contracts
run: python3 packaging/nightly-tests.py
- name: Render the Arch Nightly handoff from stub binaries
run: bash packaging/linux/nightly-arch-tar-test.sh
+8
View File
@@ -9,3 +9,11 @@
*.swp
/apps/cadcraft-web/dist/
/.claude/worktrees/
# Checked out inside the workspace by the shared nightly workflows (craft-common-actions):
# nightly_init refuses to build from a tree where these show up as changes.
/.nightly-tools
/.nightly-input
/craft-i18n
/craft-fonts
__pycache__/
+6
View File
@@ -45,6 +45,12 @@ Generated-in-code assets are original and have no file to list:
| `assets/app-icon/cadcraft-256.png` | CADCraft contributors | generated | MIT OR Apache-2.0 | |
| `assets/app-icon/cadcraft-1024.png` | CADCraft contributors | generated | MIT OR Apache-2.0 | |
| `assets/app-icon/cadcraft-macos-512.png` | CADCraft contributors | generated (macOS margin variant) | MIT OR Apache-2.0 | |
| `assets/app-icon/README.md` | CADCraft contributors | original work for this repository | MIT OR Apache-2.0 | How each icon is generated and which mark each channel uses |
| `assets/app-icon/cadcraft-nightly.png` | CADCraft contributors | generated from `assets/app-icon/cadcraft-1024.png` | MIT OR Apache-2.0 | Nightly mark: same glyph, deeper background `#0c657b`; the Linux nightly tar's icon |
| `assets/app-icon/cadcraft-nightly-1024.png` | CADCraft contributors | generated from `assets/app-icon/cadcraft-1024.png` | MIT OR Apache-2.0 | 1024 master the nightly `.icns` is generated from |
| `assets/app-icon/cadcraft-nightly.ico` | CADCraft contributors | generated from `assets/app-icon/cadcraft-nightly-1024.png` | MIT OR Apache-2.0 | Windows nightly icon (16–256 px entries) for `build.rs` |
| `assets/app-icon/cadcraft-nightly.icns` | CADCraft contributors | generated from `assets/app-icon/cadcraft-nightly-1024.png` | MIT OR Apache-2.0 | macOS nightly bundle icon (`CFBundleIconFile cadcraft-nightly`) |
| `assets/app-icon/nightly-provenance.json` | CADCraft contributors | original work for this repository | MIT OR Apache-2.0 | The exact background transform that produced the nightly set |
| `packaging/macos/dmg/background.svg` | @XusBadia | original work for this repository (2026-10-08), "CADCraft macOS DMG window background"; derived from the CADCraft app icon (`assets/app-icon/`, referenced via `<image>`, not copied); text is outlined Inter / JetBrains Mono glyph paths (OFL fonts the project already uses); no third-party material modified | MIT OR Apache-2.0 (same as the code: `LICENSE-MIT`, `LICENSE-APACHE`) | Finder window background of the macOS DMG; `packaging/macos/dmg/generate.py` renders it to `background.tiff` (see `packaging/macos/dmg/README.md`) |
| `packaging/macos/dmg/background.tiff` | @XusBadia | Rendered from `packaging/macos/dmg/background.svg` by `packaging/macos/dmg/generate.py` | MIT OR Apache-2.0 (same as the code: `LICENSE-MIT`, `LICENSE-APACHE`) | 1x + 2x HiDPI TIFF for the macOS DMG window; includes the app icon (see its row) and LittleCMS's built-in sRGB profile ("No copyright, use freely") |
| `examples/apartment.dxf` | CADCraft contributors | sample drawing made with cadcraft-cli commands | MIT OR Apache-2.0 | Original |
Generated
+1
View File
@@ -677,6 +677,7 @@ dependencies = [
"windows",
"winit",
"winresource",
"winsafe",
"zbus",
]
+4
View File
@@ -171,6 +171,10 @@ pub(crate) fn undrawn_message(d: &cadcraft_engine::doc::Drawing, path: &str) ->
ole = ole.saturating_add(1);
continue;
}
// One with proxy graphics draws them (#2697, #3438).
if !u.graphics.is_empty() {
continue;
}
let n = types.entry(u.dxf_type.as_str()).or_insert(0);
*n = n.saturating_add(1);
}
+20 -1
View File
@@ -818,7 +818,8 @@ fn non_unicode_arguments() {
assert!(err.starts_with("error: invalid UTF-8 was detected"), "{err}");
}
/// An output name that isn't valid Unicode is written as given: only its extension picks the format.
/// An output name that isn't valid Unicode reaches the filesystem unchanged: only its extension
/// picks the format. Filesystems that reject the name must report their write error.
#[cfg(unix)]
#[test]
fn non_unicode_output_names() {
@@ -836,6 +837,18 @@ fn non_unicode_output_names() {
let code = cadcraft_cli::run(args, &mut out, &mut err);
(code, String::from_utf8_lossy(&err).into_owned())
};
// APFS rejects invalid UTF-8 names (EILSEQ), although Unix paths can represent them.
// Probe this scratch filesystem rather than assuming every macOS volume behaves alike.
let probe = latin1("probe");
let rejected_name: Option<String> = match std::fs::write(&probe, b"") {
Ok(()) => {
std::fs::remove_file(&probe).expect("remove filename probe");
None
}
#[cfg(target_os = "macos")]
Err(e) if e.raw_os_error() == Some(92) => Some(e.to_string()), // Darwin EILSEQ
Err(e) => panic!("unexpected filename probe error: {e}"),
};
let b = s.0.join("b.dxf");
let cases: [(Vec<OsString>, std::path::PathBuf); 3] = [
(vec!["sample".into(), "bracket".into(), latin1("dxf").into()], latin1("dxf")),
@@ -844,6 +857,12 @@ fn non_unicode_output_names() {
];
for (args, path) in cases {
let (code, err) = run(args.clone());
if let Some(ref filesystem_error) = rejected_name {
assert_eq!(code, 1, "{args:?}: {err}");
assert!(err.contains(filesystem_error), "{args:?}: {err}");
assert!(!path.exists(), "{path:?}");
continue;
}
assert_eq!(code, 0, "{args:?}: {err}");
assert!(path.exists(), "{path:?}");
assert!(std::fs::metadata(&path).expect("stat output").len() > 0, "{path:?}");
+3
View File
@@ -77,6 +77,9 @@ windows = { version = "0.62", features = ["UI_ViewManagement"] }
# One CADCraft per sign-in: later launches hand their files over an AF_UNIX socket
# (single_instance.rs). Already in Cargo.lock through zbus.
uds_windows = "1.2.1"
# The Nightly build's own taskbar identity (process_identity.rs): the explicit
# AppUserModelID, which only a nightly launch sets.
winsafe = { version = "0.0.29", features = ["user", "shell"] }
[target.'cfg(target_os = "linux")'.dependencies]
hidapi = { version = "2.6.7", default-features = false, features = ["linux-native-basic-udev"] }
+46 -5
View File
@@ -1,23 +1,64 @@
//! Windows only: embed the app icon and version info into `cadcraft.exe`. Elsewhere a no-op.
//!
//! The build channel comes from `CADCRAFT_BUILD_CHANNEL`: `nightly-v1` compiles a Nightly build
//! with its own icon and version, `stable`/unset is the stable build, and anything else is refused
//! rather than silently producing a stable binary with a nightly name.
#[path = "src/build_channel.rs"]
mod build_channel;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=src/build_channel.rs");
println!("cargo:rerun-if-changed=../../assets/app-icon/cadcraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/cadcraft-nightly.ico");
println!("cargo:rerun-if-env-changed=CADCRAFT_REQUIRE_WINRES");
println!("cargo:rerun-if-env-changed=CADCRAFT_BUILD_SHA");
println!("cargo:rerun-if-env-changed=CADCRAFT_BUILD_CHANNEL");
println!("cargo:rerun-if-env-changed=CADCRAFT_VERSION");
println!("cargo:rustc-check-cfg=cfg(cadcraft_nightly_v1)");
let nightly = match std::env::var("CADCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=cadcraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("unsupported CADCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
// The version the build reports: the prepared feed identity for a nightly (refused when it is
// missing or is not a nightly identity), the crate version otherwise.
let built_version = if nightly {
match std::env::var("CADCRAFT_VERSION") {
Ok(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit CADCRAFT_VERSION feed identity");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=CADCRAFT_BUILT_VERSION={built_version}");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let mut res = winresource::WindowsResource::new();
if std::path::Path::new("../../assets/app-icon/cadcraft.ico").exists() {
res.set_icon("../../assets/app-icon/cadcraft.ico");
}
res.set("ProductName", "CADCraft")
.set("FileDescription", "CADCraft computer-aided design")
res.set_icon(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "CADCraft Nightly" } else { "CADCraft" })
.set("FileDescription", if nightly { "CADCraft Nightly computer-aided design" } else { "CADCraft computer-aided design" })
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) 2026 ArtCraft Team and the CADCraft contributors. MIT OR Apache-2.0.")
.set("OriginalFilename", "cadcraft.exe")
.set("InternalName", "cadcraft");
if nightly {
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
res.set("ProductVersion", &built_version);
}
if let Err(e) = res.compile() {
if std::env::var_os("CADCRAFT_REQUIRE_WINRES").is_some() {
eprintln!("embedding Windows resources failed: {e}");
+53
View File
@@ -0,0 +1,53 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/cadcraft-nightly.ico" } else { "../../assets/app-icon/cadcraft.ico" }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
assert_eq!(windows_icon_path(false), "../../assets/app-icon/cadcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/cadcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.23.1-nightly.20261120.17.1.gabcdef012345"));
for invalid in [
"",
"0.23.1",
"0.23.1-nightly",
"0.23.1-nightly.20261120",
"0.23.1-nightly.20261120.17.1.gABCDEF012345",
"0.23.1-nightly.20261120.17.1.gabcdef012345\n",
] {
assert!(!is_nightly_version(invalid), "{invalid:?}");
}
}
#[test]
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
for invalid in [
"../0.23.1-nightly.20261120.1.1.gabcdef012345",
"0.23.1-nightly.20261120.1.1.gabcdef012345/other",
"0.23.1-nightly.20261120.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
+70
View File
@@ -0,0 +1,70 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub const COMPILED: BuildFlavor = if cfg!(cadcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open CADCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable CADCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.23.1"), "0.23.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.23.1"), "0.23.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
+29
View File
@@ -71,6 +71,10 @@ impl Env {
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);
// The Nightly profile owns every data root before the first use (see [`apply_profile`]).
if Self::apply_profile(&mut vars, crate::launch_profile::current().root()) {
return vars;
}
// An explicit override (including blank, which disables settings) takes precedence.
if var(CONFIG_DIR).is_none()
&& let Some(exe) = exe_dir
@@ -87,6 +91,17 @@ impl Env {
vars
}
/// Point every data root this process resolves at the Nightly profile `root`: the settings folder
/// (logs, autosave and Drawing Recovery, workspace, plotters, LISP support, crash reports) and
/// eframe's own storage file, which would otherwise go to the stable user profile. `false` for a
/// stable launch, which then resolves its folders as before.
fn apply_profile(vars: &mut Env, root: Option<&std::path::Path>) -> bool {
let Some(root) = root else { return false };
vars.config_dir = Some(root.to_path_buf());
vars.portable_storage_file = Some(root.join("app.ron"));
true
}
/// [`Env::read`] with `var` looking a variable up.
pub(crate) fn from_vars(var: impl Fn(&str) -> Option<OsString>) -> Env {
let text = |k: &str| var(k).and_then(|v| v.into_string().ok()).filter(|v| !v.trim().is_empty());
@@ -124,6 +139,20 @@ mod tests {
use super::*;
use std::cell::RefCell;
/// The Nightly profile is the settings folder and eframe's storage file, before any portable
/// or platform resolution: no stable folder is read or written by a nightly launch.
#[test]
fn a_launch_profile_owns_the_settings_folder_and_the_eframe_storage_file() {
let profile = std::path::PathBuf::from("/nightly-data/profile");
let mut vars = Env::from_vars(|_| None);
// A stable launch keeps the platform resolution.
assert!(!Env::apply_profile(&mut vars, None));
assert!(!vars.portable_storage_file.as_ref().is_some_and(|f| f.ends_with("app.ron")));
assert!(Env::apply_profile(&mut vars, Some(&profile)));
assert_eq!(vars.config_dir, Some(profile.clone()));
assert_eq!(vars.portable_storage_file, Some(profile.join("app.ron")));
}
#[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()));
+211
View File
@@ -0,0 +1,211 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old portable/config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::portable::probe)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\cadcraft" } else { "/nightly-data/profiles/cadcraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["--new-window", "a.dxf"]), args(&["--", "--launch-profile", "file.dxf"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
}
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "drawing with spaces.dxf"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "drawing with spaces.dxf"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-window", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
] {
assert!(parse(argv).is_err());
}
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-window", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+203 -18
View File
@@ -16,16 +16,23 @@
#[cfg(any(target_os = "macos", test))]
mod apple_events;
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod control_server;
mod desktop_theme;
mod env;
#[cfg(any(target_os = "windows", test))]
mod graphics;
mod launch_args;
mod launch_profile;
mod logging;
#[cfg(target_os = "macos")]
mod native_menu;
mod nightly_session;
mod portable;
mod process_identity;
mod profile_root;
#[cfg(target_os = "macos")]
mod sheet;
mod single_instance;
@@ -34,6 +41,7 @@ mod system_animations;
mod workspace;
use cadcraft_engine::Session;
use cadcraft_ui_egui::os_window::{self, LaunchIdentity};
use cadcraft_ui_egui::switch::Switch;
use cadcraft_ui_egui::{CadApp, Pick, Services, i18n};
@@ -151,6 +159,11 @@ impl eframe::App for App {
self.persist_workspace(None);
self.cad.cancel_screenshots();
self.cad.shutdown_autosave();
// The host's last step, once: on macOS Cmd+Q ends the process here, after this, so the
// Nightly session record is finished by this hook and never by the code after `run_native`.
if let Some(at_exit) = self.cad.services.at_exit.take() {
at_exit();
}
}
/// Preferences (the interface theme) survive restarts; eframe saves the window state itself
/// (`persist_window`); egui state is not kept.
@@ -199,6 +212,8 @@ fn services() -> Services {
pick_pgp: Some(Box::new(|dir: Option<&str>| {
file_dialog(&Pick::Pgp(dir.unwrap_or_default().into())).pick_file().map(|p| p.to_string_lossy().to_string())
})),
// Set in `main` once the Nightly session record exists.
at_exit: None,
}
}
@@ -250,7 +265,8 @@ fn saved_window(app_ron: &str) -> bool {
/// 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 {
let Some(path) = portable_file.map(std::path::PathBuf::from).or_else(|| eframe::storage_dir(os_window::app_id()).map(|dir| dir.join("app.ron")))
else {
return false;
};
let Ok(mut ron) = std::fs::read_to_string(&path) else { return false };
@@ -287,14 +303,14 @@ const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("CADCraft")
.with_title(os_window::name_for(os_window::identity()))
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size(MIN_INNER_SIZE)
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false)
.with_app_id(APP_ID),
.with_app_id(os_window::app_id()),
// The size, position and maximized state are kept between sessions (#2595); eframe keeps a
// restored window on the monitors that are connected now.
persist_window: true,
@@ -311,8 +327,6 @@ fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
}
}
const APP_ID: &str = "ai.storyteller.cadcraft";
/// The key eframe saves the main window state under in its storage.
const WINDOW_KEY: &str = "window";
@@ -336,22 +350,118 @@ fn app_icon() -> Option<egui::IconData> {
eframe::icon_data::from_png_bytes(APP_ICON_PNG).map_err(|e| log::warn!("app icon: {e}")).ok()
}
/// The version this build reports: the prepared nightly identity, or the workspace version.
fn built_version() -> &'static str {
env!("CADCRAFT_BUILT_VERSION")
}
/// The stable line, exactly what clap prints for `--version`: `cadcraft <workspace version>`.
fn version_string() -> String {
format!("cadcraft {}", cadcraft_engine::build_version())
}
/// The Nightly identity line every nightly script checks: `<App> <version> (nightly-v1)`, with the
/// prepared nightly version embedded at build time. The app name never gains a "Nightly".
fn nightly_version_line() -> String {
format!("CADCraft {}", build_flavor::version(build_flavor::BuildFlavor::NightlyV1, built_version()))
}
/// The identity this build reports in its log: the Nightly line on that channel, stable's otherwise.
fn reported_version() -> String {
match build_flavor::COMPILED {
build_flavor::BuildFlavor::Stable => version_string(),
build_flavor::BuildFlavor::NightlyV1 => nightly_version_line(),
}
}
/// The reported line with the commit, for the log: a bug report's log names the build it came from.
fn log_version() -> String {
format!("{} ({})", reported_version(), option_env!("CADCRAFT_BUILD_SHA").unwrap_or("dev"))
}
/// Whether this start runs the isolated Nightly flavor.
fn is_nightly() -> bool {
launch_profile::current().is_nightly()
}
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1))
}
/// A refused launch profile ends with a native dialog on a desktop, and with the reason on standard
/// error everywhere else (a headless runner must never wait for a modal).
fn report_launch_profile_error(error: &str) {
eprintln!("CADCraft launch profile: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("CADCraft launch profile: {error}");
return;
}
let _ = rfd::MessageDialog::new()
.set_title(os_window::name_for(LaunchIdentity::NightlyV1))
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
/// Select the immutable launch profile before logging, updates, fonts or saved state, and answer
/// the version query before any of that: `None` means the query has been answered and the process
/// should return success without opening a window.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, logging, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
{
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "{}", nightly_version_line());
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| {
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
})
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable };
if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
}
/// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe.
fn main() -> eframe::Result {
// A copy of this program started to read or write a DWG file does only that.
// A copy of this program started to read or write a DWG file does only that. It is started
// with `--dwg-worker` alone, so it is answered before the launch profile is required.
if let Some(code) = cadcraft_io::dwg_worker::serve_if_asked() {
std::process::exit(code);
}
let Some(arguments) = prepare_launch() else { return Ok(()) };
cadcraft_io::dwg_worker::use_own_worker();
// First, so every start-up record is captured; see `logging`.
let logger = logging::install();
// The update helper relaunches this binary after a self-update; it runs and exits here.
// The update helper relaunches this binary after a self-update; it runs and exits here. A
// nightly build is updated by the Launcher only, so it never finishes a stable helper.
#[cfg(not(target_arch = "wasm32"))]
if let Some(done) = craft_update::self_update::finish(&cadcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
if !is_nightly()
&& let Some(done) = craft_update::self_update::finish(&cadcraft_ui_egui::UPDATE_APP, &arguments)
{
if let Err(e) = done {
eprintln!("CADCraft update helper failed: {e}");
std::process::exit(1);
@@ -361,14 +471,25 @@ fn main() -> eframe::Result {
// `--help` and `--version` print to standard output and exit 0. A usage error (an unknown or
// repeated flag, a missing or bad value, a bad CADCRAFT_CONTROL_PORT) names the argument on
// standard error and exits 2 before the window opens.
let launch = launch_args::parse(launch_args::command(), std::env::args_os().skip(1)).unwrap_or_else(|e| e.exit());
let launch = launch_args::parse(launch_args::command(), arguments).unwrap_or_else(|e| e.exit());
let vars = env::Env::read();
let (control_port, sample, files) = (launch.control, launch.sample, launch.files);
// A nightly launch accepts no control server: the inherited CADCRAFT_CONTROL_PORT and the
// Launcher's agent link belong to the stable app, and a second unauthenticated surface over
// the nightly profile is not part of the protocol.
let control_port = if is_nightly() {
if control_port.is_some() {
eprintln!("CADCraft Nightly: the control server is off in this channel; the option is ignored");
}
None
} else {
control_port
};
// The log file lives under the settings directory; opened after the arguments, so `--version`
// leaves no file behind. Records logged until now are written to it first.
if let Some(logger) = logger {
match vars.config_dir.as_ref().map(|d| logger.attach_dir(&d.join(logging::LOG_DIR))) {
Some(Ok(path)) => log::info!("{} ({} {}), log file {}", version_string(), std::env::consts::OS, std::env::consts::ARCH, path.display()),
Some(Ok(path)) => log::info!("{} ({} {}), log file {}", log_version(), std::env::consts::OS, std::env::consts::ARCH, path.display()),
Some(Err(e)) => log::warn!("no log file: {e}"),
None => {
logger.stderr_only();
@@ -379,13 +500,32 @@ fn main() -> eframe::Result {
// A launch that only names files hands them to the CADCraft already running and exits.
let handed = single_instance::absolute(&files);
let may_hand_off = handed.is_some() && !launch.new_window && !files.is_empty() && control_port.is_none() && !sample;
let instance = match single_instance::claim(handed.as_deref().unwrap_or_default(), may_hand_off) {
let instance = match single_instance::claim(handed.as_deref().unwrap_or_default(), may_hand_off, launch_profile::current().root()) {
single_instance::Claim::HandedOff => return Ok(()),
single_instance::Claim::Primary(server) => Some(server),
single_instance::Claim::Alone => None,
};
install_io();
cadcraft_engine::settings_dir::set(vars.config_dir.clone());
// Nightly session health: the owner's lease and unclean-exit record live in the profile, and the
// record is finished on the way out (on macOS in `on_exit`, see `nightly_session`).
let (nightly_watch, previous_unclean) =
match nightly_session::Session::begin_with_health(launch_profile::current().root(), built_version(), option_env!("CADCRAFT_BUILD_SHA")) {
Ok((watch, unavailable)) => {
if unavailable {
log::warn!("another CADCraft Nightly holds this profile's session lease; this window keeps no health record");
}
let unclean = watch.as_ref().is_some_and(nightly_session::Session::previous_unclean);
(std::sync::Arc::new(std::sync::Mutex::new(watch)), unclean)
}
Err(error) => {
log::warn!("Nightly session state: {error}");
(std::sync::Arc::new(std::sync::Mutex::new(None)), false)
}
};
if previous_unclean {
log::warn!("the previous CADCraft Nightly ended without finishing its session record");
}
if let Some(dir) = &vars.config_dir {
cadcraft_ui_egui::fault::install_report_hook(dir.join(cadcraft_ui_egui::fault::REPORT_DIR));
}
@@ -402,12 +542,16 @@ fn main() -> eframe::Result {
if stencil == 0 {
log::warn!("CADCRAFT_STENCIL is off: the window has no stencil buffer; clipped layout viewports draw unclipped");
}
let persistence_path = vars
.portable_storage_file
.clone()
.or_else(|| std::env::var_os("CADCRAFT_CONFIG_DIR").and_then(|_| vars.config_dir.as_ref().map(|d| d.join("app.ron"))));
let mut options = eframe::NativeOptions {
// 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),
persistence_path: vars.portable_storage_file.clone(),
..window_options(restores_window(vars.portable_storage_file.as_deref()), stencil)
persistence_path: persistence_path.clone(),
..window_options(restores_window(persistence_path.as_deref()), stencil)
};
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
@@ -452,11 +596,19 @@ fn main() -> eframe::Result {
let apple_events = apple_events::AppleEvents::install();
#[cfg(target_os = "macos")]
let apple_events = &apple_events;
eframe::run_native(
"CADCraft",
// The exit hook's own handle: the app creator is a `move` closure, so the watch is cloned before it.
let exit_watch = std::sync::Arc::clone(&nightly_watch);
let result = eframe::run_native(
os_window::name_for(os_window::identity()),
options,
Box::new(move |cc| {
let mut app = CadApp::new(Session::empty(), services());
// The exit hook runs in `on_exit`: macOS ends the process inside AppKit's terminate after
// it, so nothing after `run_native` can be relied on there.
app.services.at_exit = Some(Box::new(move || nightly_session::finish_once(&exit_watch, previous_unclean)));
if previous_unclean {
app.set_status("CADCraft Nightly ended unexpectedly last time; your drawings were recovered where autosave had them.");
}
// File dialogs are sheets on macOS: a modal loop inside the event handler crashes the
// app when the dialog is resized (#1527).
#[cfg(target_os = "macos")]
@@ -468,6 +620,17 @@ fn main() -> eframe::Result {
app.ui = ui;
}
app.set_system_cursor_default(vars.system_cursor == Switch::On);
// Native Wayland answers a clipboard request asynchronously; every other backend in the
// next frame (egui-winit).
#[cfg(all(unix, not(target_os = "macos")))]
{
use eframe::egui_wgpu::wgpu::rwh::{HasDisplayHandle, RawDisplayHandle};
if let Ok(display) = cc.display_handle() {
app.set_clipboard_late_answers(matches!(display.as_raw(), RawDisplayHandle::Wayland(_)));
}
}
#[cfg(any(not(unix), target_os = "macos"))]
app.set_clipboard_late_answers(false);
// macOS: CADCRAFT_NO_NATIVE_MENU=1 keeps the menus inside the window.
#[cfg(target_os = "macos")]
app.set_native_menus(vars.no_native_menu != Switch::On);
@@ -489,7 +652,10 @@ fn main() -> eframe::Result {
// Autosave files (SAVEFILEPATH) default to `<settings dir>/autosave`.
if let Some(dir) = &vars.config_dir {
app.enable_autosave(&dir.join("autosave"));
app.enable_update_check();
// A nightly build is updated by the Launcher, never by the app's own update check.
if !is_nightly() {
app.enable_update_check();
}
// Startup LISP (acad.lsp, acaddoc.lsp) is read from `<settings>/support`; the
// folder is made so it is there to put them in.
let support = dir.join("support");
@@ -554,12 +720,20 @@ fn main() -> eframe::Result {
apple_events,
}))
}),
)
);
// The controlled return path: a start that created no window still finishes its record. On macOS
// a quit never reaches here, and the exit hook above has done it. No window ran, so no notice was
// shown: pass false and an unclean record survives for the next launch to report.
nightly_session::finish_once(&nightly_watch, false);
result
}
#[cfg(test)]
mod tests {
use super::{STENCIL_BITS, filters_for_save, follow_desktop, saved_window, stencil_bits, window_options, without_tiny_window};
use super::{
STENCIL_BITS, filters_for_save, follow_desktop, nightly_version_line, saved_window, stencil_bits, version_string, window_options,
without_tiny_window,
};
#[test]
fn save_dialog_offers_dwg_with_the_drawing_format_first() {
@@ -642,6 +816,17 @@ mod tests {
assert_eq!(without_tiny_window("not ron"), None);
}
/// The two identity lines. Nightly prints the kit's `<App> <version> (nightly-v1)` -- the app
/// name never gains a "Nightly" -- while stable keeps exactly the line clap prints, which
/// `launch_args` asserts against its own `-V` output.
#[test]
fn the_version_lines_name_the_app_and_its_channel() {
let nightly = nightly_version_line();
assert_eq!(nightly, format!("CADCraft {} (nightly-v1)", super::built_version()));
assert!(!nightly.contains("Nightly "), "the version line must not rename the app: {nightly}");
assert_eq!(version_string(), format!("cadcraft {}", cadcraft_engine::build_version()));
}
/// View ▸ Theme ▸ System on Linux: winit reports no theme, so the desktop's answer stands in;
/// without one (or where winit answers and the desktop doesn't) the input is left alone.
#[test]
+2 -1
View File
@@ -148,7 +148,8 @@ impl NativeMenu {
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());
let en = (typing && menus::edits_text(cmd))
|| cadcraft_engine::find_command(cmd).is_none_or(|c| cadcraft_ui_egui::clipboard::offered(&app.session, c));
item.set_enabled(en);
}
}
+287
View File
@@ -0,0 +1,287 @@
//! App-private Nightly session health, not telemetry or a Launcher protocol.
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Write as _};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop.
/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and
/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path
/// still runs for a start that created no window.
pub type Shared = Arc<Mutex<Option<Session>>>;
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(unclean_notice_shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
/// Replace `path` with `bytes` without ever writing through a symbolic link at the destination.
///
/// The engine's [`cadcraft_engine::atomic_write`] resolves a destination link so that its target is
/// replaced; a profile entry is not ours to redirect, so here a link at the destination is refused,
/// and the bytes are written to a fresh temporary in the same folder (created exclusively, so a
/// planted temporary cannot be followed either) before it is renamed over the destination.
fn write_atomic_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if !metadata.file_type().is_file() => {
return Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory"));
}
Ok(_) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
let dir = path.parent().unwrap_or_else(|| Path::new("."));
for attempt in 0..32_u32 {
let temporary = dir.join(format!(".{}.{}-{attempt}.tmp", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id()));
let mut file = match OpenOptions::new().write(true).create_new(true).open(&temporary) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
};
let written = file.write_all(bytes).and_then(|()| file.sync_all());
drop(file);
if let Err(error) = written {
let _ = std::fs::remove_file(&temporary);
return Err(error);
}
return match std::fs::rename(&temporary, path) {
Ok(()) => Ok(()),
Err(error) => {
let _ = std::fs::remove_file(&temporary);
Err(error)
}
};
}
Err(io::Error::other("no free temporary name for the Nightly session state"))
}
impl Session {
/// The warning belongs to this window: a busy secondary has no health-record coverage,
/// while Stable and a lease-owning Nightly window preserve their existing result.
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version, commit)?;
let unavailable = root.is_some() && watch.is_none();
Ok((watch, unavailable))
}
/// `None` is stable or another owner of this profile. Neither case touches the record.
/// The supplied root must already be the validated private Nightly profile.
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit.filter(|value| !value.is_empty()),
}))?;
// A raced destination link is refused, not followed ([`write_atomic_no_follow`]).
write_atomic_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
}
pub fn previous_unclean(&self) -> bool {
self.previous_unclean
}
/// Controlled return. If an earlier session's interruption was detected but no window showed
/// it yet (a renderer failure before the app callback, including the CPU-retry handoff), the
/// record is left for the next owner to report; otherwise this is [`Self::complete`].
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// Controlled event-loop completion includes a handled startup error/CPU handoff, not only
/// exit0. Clear before releasing primary IPC so a successor cannot miss record ownership.
/// An unwind, abort, forced exit or killed process never calls this method.
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
}
std::fs::remove_file(&self.path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
loop {
let path =
std::env::temp_dir().join(format!("cadcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
}
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
#[test]
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
let fixture = Fixture::new();
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
assert!(stable.is_none() && !warning);
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
assert!(!warning);
let first = first.unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
assert!(!first.previous_unclean());
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
assert!(!unfinished.previous_unclean());
drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
let fixture = Fixture::new();
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
// Renderer initialization failed before the app callback: no notice was shown.
let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
// The CPU retry (or the next start) still sees the interruption and shows it.
let retry = Session::begin(Some(&fixture.0), "cpu-retry", None).unwrap().unwrap();
assert!(retry.previous_unclean());
retry.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
// Without an earlier interruption, a handled failure still clears normally.
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
assert!(!clean.previous_unclean());
clean.finish(false).unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
let fixture = Fixture::new();
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
// The exit hook (macOS quit: the only path that runs there).
finish_once(&shared, false);
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
assert!(!successor.previous_unclean());
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
finish_once(&shared, false);
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
successor.complete().unwrap();
}
#[test]
fn cleanup_never_removes_an_unknown_changed_record() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
assert!(watch.complete().is_err());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
}
#[test]
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
assert!(data["commit"].is_null(), "missing provenance must not be invented");
watch.complete().unwrap();
}
#[test]
#[cfg(unix)]
fn reserved_state_aliases_do_not_modify_external_files() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in [LEASE, RECORD] {
let alias = fixture.0.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
}
+28 -10
View File
@@ -3,21 +3,39 @@
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.
/// The marker file a portable copy ships beside `cadcraft.exe`.
pub(crate) const PORTABLE_MARKER: &str = "portable.txt";
/// The settings folder a portable copy keeps beside the executable.
pub(crate) const PORTABLE_DATA_DIR: &str = "CADCraftData";
/// The marker path, when `dir` holds a marker file (not a directory of that name).
pub(crate) fn portable_marker(dir: &Path) -> Option<PathBuf> {
let marker = dir.join(PORTABLE_MARKER);
marker.is_file().then_some(marker)
}
/// Prove `dir` is writable with the one exclusive probe this app uses: a fresh file holding a byte
/// (a full drive can still create an empty file and refuse its data) and its flush, removed again.
/// The nightly profile check and the portable check share it, so both test the same thing.
pub(crate) fn probe(dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let probe = dir.join(format!(".portable-write-test-{}", std::process::id()));
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?;
removed
}
/// 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 portable_marker(exe_dir).is_none() {
return Ok(None);
}
let data = exe_dir.join(PORTABLE_DATA_DIR);
probe(&data)?;
Ok(Some(data))
}
+70
View File
@@ -0,0 +1,70 @@
//! Set the immutable nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
use std::sync::OnceLock;
#[derive(Clone, Debug, thiserror::Error)]
pub enum IdentityError {
#[error("{0}")]
Configuration(String),
}
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
configure(nightly && cfg!(windows), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(windows)]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".into());
}
Ok(())
}
#[cfg(not(windows))]
{
let _ = id;
Ok(())
}
})
.clone()
})
.map_err(IdentityError::Configuration)
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
}
+607
View File
@@ -0,0 +1,607 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
use std::ffi::OsString;
use crate::portable::{PORTABLE_DATA_DIR, portable_marker};
use std::path::{Component, Path, PathBuf};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
// CADCraft also builds for the BSDs (packaging/freebsd): nightly-v1 is Windows, macOS and
// Linux only, as the shared nightlies publish.
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
// A component that is not valid UTF-8 keeps its exact bytes: a lossy comparison would fold two
// different names into the same replacement character and call them one folder.
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str();
match (platform.ignores_case(), value.to_str()) {
(true, Some(text)) => OsString::from(text.to_lowercase()),
_ => value.to_os_string(),
}
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
/// Every stable CADCraft data root of this platform, plus the install folders and the running
/// install ([`installation_boundary`]).
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("CADCraft")))
.collect::<Result<Vec<_>, _>>()?;
// Stable's eframe storage folder (`eframe::storage_dir`: `app.ron` under
// `%APPDATA%\ai.storyteller.cadcraft\data`), outside the roaming `CADCraft` folder.
roots.push(required_base(env, "APPDATA")?.join(EFRAME_APP_ID));
// The MSI's per-machine folder (cadcraft.wxs). A custom install folder is not known
// here; the executable's own folder is fenced below.
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("CADCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("cadcraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.extend(["/usr/bin/cadcraft", "/usr/local/bin/cadcraft", "/opt/cadcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.cadcraft"));
// Stable's eframe storage folder (`eframe::storage_dir`: window state, Options profile,
// UI and autosave prefs in `app.ron`), which is not the XDG settings folder above.
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(EFRAME_APP_ID));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/CADCraft"),
library.join("Caches/CADCraft"),
library.join("Caches/ai.storyteller.cadcraft"),
// Stable's eframe storage folder (`eframe::storage_dir`: `app.ron` in Application
// Support), beside the settings folder env.rs uses.
library.join("Application Support").join(EFRAME_APP_ID),
library.join("Preferences/CADCraft"),
library.join("Preferences/ai.storyteller.cadcraft.plist"),
library.join("Saved Application State/ai.storyteller.cadcraft.savedState"),
home.join("Applications/CADCraft.app"),
PathBuf::from("/Applications/CADCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
// A regular file in a folder's place is not a folder: the readers and sweepers that follow would
// fail halfway, so refuse it while the profile is still being validated.
match std::fs::symlink_metadata(&child) {
Ok(metadata) if !metadata.file_type().is_dir() => {
return Err(format!("the nightly {label} must be a directory, not a file or an alias"));
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
}
Ok(child)
}
/// Every existing entry directly in the profile (logs, settings and so on) must resolve inside it,
/// so a link there cannot point Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
Ok(())
}
/// Recognise the shared portable data namespace in both the supplied and resolved path.
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
// A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a
// marker only counts beside a CADCraft executable, so an unrelated portable.txt higher up
// (in a user folder or at a drive root) does not refuse the profile.
path.ancestors().enumerate().any(|(depth, ancestor)| {
portable_marker(ancestor).is_some() && (depth == 0 || ["cadcraft.exe", "cadcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
}) || path.components().any(|component| match component {
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
Component::Normal(name) => name == PORTABLE_DATA_DIR,
_ => false,
})
}
/// The writable hook is the app's existing exclusive probe (`portable::probe`). Keeping it injected
/// lets filesystem boundary tests exercise the real policy without starting the app or changing
/// global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
let chosen = canonical_future(root)?;
// The deb/rpm CLI wrapper exports CADCRAFT_CONFIG_DIR at the folder this launch already owns (the
// GUI wrappers name the profile through `--profile-root` instead), so that value is inert:
// `env::apply_profile` sets the settings folder from the profile, not from the variable. Any
// other value would redirect Nightly's settings folder, so it is refused.
if let Some(configured) = env("CADCRAFT_CONFIG_DIR").filter(|v| !v.is_empty()) {
let configured = canonical_future(&absolute(PathBuf::from(configured), "CADCRAFT_CONFIG_DIR")?)?;
if !configured.starts_with(&chosen) {
return Err("nightly-v1 cannot be combined with CADCRAFT_CONFIG_DIR outside its own profile".into());
}
}
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
{
// A Flatpak's data folder and runtime socket namespace belong to its app id. The nightly
// bundle has an id of its own ([`NIGHTLY_FLATPAK_ID`], named by
// `packaging/linux/flatpak-bundle.sh`), so its profile is already the sandbox's own; any
// other instance is the stable app's (or another app's), whose socket this profile must
// not inherit.
if id.to_string_lossy() != NIGHTLY_FLATPAK_ID {
return Err("nightly-v1 cannot inherit another Flatpak app's instance; launch through the native Launcher".into());
}
}
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
return Err("the nightly root must not use a portable CADCraft installation or its CADCraftData settings folder".into());
}
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
entries_stay_inside(&chosen)?;
// Drawing Recovery reads, adopts, overwrites and sweeps entries. Never let its alias leave this
// private profile, including toward a stable portable directory not in our known roots.
private_subdirectory(&chosen, AUTOSAVE, "recovery folder")?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
private_subdirectory(&confirmed, AUTOSAVE, "recovery folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
/// The app id of the nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`): the one Flatpak
/// instance whose sandbox is this channel's own. The window identity ([`crate::os_window`]) and the
/// bundle id differ on purpose, as they do for stable.
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.cadcraft.nightly";
/// The app id eframe derives stable's storage folder from ([`crate::main`]'s `persistence_path`).
/// A profile that sits there would overwrite stable's `app.ron`, so its folder is fenced too.
const EFRAME_APP_ID: &str = "ai.storyteller.cadcraft";
/// The subfolder autosave and Drawing Recovery write ([`crate::main`], `<settings>/autosave`).
pub const AUTOSAVE: &str = "autosave";
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("cadcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/cadcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
|dir| {
let probe = dir.join("exclusive-test-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
},
)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
}
impl Drop for Fixture {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
fn portable_settings_from_another_install_are_refused_before_any_probe() {
let fixture = Fixture::new();
let stable_install = fixture.root.join("stable portable install");
let stable_data = stable_install.join(PORTABLE_DATA_DIR);
std::fs::create_dir_all(&stable_data).unwrap();
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "a different portable install is not a private Nightly profile");
assert!(!probed.get(), "reject portable data before a writable probe");
assert!(!stable_data.join("nested nightly").exists());
assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change");
assert_eq!(std::fs::read_dir(&stable_data).unwrap().count(), 1);
}
}
let private = fixture.root.join("CADCraftData-backup-name/nightly");
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component");
}
#[cfg(unix)]
#[test]
fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
let fixture = Fixture::new();
let stable = fixture.home().join(".local/state/cadcraft/autosave");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join(AUTOSAVE)).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "autosave must not escape the private profile or follow a dangling alias");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-self");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&private, private.join(AUTOSAVE)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_err(), "autosave cannot treat all profile settings as recovery entries");
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let recovery = private.join("private-recovery");
std::fs::create_dir_all(&recovery).unwrap();
std::os::unix::fs::symlink(&recovery, private.join(AUTOSAVE)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
assert_eq!(std::fs::canonicalize(private.join(AUTOSAVE)).unwrap(), recovery);
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/cadcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join(AUTOSAVE), platform));
assert!(overlaps(&root.join(AUTOSAVE), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("cadcraft-other"), platform));
}
}
#[test]
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("cadcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
// Stable's eframe storage folder holds `app.ron`, so a profile may not sit at or inside it.
let storage = data.join(EFRAME_APP_ID);
std::fs::create_dir_all(&storage).unwrap();
std::fs::write(storage.join("app.ron"), b"stable window state").unwrap();
for candidate in [storage.clone(), storage.join("nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"), "{}", candidate.display());
}
assert_eq!(std::fs::read(storage.join("app.ron")).unwrap(), b"stable window state");
let nightly = data.join("ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/CADCraft Nightly.app/Contents/MacOS/CADCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/CADCraft",
"Application Support/ai.storyteller.cadcraft",
"Caches/CADCraft",
"Caches/ai.storyteller.cadcraft",
"Preferences/CADCraft",
"Saved Application State/ai.storyteller.cadcraft.savedState",
] {
let stable = library.join(suffix);
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
// The bundle path and the Library fences fold case on macOS.
let cased = library.join("application support/cadcraft/nightly");
assert!(fixture.check(Platform::Mac, &cased).is_err());
}
#[test]
fn windows_fences_roaming_local_and_both_install_folders() {
let mut fixture = Fixture::new();
fixture.env.insert("ProgramFiles".into(), fixture.root.join("program files").into_os_string());
for stable in [
fixture.root.join("roaming/CADCraft"),
fixture.root.join("roaming/ai.storyteller.cadcraft"),
fixture.root.join("local/CADCraft"),
fixture.root.join("program files/ArtCraft/CADCraft"),
] {
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly")] {
assert!(fixture.check(Platform::Windows, &candidate).unwrap_err().contains("overlap"), "{}", candidate.display());
}
// Windows folder names ignore case.
assert!(fixture.check(Platform::Windows, &stable.with_file_name("cadcraft")).is_err());
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let valid = fixture.root.join("local/ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Windows, &valid).unwrap(), valid);
}
#[test]
fn config_dir_and_flatpak_are_refused() {
let mut fixture = Fixture::new();
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), fixture.root.join("custom").into_os_string());
let private = fixture.root.join("nightly-config");
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("CADCRAFT_CONFIG_DIR"));
assert!(!private.exists());
fixture.env.remove("CADCRAFT_CONFIG_DIR");
for inherited in ["ai.storyteller.cadcraft", "org.freedesktop.other"] {
fixture.env.insert("FLATPAK_ID".into(), inherited.into());
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("Flatpak"), "{inherited}");
assert!(!private.exists());
}
}
/// The nightly bundle runs under an app id of its own, so its sandbox data folder is this
/// channel's data root; that one instance is accepted, and its profile stays inside it.
#[test]
fn the_nightly_flatpaks_own_instance_accepts_its_own_profile() {
let mut fixture = Fixture::new();
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
let private = fixture.home().join(".var/app/ai.storyteller.cadcraft.nightly/data/cadcraft-nightly");
assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private);
// Stable's Flatpak folder is still fenced even inside the nightly instance.
let stable = fixture.home().join(".var/app/ai.storyteller.cadcraft");
assert!(fixture.check(Platform::Linux, &stable).unwrap_err().contains("overlap"));
}
/// A Linux Launcher wrapper exports `CADCRAFT_CONFIG_DIR` at the profile it launches; that is
/// the folder this launch already owns, so it must not refuse the profile. Anything else is
/// still a redirect.
#[test]
fn a_wrapper_naming_the_profile_in_config_dir_is_accepted() {
let mut fixture = Fixture::new();
let private = fixture.root.join("nightly-wrapper");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), private.clone().into_os_string());
assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private);
let inside = private.join("nested");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), inside.clone().into_os_string());
assert!(fixture.check(Platform::Linux, &inside).is_ok(), "a folder inside the profile is the profile's own");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), fixture.root.join("elsewhere").into_os_string());
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("CADCRAFT_CONFIG_DIR"));
}
#[test]
fn a_profile_that_cannot_be_written_is_refused_without_a_stable_fallback() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-unwritable");
let result = validate_for(Platform::Linux, &private, |key| fixture.get(key), Some(&fixture.exe), |_| Err(std::io::Error::other("read-only")));
assert!(result.unwrap_err().contains("not writable"));
assert!(private.exists(), "the profile was created before the probe, and nothing was written into stable");
assert!(!fixture.home().join(".config/cadcraft").exists());
}
#[cfg(unix)]
#[test]
fn a_dangling_entry_inside_the_profile_is_refused_before_writes() {
let fixture = Fixture::new();
let outside = fixture.root.join("outside");
std::fs::create_dir_all(&outside).unwrap();
let private = fixture.root.join("nightly-dangling");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(outside.join("missing"), private.join("logs")).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err());
assert!(!probed.get());
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
}
}
+10 -5
View File
@@ -100,25 +100,30 @@ pub fn absolute(paths: &[PathBuf]) -> Option<Vec<String>> {
/// Decide what this launch does. `files` are absolute ([`absolute`]); `may_hand_off` is false
/// when the launch asked for anything besides opening files, so it gets its own window.
pub fn claim(files: &[String], may_hand_off: bool) -> Claim {
/// `profile` is the Nightly profile root: its socket then lives in the profile, so a nightly launch
/// can never hand its files to a running stable CADCraft (and the reverse).
pub fn claim(files: &[String], may_hand_off: bool, profile: Option<&std::path::Path>) -> Claim {
#[cfg(windows)]
{
match socket_path() {
match socket_path(profile) {
Some(path) => claim_at(&path, files, may_hand_off),
None => Claim::Alone,
}
}
#[cfg(not(windows))]
{
let _ = (files, may_hand_off);
let _ = (files, may_hand_off, profile);
Claim::Alone
}
}
/// The socket in `%LOCALAPPDATA%\CADCraft`.
/// The socket in `%LOCALAPPDATA%\CADCraft`, or `<profile>\single-instance` for a Nightly launch.
#[cfg(windows)]
fn socket_path() -> Option<std::path::PathBuf> {
fn socket_path(profile: Option<&std::path::Path>) -> Option<std::path::PathBuf> {
let name = socket_name(std::env::var("SESSIONNAME").ok().as_deref());
if let Some(root) = profile {
return Some(root.join("single-instance").join(name));
}
std::env::var_os("LOCALAPPDATA").filter(|v| !v.is_empty()).map(|d| std::path::PathBuf::from(d).join("CADCraft").join(name))
}
+28
View File
@@ -0,0 +1,28 @@
# App icons
The stable icon is `cadcraft-1024.png` (the padded master). The packaging scripts derive the other
sizes from it:
| File | Where it goes |
|---|---|
| `cadcraft.ico` | `cadcraft.exe` resources and the MSI shortcuts (Windows) |
| `cadcraft.icns` | `CADCraft.app/Contents/Resources` (macOS) |
| `cadcraft-256.png` | the window and About icon on Linux, and the AppImage/menu entry |
| `hicolor/<size>/apps/ai.storyteller.cadcraft.png` | the freedesktop icon theme, so docks and menus find the app by its id |
## Nightly
The Nightly channel has its own icon, so a nightly window, taskbar button and bundle are not
mistaken for the stable app. It is the same mark — foreground unchanged, no badge — on a deeper
background, derived from the stable 1024 master (never an upscale):
| File | Where it goes |
|---|---|
| `cadcraft-nightly-1024.png` | the master the `.icns` is generated from |
| `cadcraft-nightly.png` | the Linux nightly tar (`cadcraft-nightly.png` beside the executable) |
| `cadcraft-nightly.ico` | `cadcraft.exe` of a nightly build (`build.rs`) |
| `cadcraft-nightly.icns` | `CADCraft Nightly.app/Contents/Resources`, `CFBundleIconFile cadcraft-nightly` |
`nightly-provenance.json` records the exact transform (which pixels changed, and from which
colour), so the nightly icon can be regenerated or reviewed against the stable one. Regenerating
either set is a deliberate change: check the result at 16 px before replacing a file.
Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

+24
View File
@@ -0,0 +1,24 @@
{
"schema": "craft-nightly-icon-provenance/v1",
"app": "cadcraft",
"channel": "nightly-v1",
"source": {
"master": "assets/app-icon/cadcraft-1024.png",
"note": "The stable 1024 master, padded as its designer made it; the nightly files are derived from it, never upscaled from a smaller icon."
},
"transform": {
"summary": "The app mark (near-black strokes, cream highlights and their antialiasing) is copied unchanged; only the background square is deepened.",
"background": {
"from": "#14a3c7",
"to": "#0c657b",
"rule": "A pixel whose channel distance from the stable background is at most 180 is scaled by 0.62; fully transparent pixels and every other colour are left as they were."
}
},
"outputs": {
"cadcraft-nightly.png": "256 px PNG of the icon the Linux tar carries as cadcraft-nightly.png",
"cadcraft-nightly-1024.png": "the padded 1024 master the icns is generated from",
"cadcraft-nightly.ico": "16, 24, 32, 48, 64, 128 and 256 px PNG entries, the Windows executable and window icon",
"cadcraft-nightly.icns": "icp4 icp5 icp6 ic07 ic08 ic09 ic10 PNG entries for the macOS bundle (CFBundleIconFile cadcraft-nightly)"
},
"not_done_here": "No badge, crescent or N was added, and the stable cadcraft.png/.ico/.icns files are untouched."
}
+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");
}
}
+5 -3
View File
@@ -271,8 +271,10 @@ impl EntityKind {
EntityKind::Image(i) => vec![Prim::Point(i.insert.xy())],
EntityKind::Table(t) => vec![Prim::Point(t.insert.xy())],
EntityKind::Tolerance(t) => vec![Prim::Point(t.insert.xy())],
// What its proxy graphics draw, so a proxy can be picked and snapped to.
EntityKind::Unknown(u) => u.graphics.iter().flat_map(|g| g.kind.prims()).collect(),
// What its proxy graphics draw, so a proxy can be picked and snapped to. A filled
// shape's hatch is left out: its outline is drawn too, and the hatch's sides (72 for an
// ellipse) would offer snaps inside it.
EntityKind::Unknown(u) => u.graphics.iter().filter(|g| !matches!(g.kind, EntityKind::Hatch(_))).flat_map(|g| g.kind.prims()).collect(),
}
}
@@ -625,7 +627,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())
+754 -60
View File
@@ -9,7 +9,8 @@
//! until a chunk sets them. Chunks CADCraft doesn't decode (meshes, shells, lightweight
//! polylines, materials) are skipped.
use super::{Arc, Circle, Common, Entity, EntityKind, Handle, Hatch, HatchLoop, Line, Lineweight, LwPolyline, Text, Unknown};
use super::{Arc, Circle, Common, Ellipse, Entity, EntityKind, Handle, Hatch, HatchLoop, Line, Lineweight, LwPolyline, Text, Unknown};
use crate::RawTag;
use cadcraft_color::{Color, Rgb};
use cadcraft_geom::{PolyVertex, Vec2, Vec3};
@@ -35,16 +36,20 @@ pub struct ProxyTables {
}
impl Unknown {
/// The proxy graphics bytes of an ACAD_PROXY_ENTITY: the 310 groups after its size group
/// (92, or 160 in newer files), cut to that size. Empty for other records, for an entity
/// without graphics and for one whose data isn't hex.
/// The proxy graphics bytes of an entity: the 310 groups after its size group (92, or 160 in
/// newer files), cut to that size. An ACAD_PROXY_ENTITY holds them in its proxy data: the size
/// group is the first after the `AcDbProxyEntity` subclass marker (from the start in a record
/// without one), so a 92 or 160 among the entity's own groups before it isn't taken for it.
/// An entity of another type CADCraft keeps as read holds them in its `AcDbEntity` part when
/// it was saved with a picture of itself (a LARGE_RADIAL_DIMENSION or an ARC_DIMENSION, or an
/// object of another application; #3438). Empty for an entity without graphics and for one
/// whose data isn't hex.
pub fn proxy_graphics_bytes(&self) -> Vec<u8> {
if !self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") {
return Vec::new();
}
let Some(at) = self.tags.iter().position(|t| t.code == 92 || t.code == 160) else { return Vec::new() };
let size = self.tags.get(at).and_then(|t| t.value.trim().parse::<usize>().ok()).unwrap_or(0).min(MAX_BYTES);
let mut out = Vec::with_capacity(size);
let Some((at, size)) = self.graphics_size_group() else { return Vec::new() };
// Reserve what the 310 groups hold, not what the size claims: a size far past the data
// would otherwise reserve up to MAX_BYTES for nothing.
let held: usize = self.tags.iter().skip(at + 1).take_while(|t| t.code == 310).map(|t| t.value.trim().len() / 2).sum();
let mut out = Vec::with_capacity(size.min(held));
for t in self.tags.iter().skip(at + 1).take_while(|t| t.code == 310) {
// Damaged data draws nothing rather than a picture cut at a guess.
if !push_hex(&mut out, &t.value) {
@@ -59,6 +64,232 @@ impl Unknown {
}
}
impl Unknown {
/// The `*D` block a dimension CADCraft keeps as read names (group 2 of its `AcDbDimension`
/// part): a LARGE_RADIAL_DIMENSION or an ARC_DIMENSION. AutoCAD draws a dimension from that
/// block, so CADCraft draws it from there too, and saving keeps it (#3438, #1161). `None`
/// for other records.
pub fn dimension_block(&self) -> Option<&str> {
let m = self.tags.iter().position(|t| t.code == 100 && t.value.trim() == "AcDbDimension")?;
self.tags[m + 1..].iter().take_while(|t| t.code != 100).find(|t| t.code == 2).map(|t| t.value.trim()).filter(|n| !n.is_empty())
}
/// Where the proxy graphics size group (92, or 160 in newer files) is, and the size it gives
/// (at most [`MAX_BYTES`]): in an ACAD_PROXY_ENTITY the first after the `AcDbProxyEntity`
/// marker, in another kept entity the one in its `AcDbEntity` part.
fn graphics_size_group(&self) -> Option<(usize, usize)> {
let at = if self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") {
let from = self.tags.iter().position(|t| t.code == 100 && t.value.trim() == "AcDbProxyEntity").map_or(0, |m| m + 1);
self.tags.iter().skip(from).position(|t| t.code == 92 || t.code == 160).map(|i| from + i)
} else {
// The groups of the AcDbEntity subclass, up to the entity's own subclass marker.
self.tags.iter().position(|t| t.code == 100 && t.value.trim() == "AcDbEntity").and_then(|m| {
let own = &self.tags[m + 1..];
own.iter().take_while(|t| t.code != 100).position(|t| t.code == 92 || t.code == 160).map(|i| m + 1 + i)
})
}?;
let size = self.tags.get(at).and_then(|t| t.value.trim().parse::<usize>().ok()).unwrap_or(0).min(MAX_BYTES);
Some((at, size))
}
/// The record's groups with the layer indices of its proxy graphics (ATTRIBUTE_LAYER) turned
/// into the written LAYER table `written`, by name; everything else as read. The name of an
/// index is the one the record's own decoded graphics draw on after it (so a proxy copied from
/// another drawing, or one whose layer was renamed, keeps the layer it shows); an index no
/// drawn entity follows takes the name from the file's table `read` (see
/// [`crate::Drawing::proxy_layers`]). A layer that is gone becomes layer 0 (the proxy's own
/// layer, as in a block); an index past the table, or one of a record without a name, stays
/// past the written one, which keeps the layer before it as AutoCAD does. Only the 310 groups
/// that hold the declared size are read and rewritten. `None` when no index changes, or the
/// graphics aren't readable.
pub fn with_proxy_layers(&self, read: &[String], written: &[String]) -> Option<Vec<RawTag>> {
// Only a proxy entity's own graphics: a kept dimension draws from its block instead.
if !self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") {
return None;
}
let (at, size) = self.graphics_size_group()?;
let (mut bytes, mut groups) = (Vec::new(), Vec::new());
for i in (at + 1..self.tags.len()).take_while(|&i| self.tags[i].code == 310) {
if bytes.len() >= size {
break;
}
let before = bytes.len();
if !push_hex(&mut bytes, &self.tags[i].value) {
return None;
}
groups.push((i, bytes.len() - before));
}
let end = size.min(bytes.len());
// The ATTRIBUTE_LAYER chunks: where each index sits.
let mut refs: Vec<(usize, u32)> = Vec::new();
let mut chunk = 8usize;
while let (Some(len), Some(kind)) = (u32_at(&bytes[..end], chunk), u32_at(&bytes[..end], chunk + 4)) {
let len = len as usize;
if len < 8 || chunk.saturating_add(len) > end {
break;
}
if kind == 16
&& let Some(i) = u32_at(&bytes[..chunk + len], chunk + 8)
{
refs.push((chunk + 8, i));
}
chunk += len;
}
if refs.is_empty() {
return None;
}
let indices: Vec<u32> = refs.iter().map(|r| r.1).collect();
let learned = self.layers_by_index(&bytes[..end], &indices);
if read.is_empty() && learned.is_empty() {
return None;
}
// Each written name's first place, found once.
let mut place: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
for (p, n) in written.iter().enumerate() {
place.entry(n.to_ascii_lowercase()).or_insert(u32::try_from(p).unwrap_or(u32::MAX));
}
let zero = place.get("0").copied();
let past = u32::try_from(written.len()).unwrap_or(u32::MAX).max(u32::try_from(read.len()).unwrap_or(u32::MAX));
let mut resolved: std::collections::HashMap<u32, u32> = std::collections::HashMap::new();
let mut changed = false;
for (offset, i) in refs {
let j = *resolved.entry(i).or_insert_with(|| {
let name = match learned.get(&i) {
Some(name) => name.as_deref(),
None => read.get(i as usize).map(String::as_str),
};
match name.filter(|n| !n.is_empty()) {
Some(name) => place.get(&name.to_ascii_lowercase()).copied().or(zero).unwrap_or(i),
None if i >= past => i,
None => past,
}
});
if j != i {
bytes[offset..offset + 4].copy_from_slice(&j.to_le_bytes());
changed = true;
}
}
if !changed {
return None;
}
let mut tags = self.tags.clone();
let mut from = 0;
for (g, n) in groups {
tags[g].value = bytes[from..from + n].iter().map(|b| format!("{b:02X}")).collect();
from += n;
}
Some(tags)
}
/// The layer each ATTRIBUTE_LAYER index of `bytes` (the record's `indices`) stands for in
/// this record's decoded graphics: the bytes decoded again with index `i` named `#i` give the
/// same entities in the same order, so each one's marker meets its real layer. `None` for an
/// index after which the graphics stay on the layer before (one past the table it was read
/// with). An index above 65,535 isn't named here (it resolves through the file's table, like
/// one no entity follows). Empty when the graphics don't match
/// (not decoded from these bytes); an index whose entities disagree is left out.
fn layers_by_index(&self, bytes: &[u8], indices: &[u32]) -> std::collections::HashMap<u32, Option<String>> {
/// What the entities after an index say about it.
enum Seen {
/// They are on this layer, and the ones before them weren't.
Named(String),
/// They are on the same layer as the ones before them: the index keeps that layer,
/// or names it.
Kept(String),
/// It keeps the layer before (two kept observations on different layers).
Keeps,
}
const MAX: u32 = 65_535;
let mut out: std::collections::HashMap<u32, Option<String>> = std::collections::HashMap::new();
if self.graphics.is_empty() {
return out;
}
let max = indices.iter().copied().filter(|&i| i <= MAX).max().unwrap_or(0);
let markers = ProxyTables { layers: (0..=max).map(|i| format!("\u{1}{i}")).collect(), ..ProxyTables::default() };
let marked = proxy_entities(bytes, &markers, Handle(0));
if marked.len() != self.graphics.len() {
return out;
}
let same = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
let mut seen: std::collections::HashMap<u32, Seen> = std::collections::HashMap::new();
let mut conflict = std::collections::HashSet::new();
let mut before: Option<(&str, &str)> = None;
for (m, g) in marked.iter().zip(&self.graphics) {
let (mark, real) = (m.common.layer.as_str(), g.common.layer.as_str());
let changed_here = before.is_none_or(|(prev_mark, _)| prev_mark != mark);
let kept = before.is_some_and(|(_, prev_real)| same(prev_real, real));
before = Some((mark, real));
let Some(i) = mark.strip_prefix('\u{1}').and_then(|i| i.parse::<u32>().ok()) else { continue };
if !changed_here {
// The same marker on another real layer: an index in between (one past the table
// the marker decoding doesn't see as such) changed it, so this one can't be named.
if !kept {
conflict.insert(i);
}
continue;
}
let real = real.to_string();
let merged = match (seen.remove(&i), kept) {
(None, false) => Some(Seen::Named(real)),
(None, true) => Some(Seen::Kept(real)),
(Some(Seen::Named(a) | Seen::Kept(a)), false) | (Some(Seen::Named(a)), true) if same(&a, &real) => Some(Seen::Named(a)),
(Some(Seen::Kept(a)), true) => Some(if same(&a, &real) { Seen::Kept(a) } else { Seen::Keeps }),
(Some(Seen::Keeps), true) => Some(Seen::Keeps),
_ => None,
};
match merged {
Some(s) => {
seen.insert(i, s);
}
None => {
conflict.insert(i);
}
}
}
for (i, s) in seen {
if !conflict.contains(&i) {
out.insert(i, if let Seen::Named(n) = s { Some(n) } else { None });
}
}
out
}
}
impl crate::Drawing {
/// Rename layer `old` to `new` where proxy graphics use it: in [`crate::Drawing::proxy_layers`],
/// so saving finds the layer under its new name, and in the decoded graphics, which draw on
/// it at once. RENAME calls it, LAYMRG for each merged layer (its graphics move to the
/// target, as its objects do) and LAYDEL with layer 0.
pub fn rename_proxy_layer(&mut self, old: &str, new: &str) {
for n in &mut self.proxy_layers {
if n.eq_ignore_ascii_case(old) {
*n = new.to_string();
}
}
let uses = |e: &Entity| matches!(&e.kind, EntityKind::Unknown(u) if u.graphics.iter().any(|g| g.common.layer.eq_ignore_ascii_case(old)));
let fix = |e: &mut Entity| {
if let EntityKind::Unknown(u) = &mut e.kind {
for g in u.graphics.iter_mut().filter(|g| g.common.layer.eq_ignore_ascii_case(old)) {
g.common.layer = new.to_string();
}
}
};
let mut stores: Vec<&mut crate::EntityStore> = vec![&mut self.model];
stores.extend(self.layouts.iter_mut().map(|l| &mut l.entities));
for b in self.blocks.values_mut() {
if b.entities.iter().any(|e| uses(e)) {
stores.push(&mut std::sync::Arc::make_mut(b).entities);
}
}
for store in stores {
let hs: Vec<Handle> = store.iter().filter(|e| uses(e)).map(|e| e.handle).collect();
for h in hs {
store.modify(h, fix);
}
}
}
}
/// Append the bytes of hex string `s`. False on a character that isn't a hex digit.
fn push_hex(out: &mut Vec<u8>, s: &str) -> bool {
let digits: Vec<u8> = s.trim().bytes().collect();
@@ -99,6 +330,7 @@ struct Decoder<'a> {
handle: Handle,
/// Layer, colour, linetype and lineweight for the entities that follow.
pen: Common,
/// Whether polygons and circles that follow are filled (ATTRIBUTE_FILL).
fill: bool,
/// Model transforms pushed by PUSH_MATRIX, innermost last (row-major 3x4 of the 4x4).
matrices: Vec<[f64; 12]>,
@@ -119,9 +351,9 @@ impl Decoder<'_> {
// CIRCLE_3P: three points on it.
3 => {
if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point())
&& let Some((c, r)) = circle_through(self.xy(p1), self.xy(p2), self.xy(p3))
&& let Some(fit) = Fit3::through(p1, p2, p3)
{
self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r }));
self.circle_in(fit.center, fit.radius, fit.e1, fit.e2);
}
}
// CIRCULAR_ARC: centre, radius, normal, start vector, sweep angle (around the normal).
@@ -133,11 +365,12 @@ impl Decoder<'_> {
// CIRCULAR_ARC_3P: start, a point on the arc, end.
5 => {
if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point()) {
self.arc_3p(self.xy(p1), self.xy(p2), self.xy(p3));
self.arc_3p_local(p1, p2, p3);
}
}
// POLYLINE and POLYGON: a count, then the points.
6 | 7 => {
// POLYLINE and POLYGON: a count, then the points; POLYLINE_WITH_NORMAL: a count, the
// points and a normal (the dimension lines of a LARGE_RADIAL_DIMENSION's picture).
6 | 7 | 32 => {
let Some(n) = b.u32() else { return };
let n = (n as usize).min(MAX_VERTICES);
let pts: Vec<Vec2> = (0..n).map_while(|_| b.point()).map(|p| self.xy(p)).collect();
@@ -192,9 +425,10 @@ impl Decoder<'_> {
self.pen.color = Color::from_aci(i16::try_from(c).unwrap_or(256));
}
}
// ATTRIBUTE_LAYER: index into the layer table; an index past it leaves the layer.
// ATTRIBUTE_LAYER: index into the layer table; an index past it, or one of a record
// without a name, leaves the layer.
16 => {
if let Some(name) = b.u32().and_then(|i| self.tables.layers.get(i as usize)) {
if let Some(name) = b.u32().and_then(|i| self.tables.layers.get(i as usize)).filter(|n| !n.is_empty()) {
self.pen.layer = name.clone();
}
}
@@ -204,12 +438,18 @@ impl Decoder<'_> {
if let Some(i) = b.u32() {
self.pen.linetype = match i {
32766 => "ByBlock".into(),
_ => self.tables.linetypes.get(i as usize).cloned().unwrap_or_else(|| "ByLayer".into()),
_ => self.tables.linetypes.get(i as usize).filter(|n| !n.is_empty()).cloned().unwrap_or_else(|| "ByLayer".into()),
};
}
}
// ATTRIBUTE_FILL: the next polygon is filled.
20 => self.fill = b.u32().is_some_and(|f| f != 0),
// ATTRIBUTE_FILL: a trait like the colour, in force until the next one: 1 fills the
// polygons and circles that follow, 2 (and anything else) doesn't (AcGiFillType
// kAcGiFillAlways, kAcGiFillNever).
20 => {
if let Some(f) = b.u32() {
self.fill = f == 1;
}
}
// ATTRIBUTE_TRUE_COLOR: a colour with its method in the top byte.
22 => {
if let Some(v) = b.u32() {
@@ -277,12 +517,60 @@ impl Decoder<'_> {
self.matrices.iter().map(|m| (m[0] * m[5] - m[1] * m[4]).abs().sqrt()).product()
}
/// A full circle around `c`, through the pushed matrices.
/// Where the pushed matrices take `c` and the unit vectors `e1`, `e2` of a circle's plane: the
/// circle of radius 1 around `c` is drawn as `c' + u·cos a + v·sin a`. The vectors go through
/// the matrices' linear parts only, so a small scale isn't lost against a large translation.
fn axes(&self, c: Vec3, e1: Vec3, e2: Vec3) -> (Vec2, Vec2, Vec2) {
(self.xy(c), self.linear(e1), self.linear(e2))
}
/// Direction `v` through the pushed matrices' linear parts, innermost first, in the XY plane.
fn linear(&self, v: Vec3) -> Vec2 {
let mut v = v;
for m in self.matrices.iter().rev() {
v = Vec3::new(m[0] * v.x + m[1] * v.y + m[2] * v.z, m[4] * v.x + m[5] * v.y + m[6] * v.z, m[8] * v.x + m[9] * v.y + m[10] * v.z);
}
v.xy()
}
/// A full circle around `c`, through the pushed matrices: an ellipse when they scale its
/// plane unevenly or shear it. While ATTRIBUTE_FILL is on, a solid hatch under it: AutoCAD
/// draws a filled shape's outline too, with its lineweight.
fn circle(&mut self, c: Vec3, r: f64) {
let r = r * self.scale();
let c = self.xy(c);
if r.is_finite() && r > 0.0 && c.is_finite() {
self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r }));
self.circle_in(c, r, X, Y);
}
/// The circle of radius `r` around `c` in the plane of the unit vectors `e1` and `e2`, as
/// `circle` draws one in the chunk's XY plane.
fn circle_in(&mut self, c: Vec3, r: f64, e1: Vec3, e2: Vec3) {
let (at, u, v) = self.axes(c, e1, e2);
if !(r.is_finite() && r > 0.0 && at.is_finite()) {
return;
}
match round(u * r, v * r) {
Some(r) => {
if self.fill {
// Two half-circle arcs (bulge 1).
let side = |p: Vec2| PolyVertex { p, bulge: 1.0, start_width: 0.0, end_width: 0.0 };
self.solid(vec![side(at + Vec2::new(r, 0.0)), side(at - Vec2::new(r, 0.0))]);
}
self.push(EntityKind::Circle(Circle { center: at.to3(0.0), radius: r }));
}
None => {
let Some(e) = ellipse(at, u * r, v * r, 0.0, std::f64::consts::TAU) else {
return self.edge_on(at, u * r, v * r, 0.0, std::f64::consts::TAU);
};
if self.fill {
// Bulges draw circular arcs only: the fill follows the ellipse in 72
// straight sides, finer than a plotted pixel at the sizes proxies use.
let side = |i: u32| {
let a = std::f64::consts::TAU * f64::from(i) / 72.0;
PolyVertex { p: at + u * (r * a.cos()) + v * (r * a.sin()), bulge: 0.0, start_width: 0.0, end_width: 0.0 }
};
self.solid((0..72).map(side).collect());
}
self.push(EntityKind::Ellipse(e));
}
}
}
@@ -296,12 +584,62 @@ impl Decoder<'_> {
let dir = if normal.z < 0.0 { -1.0 } else { 1.0 };
let a0 = start.y.atan2(start.x);
let a1 = a0 + dir * sweep;
let on = |a: f64| c + Vec3::new(r * a.cos(), r * a.sin(), 0.0);
let mid = on((a0 + a1) / 2.0);
if sweep.abs() >= std::f64::consts::TAU - 1e-9 {
return self.circle(c, r);
}
self.arc_3p(self.xy(on(a0)), self.xy(mid), self.xy(on(a1)));
self.arc_between(c, r, X, Y, a0, a1);
}
/// The arc of radius `r` around `c` from angle `a0` to `a1` (from `e1` towards `e2`, the unit
/// vectors of its plane), either way round, through the pushed matrices: an elliptical arc
/// when they don't keep it round.
fn arc_between(&mut self, c: Vec3, r: f64, e1: Vec3, e2: Vec3, a0: f64, a1: f64) {
let (at, u, v) = self.axes(c, e1, e2);
let on = |a: f64| at + u * (r * a.cos()) + v * (r * a.sin());
if round(u * r, v * r).is_some() {
return self.arc_3p(on(a0), on((a0 + a1) / 2.0), on(a1));
}
match ellipse(at, u * r, v * r, a0.min(a1), a0.max(a1)) {
Some(e) => self.push(EntityKind::Ellipse(e)),
None => self.edge_on(at, u * r, v * r, a0.min(a1), a0.max(a1)),
}
}
/// A circle or arc `c + u·cos a + v·sin a` (`a` from `a0` to `a1`) seen edge-on: `u` and `v`
/// on one line, so it draws as the line between its two farthest points along it.
fn edge_on(&mut self, c: Vec2, u: Vec2, v: Vec2, a0: f64, a1: f64) {
use std::f64::consts::{PI, TAU};
let d = if u.len() >= v.len() { u } else { v };
if !(c.is_finite() && d.is_finite() && v.is_finite() && u.is_finite() && d.len() > 0.0) {
return;
}
let d = d * (1.0 / d.len());
// Along d the point is at R·cos(a − φ): farthest out at φ and φ + π, where the sweep has them.
let phi = v.dot(d).atan2(u.dot(d));
let inside = |a: f64| (a - a0).rem_euclid(TAU) <= a1 - a0;
let on = |a: f64| c + u * a.cos() + v * a.sin();
let mut ends = [a0, a1, phi, phi + PI].into_iter().filter(|&a| a == a0 || a == a1 || inside(a)).map(on).map(|p| (p - c).dot(d));
let first = ends.next().unwrap_or(0.0);
let (lo, hi) = ends.fold((first, first), |(lo, hi), t| (lo.min(t), hi.max(t)));
if hi > lo {
self.push(EntityKind::Line(Line { a: (c + d * lo).to3(0.0), b: (c + d * hi).to3(0.0) }));
}
}
/// The arc from `p1` through `p2` to `p3`, chunk coordinates: fitted in the plane of the
/// three points and drawn through the pushed matrices, which may make it elliptical.
fn arc_3p_local(&mut self, p1: Vec3, p2: Vec3, p3: Vec3) {
if self.matrices.is_empty() && p1.z == p2.z && p2.z == p3.z {
return self.arc_3p(p1.xy(), p2.xy(), p3.xy());
}
let Some(fit) = Fit3::through(p1, p2, p3) else {
return self.polyline(vec![self.xy(p1), self.xy(p3)], false);
};
let (a1, a2, a3) = (fit.angle(p1), fit.angle(p2), fit.angle(p3));
let ccw = |from: f64, to: f64| (to - from).rem_euclid(std::f64::consts::TAU);
// Counter-clockwise from p1 to p3 when p2 lies on that way, else from p3 to p1.
let (from, sweep) = if ccw(a1, a2) <= ccw(a1, a3) { (a1, ccw(a1, a3)) } else { (a3, ccw(a3, a1)) };
self.arc_between(fit.center, fit.radius, fit.e1, fit.e2, from, from + sweep);
}
/// The arc from `p1` through `p2` to `p3`.
@@ -317,29 +655,15 @@ impl Decoder<'_> {
self.push(EntityKind::Arc(Arc { center: c.to3(0.0), radius: r, start, end }));
}
/// A polyline, or a closed polygon: filled (a solid hatch) when ATTRIBUTE_FILL asked for it,
/// which applies to this one polygon only.
/// A polyline, or a closed polygon: on a solid hatch while ATTRIBUTE_FILL is on (the outline
/// is drawn too, as for a circle).
fn polyline(&mut self, pts: Vec<Vec2>, polygon: bool) {
let fill = std::mem::take(&mut self.fill);
if pts.iter().any(|p| !p.is_finite()) || pts.is_empty() {
return;
}
if polygon && fill && pts.len() >= 3 {
if polygon && self.fill && pts.len() >= 3 {
let vertices = pts.iter().map(|&p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect();
return self.push(EntityKind::Hatch(Hatch {
pattern: "SOLID".into(),
solid: true,
loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
style: 0,
elevation: 0.0,
gradient: None,
origin: Vec2::ZERO,
background: None,
pattern_lines: Vec::new(),
}));
self.solid(vertices);
}
match pts.as_slice() {
[a, b] if !polygon => self.push(EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) })),
@@ -350,6 +674,29 @@ impl Decoder<'_> {
}
}
/// A solid hatch with the one boundary `vertices`.
fn solid(&mut self, vertices: Vec<PolyVertex>) {
// At the cap the fill gives way to the outline that follows it: a shape left with only
// its fill couldn't be picked or snapped to.
if self.out.len() + 1 >= MAX_ENTITIES {
return;
}
self.push(EntityKind::Hatch(Hatch {
pattern: "SOLID".into(),
solid: true,
loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
style: 0,
elevation: 0.0,
gradient: None,
origin: Vec2::ZERO,
background: None,
pattern_lines: Vec::new(),
}));
}
/// A single-line text, its style the first one whose font file the chunk names.
fn text(&mut self, t: TextChunk) {
let TextChunk { p, dir, height, width, oblique, value, font } = t;
@@ -407,17 +754,90 @@ struct TextChunk {
font: String,
}
/// The circle through three points (centre, radius), if they aren't on one line.
fn circle_through(a: Vec2, b: Vec2, c: Vec2) -> Option<(Vec2, f64)> {
let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));
if !d.is_finite() || d.abs() < 1e-12 {
/// The radius of the circle with conjugate radii `u` and `v` when they are one: as long as each
/// other and at right angles (a matrix that turns, mirrors and scales evenly).
fn round(u: Vec2, v: Vec2) -> Option<f64> {
let (lu, lv) = (u.len(), v.len());
let tol = 1e-9 * lu.max(lv);
((lu - lv).abs() <= tol && u.dot(v).abs() <= tol * lu.max(lv) && lu.is_finite() && lu > 0.0).then_some(lu)
}
/// The ellipse `c + u·cos a + v·sin a` for `a` from `a0` to `a1` (counter-clockwise in the
/// parameter): its axes from the conjugate radii `u` and `v`, the arc carried over to the
/// ellipse's own parameter (counter-clockwise from its major axis).
fn ellipse(c: Vec2, u: Vec2, v: Vec2, a0: f64, a1: f64) -> Option<Ellipse> {
use std::f64::consts::{FRAC_PI_2, TAU};
// c + u·cos a + v·sin a = c + p·cos(a − t) + q·sin(a − t): p and q at right angles.
let t = 0.5 * (2.0 * u.dot(v)).atan2(u.len2() - v.len2());
let p = u * t.cos() + v * t.sin();
let q = v * t.cos() - u * t.sin();
// The ellipse turns counter-clockwise with its parameter only when q is p turned left;
// a mirroring matrix reverses it.
let mirrored = p.cross(q) < 0.0;
let q = if mirrored { -q } else { q };
let (mut s0, mut s1) = if mirrored { (t - a1, t - a0) } else { (a0 - t, a1 - t) };
// The major axis is the longer of p and q.
let (major, minor) = if q.len() > p.len() {
s0 -= FRAC_PI_2;
s1 -= FRAC_PI_2;
(q, p.len())
} else {
(p, q.len())
};
let ratio = minor / major.len();
if !(c.is_finite() && major.is_finite() && major.len() > 0.0 && ratio.is_finite() && ratio > 0.0) {
return None;
}
let (a2, b2, c2) = (a.x * a.x + a.y * a.y, b.x * b.x + b.y * b.y, c.x * c.x + c.y * c.y);
let center =
Vec2::new((a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d, (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d);
let r = (a - center).len();
(center.is_finite() && r.is_finite() && r > 0.0).then_some((center, r))
let full = (a1 - a0) >= TAU - 1e-9;
let (start, end) = if full { (0.0, TAU) } else { (s0.rem_euclid(TAU), s1.rem_euclid(TAU)) };
Some(Ellipse { center: c.to3(0.0), major: major.to3(0.0), ratio, start, end })
}
/// The circle through three points (centre, radius), if they aren't on one line.
fn circle_through(a: Vec2, b: Vec2, c: Vec2) -> Option<(Vec2, f64)> {
cadcraft_geom::Circle::from_3_points(a, b, c).filter(|f| f.radius > 0.0).map(|f| (f.center, f.radius))
}
const X: Vec3 = Vec3 { x: 1.0, y: 0.0, z: 0.0 };
const Y: Vec3 = Vec3 { x: 0.0, y: 1.0, z: 0.0 };
/// The circle through three points in space: its centre, radius and the unit vectors `e1`, `e2`
/// of its plane. For points of equal `z` they are X and Y, so angles are the chunk's.
struct Fit3 {
center: Vec3,
radius: f64,
e1: Vec3,
e2: Vec3,
}
impl Fit3 {
/// The fit, if the points aren't on one line (relative to the triangle's size, so it holds at
/// any scale).
fn through(p1: Vec3, p2: Vec3, p3: Vec3) -> Option<Fit3> {
let (u, v) = (p2 - p1, p3 - p1);
let w = u.cross(v);
let w2 = w.dot(w);
if !(w2.is_finite() && w.len() > 1e-12 * (u.len() * v.len()) && w2 > 0.0) {
return None;
}
// The centre in point-relative coordinates: ((|u|² v − |v|² u) × w) / (2 |w|²).
let center = p1 + (v * u.dot(u) - u * v.dot(v)).cross(w) * (0.5 / w2);
let radius = (p1 - center).len();
// The plane's normal towards +Z (which way the arc turns comes from the middle point), and
// X (or Y) laid into the plane.
let up = if w.z < 0.0 { -1.0 } else { 1.0 };
let n = w * (up / w.len());
let along = |a: Vec3| a - n * a.dot(n);
let e1 = if along(X).len() > 1e-6 { along(X).normalized() } else { along(Y).normalized() };
let e2 = n.cross(e1);
(center.is_finite() && radius.is_finite() && radius > 0.0 && e2.is_finite()).then_some(Fit3 { center, radius, e1, e2 })
}
/// The angle of `p` around the centre, from `e1` towards `e2`.
fn angle(&self, p: Vec3) -> f64 {
let d = p - self.center;
d.dot(self.e2).atan2(d.dot(self.e1))
}
}
/// The little-endian u32 at `at`, if `bytes` holds one there.
@@ -591,15 +1011,160 @@ mod tests {
assert!(matches!(&e.kind, EntityKind::LwPolyline(p) if p.vertices.len() == 3 && !p.closed));
}
/// ATTRIBUTE_FILL is a trait like the colour: 1 (kAcGiFillAlways) fills every polygon and
/// circle until a 2 (kAcGiFillNever) ends it, whatever is drawn in between. AutoCAD
/// Mechanical writes 2 before its balloons' circles and 1 before their arrowheads and dots.
#[test]
fn a_filled_polygon_is_a_solid_hatch_and_fill_applies_once() {
fn fill_is_a_trait_until_turned_off() {
let mut tri = 3u32.to_le_bytes().to_vec();
for (x, y) in [(0.0, 0.0), (4.0, 0.0), (2.0, 3.0)] {
tri.extend(pt(x, y));
}
let es = proxy_entities(&graphics(&[chunk(20, &1u32.to_le_bytes()), chunk(7, &tri), chunk(7, &tri)]), &tables(), Handle(1));
assert!(matches!(&es[0].kind, EntityKind::Hatch(h) if h.solid && h.loops[0].vertices.len() == 3));
assert!(matches!(&es[1].kind, EntityKind::LwPolyline(p) if p.closed));
let mut line = 2u32.to_le_bytes().to_vec();
line.extend(pt(0.0, 0.0));
line.extend(pt(1.0, 0.0));
let mut dot = pt(5.0, 5.0);
dot.extend(0.5f64.to_le_bytes());
dot.extend(pt(0.0, 0.0));
let (on, off) = (chunk(20, &1u32.to_le_bytes()), chunk(20, &2u32.to_le_bytes()));
let es = proxy_entities(
&graphics(&[on, chunk(6, &line), chunk(7, &tri), chunk(2, &dot), chunk(7, &tri), off, chunk(7, &tri), chunk(2, &dot)]),
&tables(),
Handle(1),
);
let kinds: Vec<&str> = es.iter().map(|e| e.kind.type_name()).collect();
// A filled shape is a solid hatch with its outline on top.
assert_eq!(kinds, ["Line", "Hatch", "Polyline", "Hatch", "Circle", "Hatch", "Polyline", "Polyline", "Circle"]);
assert!(matches!(&es[1].kind, EntityKind::Hatch(h) if h.solid && h.loops[0].vertices.len() == 3));
assert!(matches!(&es[2].kind, EntityKind::LwPolyline(p) if p.closed));
// The filled circle: two half-circle arcs around its centre.
let disc: Vec<(Vec2, f64)> = match &es[3].kind {
EntityKind::Hatch(h) => h.loops[0].vertices.iter().map(|v| (v.p, v.bulge)).collect(),
other => panic!("{other:?}"),
};
assert_eq!(disc, [(Vec2::new(5.5, 5.0), 1.0), (Vec2::new(4.5, 5.0), 1.0)]);
assert!(matches!(&es[6].kind, EntityKind::LwPolyline(p) if p.closed));
}
/// A circle or arc under a matrix that scales its plane unevenly is an ellipse, measured
/// and snapped as one; one that scales evenly stays a circle or arc.
#[test]
fn circles_and_arcs_under_an_uneven_matrix_are_ellipses() {
use std::f64::consts::{FRAC_PI_2, PI, TAU};
let push = |sx: f64, sy: f64| {
let mut m = [0.0f64; 16];
(m[0], m[5], m[10], m[15], m[3]) = (sx, sy, 1.0, 1.0, 10.0);
chunk(29, &m.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>())
};
let mut circle = pt(0.0, 0.0);
circle.extend(1.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0));
let quarter = {
let mut a = pt(0.0, 0.0);
a.extend(1.0f64.to_le_bytes());
a.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
a.extend(pt(1.0, 0.0));
a.extend(FRAC_PI_2.to_le_bytes());
a.extend(0u32.to_le_bytes());
a
};
// Three points of the same quarter arc, as CIRCULAR_ARC_3P gives them.
let h = std::f64::consts::FRAC_1_SQRT_2;
let quarter_3p: Vec<u8> = [pt(1.0, 0.0), pt(h, h), pt(0.0, 1.0)].concat();
let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
let ell = |e: &Entity| match &e.kind {
EntityKind::Ellipse(e) => (e.center, e.major, e.ratio, e.start, e.end),
other => panic!("{other:?}"),
};
let es = proxy_entities(&graphics(&[push(2.0, 1.0), chunk(2, &circle), chunk(4, &quarter), chunk(5, &quarter_3p)]), &tables(), Handle(1));
let (c, major, ratio, start, end) = ell(&es[0]);
assert!(c == Vec3::new(10.0, 0.0, 0.0) && near(major.x.abs(), 2.0) && near(major.y, 0.0) && near(ratio, 0.5) && (start, end) == (0.0, TAU));
for e in &es[1..] {
let (_, major, ratio, start, end) = ell(e);
// The major axis may point either way along x; the arc runs from (12, 0) to (10, 1).
let at = |t: f64| Vec2::new(10.0, 0.0) + major.xy() * t.cos() + major.xy().perp() * (ratio * t.sin());
assert!((at(start) - Vec2::new(12.0, 0.0)).len() < 1e-9 && (at(end) - Vec2::new(10.0, 1.0)).len() < 1e-9, "{start} {end}");
assert!(near((end - start).rem_euclid(TAU), FRAC_PI_2));
}
// Mirrored along x and stretched: the quarter arc runs from (10, 1) to (8, 0).
let es = proxy_entities(&graphics(&[push(-2.0, 1.0), chunk(4, &quarter)]), &tables(), Handle(1));
let (_, major, ratio, start, end) = ell(&es[0]);
let at = |t: f64| Vec2::new(10.0, 0.0) + major.xy() * t.cos() + major.xy().perp() * (ratio * t.sin());
assert!((at(start) - Vec2::new(10.0, 1.0)).len() < 1e-9 && (at(end) - Vec2::new(8.0, 0.0)).len() < 1e-9, "{start} {end}");
// A filled circle under it: a solid hatch along the ellipse, under the ellipse.
let fill = chunk(20, &1u32.to_le_bytes());
let es = proxy_entities(&graphics(&[push(2.0, 1.0), fill, chunk(2, &circle)]), &tables(), Handle(1));
match (&es[0].kind, &es[1].kind) {
(EntityKind::Hatch(h), EntityKind::Ellipse(_)) => {
let xs = h.loops[0].vertices.iter().map(|v| v.p.x);
let (lo, hi) = xs.fold((f64::MAX, f64::MIN), |(lo, hi), x| (lo.min(x), hi.max(x)));
assert!(near(lo, 8.0) && near(hi, 12.0), "{lo} {hi}");
}
other => panic!("{other:?}"),
}
// Picked and snapped by the ellipse only, not the hatch's sides.
let u = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: es };
let prims = EntityKind::Unknown(u).prims();
assert!(matches!(prims.as_slice(), [crate::entity::Prim::Ellipse(_)]), "{prims:?}");
// A tiny scale under a far translation keeps the circle: radius 1e8 at scale 1e-8 is 1.
let mut far = [0.0f64; 16];
(far[0], far[5], far[10], far[15], far[3], far[7]) = (1e-8, 1e-8, 1.0, 1.0, 1e9, 1e9);
let far = chunk(29, &far.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>());
let mut big = pt(0.0, 0.0);
big.extend(1e8f64.to_le_bytes());
big.extend(pt(0.0, 0.0));
let es = proxy_entities(&graphics(&[far, chunk(2, &big)]), &tables(), Handle(1));
assert!(matches!(&es[..], [e] if matches!(&e.kind, EntityKind::Circle(c) if (c.radius - 1.0).abs() < 1e-6)), "{es:?}");
// Even scaling, mirrored or not, keeps circles and arcs.
let es = proxy_entities(&graphics(&[push(-3.0, 3.0), chunk(2, &circle), chunk(4, &quarter), chunk(5, &quarter_3p)]), &tables(), Handle(1));
assert!(matches!(&es[0].kind, EntityKind::Circle(c) if near(c.radius, 3.0)));
for e in &es[1..] {
let angle = |a: f64, b: f64| near((a - b).rem_euclid(TAU).min((b - a).rem_euclid(TAU)), 0.0);
assert!(matches!(&e.kind, EntityKind::Arc(a) if near(a.radius, 3.0) && angle(a.start, FRAC_PI_2) && angle(a.end, PI)), "{e:?}");
}
}
/// Three-point chunks are fitted in the plane of their points, then mapped: a circle across XY
/// turned into it, points far smaller than the scale that enlarges them, and circles and arcs
/// seen edge-on.
#[test]
fn three_point_chunks_fit_in_their_own_plane() {
use std::f64::consts::TAU;
let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
let p3 = |p: [f64; 3]| p.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>();
let mat = |m: [f64; 16]| chunk(29, &m.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>());
let turn = mat([0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]);
let across = [p3([0.0, 1.0, 0.0]), p3([0.0, 0.0, 1.0]), p3([0.0, -1.0, 0.0])].concat();
let tiny = mat([1e7, 0.0, 0.0, 0.0, 0.0, 1e7, 0.0, 0.0, 0.0, 0.0, 1e7, 0.0, 0.0, 0.0, 0.0, 1.0]);
let small = [p3([1e-7, 0.0, 0.0]), p3([0.0, 1e-7, 0.0]), p3([-1e-7, 0.0, 0.0])].concat();
// The arc's half is the one through the middle point.
for (m, pts, mid) in [(turn, across.clone(), Vec2::new(1.0, 0.0)), (tiny, small, Vec2::new(0.0, 1.0))] {
let es = proxy_entities(&graphics(&[m, chunk(3, &pts), chunk(5, &pts)]), &tables(), Handle(1));
assert!(matches!(&es[0].kind, EntityKind::Circle(c) if c.center.xy().len() < 1e-9 && near(c.radius, 1.0)), "{es:?}");
match &es[1].kind {
EntityKind::Arc(a) => {
let m = a.start + (a.end - a.start).rem_euclid(TAU) / 2.0;
assert!(near(a.radius, 1.0) && (Vec2::new(m.cos(), m.sin()) - mid).len() < 1e-9, "{a:?}");
}
other => panic!("{other:?}"),
}
}
// Seen edge-on (in a vertical plane, no matrix) a circle or arc is a line over all it
// covers in plan: for the arc through (0, 1) from (0, 0.6) to (0, 0.6), beyond its ends.
let edge = |pts: Vec<u8>, kind: u32| match proxy_entities(&graphics(&[chunk(kind, &pts)]), &tables(), Handle(1)).as_slice() {
[Entity { kind: EntityKind::Line(l), .. }] => {
let (lo, hi) = (l.a.y.min(l.b.y), l.a.y.max(l.b.y));
assert!(near(l.a.x, 0.0) && near(l.b.x, 0.0), "{l:?}");
(lo, hi)
}
other => panic!("{other:?}"),
};
let (lo, hi) = edge(across.clone(), 3);
assert!(near(lo, -1.0) && near(hi, 1.0));
let (lo, hi) = edge(across, 5);
assert!(near(lo, -1.0) && near(hi, 1.0));
let (lo, hi) = edge([p3([0.0, 0.6, 0.8]), p3([0.0, 1.0, 0.0]), p3([0.0, 0.6, -0.8])].concat(), 5);
assert!(near(lo, 0.6) && near(hi, 1.0), "{lo} {hi}");
}
/// A quarter arc counter-clockwise from 0°, and the same sweep around a downward normal,
@@ -675,8 +1240,137 @@ mod tests {
assert_eq!(u.proxy_graphics_bytes(), [1, 2, 3, 4, 5]);
let other = Unknown { dxf_type: "ACAD_PROXY_OBJECT".into(), ..u.clone() };
assert!(other.proxy_graphics_bytes().is_empty());
let bad = Unknown { tags: vec![tag(92, "4"), tag(310, "01zz")], ..u };
let bad = Unknown { tags: vec![tag(92, "4"), tag(310, "01zz")], ..u.clone() };
assert!(bad.proxy_graphics_bytes().is_empty());
// The size group is the first after the AcDbProxyEntity marker: a 160 or 92 before it
// belongs to the entity's common data.
let marked = Unknown {
tags: vec![
tag(100, "AcDbEntity"),
tag(160, "2"),
tag(310, "EEEE"),
tag(100, "AcDbProxyEntity"),
tag(90, "498"),
tag(92, "3"),
tag(310, "010203"),
],
..u.clone()
};
assert_eq!(marked.proxy_graphics_bytes(), [1, 2, 3]);
// A size far past the data gives the data there is.
let short = Unknown { tags: vec![tag(92, "16000000"), tag(310, "0102")], ..u };
assert_eq!(short.proxy_graphics_bytes(), [1, 2]);
}
/// Another entity saved with a picture of itself (a LARGE_RADIAL_DIMENSION) holds it in its
/// AcDbEntity part; a 92 among its own groups after that isn't taken for it. Its dimension
/// lines are POLYLINE_WITH_NORMAL chunks (type 32).
#[test]
fn a_kept_entity_draws_the_picture_in_its_acdbentity_part() {
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let mut line = 2u32.to_le_bytes().to_vec();
line.extend(pt(250.0, 150.0));
line.extend(pt(290.0, 190.0));
line.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
let g = graphics(&[chunk(32, &line)]);
let hex: String = g.iter().map(|b| format!("{b:02X}")).collect();
let size = g.len().to_string();
let u = Unknown {
dxf_type: "LARGE_RADIAL_DIMENSION".into(),
tags: vec![
tag(100, "AcDbEntity"),
tag(8, "0"),
tag(92, &size),
tag(310, &hex),
tag(100, "AcDbDimension"),
tag(2, "*D1"),
tag(100, "AcDbRadialDimensionLarge"),
tag(40, "0.785398"),
],
graphics: Vec::new(),
};
assert_eq!(u.proxy_graphics_bytes(), g);
let es = proxy_entities(&u.proxy_graphics_bytes(), &tables(), Handle(1));
assert!(
matches!(&es[..], [e] if matches!(&e.kind, EntityKind::Line(l) if l.a == Vec3::new(250.0, 150.0, 0.0) && l.b == Vec3::new(290.0, 190.0, 0.0)))
);
// Without graphics in the AcDbEntity part, a 92 in the entity's own data is not one.
let own = Unknown { tags: vec![tag(100, "AcDbEntity"), tag(8, "0"), tag(100, "AcDbSomething"), tag(92, "4"), tag(310, "01020304")], ..u };
assert!(own.proxy_graphics_bytes().is_empty());
}
/// Saving renames the layer indices by name into the written table, reading only the 310
/// groups the declared size needs: a damaged group after them doesn't stop it.
#[test]
fn layer_indices_follow_the_written_table() {
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let mut circle = pt(0.0, 0.0);
circle.extend(1.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0));
let g = graphics(&[chunk(16, &2u32.to_le_bytes()), chunk(2, &circle)]);
let hex: String = g.iter().map(|b| format!("{b:02X}")).collect();
let read: Vec<String> = ["0", "A", "B", "C"].map(String::from).to_vec();
let tables = ProxyTables { layers: read.clone(), ..ProxyTables::default() };
let u = Unknown {
dxf_type: "ACAD_PROXY_ENTITY".into(),
tags: vec![tag(100, "AcDbProxyEntity"), tag(92, &g.len().to_string()), tag(310, &hex), tag(310, "GG")],
graphics: proxy_entities(&g, &tables, Handle(1)),
};
assert_eq!(u.graphics[0].common.layer, "B");
let written: Vec<String> = ["0", "B", "C"].map(String::from).to_vec();
let tags = u.with_proxy_layers(&read, &written).expect("remapped");
let again = Unknown { tags, ..u.clone() };
assert_eq!(
proxy_entities(&again.proxy_graphics_bytes(), &ProxyTables { layers: written, ..ProxyTables::default() }, Handle(1))[0].common.layer,
"B"
);
assert_eq!(again.tags[3].value, "GG", "the group after the graphics is kept as read");
}
/// An index whose graphics stay on the layer before (99 here, past the table) doesn't make
/// the index before it (3) look contradictory when that one comes again; an index above
/// 65,535 isn't named (it resolves through the file's table), and the others still are.
#[test]
fn indices_are_named_around_kept_layers_and_huge_indices() {
let mut circle = pt(0.0, 0.0);
circle.extend(1.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0));
let read: Vec<String> = ["0", "A", "C", "B"].map(String::from).to_vec();
let tables = ProxyTables { layers: read, ..ProxyTables::default() };
let named = |indices: &[u32]| {
let mut chunks = Vec::new();
for &i in indices {
chunks.push(chunk(16, &i.to_le_bytes()));
chunks.push(chunk(2, &circle));
}
let g = graphics(&chunks);
let u = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: proxy_entities(&g, &tables, Handle(1)) };
let mut learned: Vec<(u32, Option<String>)> = u.layers_by_index(&g, indices).into_iter().collect();
learned.sort();
learned
};
assert_eq!(named(&[0, 3, 99, 3]), [(0, Some("0".into())), (3, Some("B".into())), (99, None)]);
assert_eq!(named(&[2, 70_000]), [(2, Some("C".into()))]);
// Layer 4 (past the table, so it keeps layer 0), a circle, then layers 1 and 4 at once (4
// keeps A): both circles follow index 4 in the marker decoding, on different layers.
let g = graphics(&[
chunk(16, &4u32.to_le_bytes()),
chunk(2, &circle),
chunk(16, &1u32.to_le_bytes()),
chunk(16, &4u32.to_le_bytes()),
chunk(2, &circle),
]);
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let hex: String = g.iter().map(|b| format!("{b:02X}")).collect();
let u = Unknown {
dxf_type: "ACAD_PROXY_ENTITY".into(),
tags: vec![tag(100, "AcDbProxyEntity"), tag(92, &g.len().to_string()), tag(310, &hex)],
graphics: proxy_entities(&g, &tables, Handle(1)),
};
assert_eq!(u.graphics.iter().map(|e| e.common.layer.as_str()).collect::<Vec<_>>(), ["0", "A"]);
assert!(!u.layers_by_index(&g, &[4, 1, 4]).contains_key(&4), "index 4 isn't named");
// Saved with the same table, nothing changes, so both circles stay where they are.
assert!(u.with_proxy_layers(&tables.layers, &tables.layers).is_none());
}
/// Truncated chunks, sizes past the end, huge counts and garbage draw what they can and
+9
View File
@@ -111,6 +111,8 @@ pub struct Drawing {
pub mline_styles: Vec<MLineStyle>,
pub blocks: BTreeMap<String, std::sync::Arc<Block>>,
pub model: EntityStore,
/// Model layout's page setup, or the default extents-to-fit setup for a new drawing.
pub model_page: Option<PageSetup>,
pub layouts: Vec<Layout>,
/// The layout a file marks active (its block is `*Paper_Space`, the others `*Paper_SpaceN`),
/// written active again. `None`, or a layout that no longer exists: the first by tab order.
@@ -158,6 +160,11 @@ pub struct Drawing {
pub portable_fonts: bool,
/// The pixels of the raster images that are loaded (IMAGE). Never written to a file.
pub rasters: Rasters,
/// The LAYER table of the file this drawing was read from, in the file's order and under
/// the layers' current names: proxy graphics name layers by their index in it, and saving
/// turns those indices into the written table's (#3094). An empty name stands for a record
/// without one. Empty for a drawing not read from a file.
pub proxy_layers: Vec<String>,
}
impl Default for Drawing {
@@ -201,6 +208,7 @@ impl Drawing {
mline_styles: vec![MLineStyle::default()],
blocks: BTreeMap::new(),
model: EntityStore::new(),
model_page: None,
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
active_layout: None,
views: Vec::new(),
@@ -221,6 +229,7 @@ impl Drawing {
skipped_records: BTreeMap::new(),
portable_fonts: false,
rasters: Rasters::default(),
proxy_layers: Vec::new(),
}
}
+15 -1
View File
@@ -782,6 +782,10 @@ impl Block {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PageSetup {
/// Original plot subclass and the modeled values it was read with.
/// Only edits that clone the page retain these original fields; the JSON form does not carry them.
#[serde(skip)]
pub file_plot_settings: Option<Box<FilePlotSettings>>,
pub device: String,
pub paper: String,
/// Paper size in millimetres (portrait width/height before rotation).
@@ -789,7 +793,7 @@ pub struct PageSetup {
pub height_mm: f64,
pub margins_mm: [f64; 4],
pub landscape: bool,
/// "layout" | "extents" | "display" | "window" | "limits".
/// "layout" | "extents" | "display" | "window" | "limits" | "view".
pub plot_area: String,
/// Plot window corners `[x1, y1, x2, y2]` (DXF plot layout groups 48, 49, 140, 141); used when `plot_area` is "window".
pub plot_window: [f64; 4],
@@ -838,6 +842,7 @@ pub struct PageSetup {
impl Default for PageSetup {
fn default() -> Self {
PageSetup {
file_plot_settings: None,
device: "None".into(),
paper: "ANSI A (8.50 x 11.00 Inches)".into(),
width_mm: 215.9,
@@ -862,6 +867,15 @@ impl Default for PageSetup {
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct FilePlotSettings {
/// Groups after AcDbPlotSettings and before AcDbLayout, including unmodeled fields.
/// See the Autodesk DXF Reference, LAYOUT and PLOTSETTINGS.
pub tags: Vec<craft_dxf::Tag>,
/// The interpreted page with no nested file settings, for detecting edits on save.
pub page: PageSetup,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Layout {
+4 -2
View File
@@ -46,7 +46,7 @@ pub(super) fn linear_kind(p1: Vec2, p2: Vec2, at: Vec2, rotation: Option<f64>, a
DimKind::Linear { rotation: rotation.unwrap_or_else(auto) }
}
/// Add a dimension. With DIMASSOC on, definition points that sit on object endpoints,
/// Add a dimension. With DIMASSOC 2, definition points that sit on object endpoints,
/// vertices or centres are attached to them (associative dimensions).
pub(super) fn add_dim(s: &mut Session, k: EntityKind) -> Result<Handle> {
let mut k = k;
@@ -74,8 +74,10 @@ pub(super) fn add_dim(s: &mut Session, k: EntityKind) -> Result<Handle> {
Ok(h)
}
/// Only DIMASSOC mode 2 attaches newly created dimensions to their source geometry.
pub(super) fn assoc_enabled(s: &Session) -> bool {
s.doc().map(|d| d.header.i64("DIMASSOC", 2) != 0).unwrap_or(false)
// Mode 1 keeps a dimension as one object without linking it to source geometry.
s.doc().map(|d| d.header.i64("DIMASSOC", 2) == 2).unwrap_or(false)
}
pub(super) fn with_assoc(k: EntityKind, assoc: Vec<DimAssoc>) -> EntityKind {
+12 -7
View File
@@ -161,17 +161,22 @@ pub(super) fn run_dimtedit(s: &mut Session, p: &Value) -> Result<Value> {
}
/// DIMSPACE: equal spacing of parallel linear dimensions from a base dimension.
/// [Auto spacing](https://help.autodesk.com/cloudhelp/2023/ENU/AutoCAD-LT-MAC/files/GUID-18DF8B02-3E43-4531-ACE0-75FA7161F209.htm)
/// uses twice the base dimension's text height.
pub(super) fn run_dimspace(s: &mut Session, p: &Value) -> Result<Value> {
let base = hex_param(p, "base").ok_or_else(|| bad("dimspace", "`base` dimension is required"))?;
let hs: Vec<Handle> = dims_of(s, &targets(s, p)?).into_iter().filter(|h| *h != base).collect();
let d = s.doc()?;
let Some(EntityKind::Dimension(b)) = d.entity(base).map(|e| e.kind.clone()) else { return Err(bad("dimspace", "`base` is not a dimension")) };
let st = d.dim_style(&b.style).cloned().unwrap_or_default().with_overrides(&b.overrides);
let spacing = p
.get("spacing")
.and_then(Value::as_f64)
.filter(|v| v.is_finite() && *v >= 0.0)
.unwrap_or(st.baseline_spacing * st.effective_scale(d.header.f64("DIMSCALE", 1.0)) * 2.0);
let spacing = p.get("spacing").and_then(Value::as_f64).filter(|v| v.is_finite() && *v >= 0.0).unwrap_or_else(|| {
let st = d.dim_style(&b.style).cloned().unwrap_or_default().with_overrides(&b.overrides);
let text_height = d
.text_style(&st.text_style)
.map(|style| style.height)
.filter(|height| height.is_finite() && *height > 0.0)
.unwrap_or_else(|| st.text_height * st.effective_scale(d.header.f64("DIMSCALE", 1.0)));
2.0 * text_height
});
let dir = match b.kind {
DimKind::Linear { rotation } => Vec2::from_angle(rotation),
DimKind::Aligned => (b.p14.xy() - b.p13.xy()).normalized(),
@@ -209,7 +214,7 @@ pub(super) fn run_dimspace(s: &mut Session, p: &Value) -> Result<Value> {
}
/// DIMSPACE at the command line: select the base dimension, select the dimensions to space, then
/// the spacing (Enter or Auto takes the DIMDLI-based default).
/// the spacing (Enter or Auto uses the base dimension's text height).
#[derive(Default)]
pub(super) struct DimSpaceM {
base: Option<Handle>,
+40
View File
@@ -318,6 +318,46 @@ fn dimtedit_and_dimspace() {
assert!((dim(&s, b).defpt.y - 1.5).abs() < 1e-9, "{:?}", dim(&s, b).defpt);
}
#[test]
fn dimspace_auto_uses_the_base_dimension_text_height_and_scale() {
let mut s = Session::new();
let text_height = 3.0;
let scale = 1.5;
s.execute("dimstyle", &json!({ "name": "Base", "DIMTXT": 2, "DIMDLI": 7, "DIMSCALE": scale })).unwrap();
let base = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 4] })).unwrap());
s.execute("dimoverride", &json!({ "handles": [base.hex()], "DIMTXT": text_height })).unwrap();
s.execute("dimstyle.current", &json!({ "name": "Standard" })).unwrap();
let first = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [20, 0], "at": [10, 20] })).unwrap());
let second = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [30, 0], "at": [15, 36] })).unwrap());
s.execute("dimspace", &json!({ "base": base.hex(), "handles": [first.hex(), second.hex()] })).unwrap();
let positions = [base, first, second].map(|handle| dim(&s, handle).defpt.y);
let expected_spacing = 2.0 * text_height * scale;
assert!((positions[0] - 4.0).abs() < 1e-9, "positions: {positions:?}");
assert!(positions.windows(2).all(|pair| (pair[1] - pair[0] - expected_spacing).abs() < 1e-9), "positions: {positions:?}");
}
#[test]
fn dimspace_auto_uses_the_base_dimension_fixed_text_style_height() {
let mut s = Session::new();
let fixed_height = 2.5;
s.execute("style", &json!({ "name": "Fixed", "height": fixed_height })).unwrap();
s.execute("dimstyle", &json!({ "name": "Base", "DIMTXSTY": "Fixed", "DIMTXT": 3, "DIMDLI": 7, "DIMSCALE": 2 })).unwrap();
let base = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 4] })).unwrap());
s.execute("dimstyle.current", &json!({ "name": "Standard" })).unwrap();
let target = h(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [20, 0], "at": [10, 20] })).unwrap());
s.start("dimspace").unwrap();
s.input(Input::Pick(vec![base])).unwrap();
s.input(Input::Pick(vec![target])).unwrap();
s.input(Input::Enter).unwrap();
s.input(Input::Text("Auto".into())).unwrap();
let spacing = dim(&s, target).defpt.y - dim(&s, base).defpt.y;
assert!((spacing - 2.0 * fixed_height).abs() < 1e-9, "spacing: {spacing}");
}
#[test]
fn text_style_rename_follows_block_definition_text() {
let mut s = Session::new();
+39 -10
View File
@@ -15,7 +15,7 @@ use super::machines::{SelOutcome, SelectPhase, number};
use super::{CommandSpec, bad, bool_or, f64_or, find_command, ok, point_param, point_req, point_value, str_param, targets};
use super::has_doc;
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
use crate::{Accept, AttribAsk, AttribEntry, EngineError, Input, Interactive, Origin, Prompt, Result, Session, Step};
mod attdef;
mod attedit;
@@ -43,14 +43,14 @@ pub fn specs() -> Vec<CommandSpec> {
.menu(&["Insert", "Block..."])
.alias(&["i", "-insert", "ddinsert"])
.params("{name (\"*NAME\": exploded), file?: DXF/DWG path (defines or redefines block `name`, default the file name, from its model space; base point $INSBASE), at: [x,y], scale?: number | [x, y], rotation? (degrees), basePoint?: [x,y] (block coordinates), attribs?: {TAG: value}, explode?: bool}")
.interactive(|_| Ok(Box::new(InsertM::default()))),
.interactive(|s| Ok(Box::new(InsertM { person: s.command_origin() == Origin::Person, ..InsertM::default() }))),
CommandSpec::new("blockspalette", "Blocks Palette", run_blockspalette)
.params("{references?: bool (default true; counting reads every object)} → {blocks: [{name, description, references?}], truncated} (the app opens the Blocks palette instead)")
.enabled(has_doc)
.noundo(),
CommandSpec::new("minsert", "Multiple Insert", run_minsert)
.params("{name, file?: DXF/DWG path (as INSERT), at: [x,y], scale?: number | [x, y], rotation? (degrees), basePoint?: [x,y], attribs?: {TAG: value}, rows?: 1..32767 (default 1), columns?: 1..32767 (default 1), rowSpacing?, columnSpacing? (along the reference's own axes, not scaled with it)}")
.interactive(|_| Ok(Box::new(InsertM { minsert: true, ..InsertM::default() }))),
.interactive(|s| Ok(Box::new(InsertM { minsert: true, person: s.command_origin() == Origin::Person, ..InsertM::default() }))),
CommandSpec::new("attdef", "Define Attributes...", run_attdef)
.menu(&["Draw", "Block", "Define Attributes..."])
.alias(&["att", "-attdef"])
@@ -73,14 +73,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"])
@@ -858,6 +858,16 @@ struct InsertM {
rotation: Option<f64>,
/// The attributes asked for: tag, prompt, default value, and Verify (asked again).
attdefs: Vec<(String, String, String, bool)>,
/// How many of `attdefs` have their value: counted here, not by `values`, whose key is the
/// tag, so two definitions with one tag are still each asked once.
asked: usize,
/// ATTDIA 1 and a person started the command: the values are asked for in the Edit
/// Attributes dialog. A script, LISP routine or JSON call that opened INSERT has nobody to
/// answer a dialog, so it asks at the command line, even after the program is done.
dialog: bool,
/// A person started this command ([`Session::command_origin`]), fixed for its whole life:
/// only then may ATTDIA 1 open the dialog.
person: bool,
values: serde_json::Map<String, Value>,
/// Verify attributes asked again so far.
verified: usize,
@@ -889,7 +899,7 @@ impl InsertM {
s.echo("Enter attribute values");
}
// Then the Verify attributes are asked again, with the values typed.
if self.stage == InsStage::Attribs && self.values.len() >= self.attdefs.len() && self.verified < self.verifying().len() {
if self.stage == InsStage::Attribs && self.asked >= self.attdefs.len() && self.verified < self.verifying().len() {
if self.verified == 0 {
s.echo("Verify attribute values");
}
@@ -897,7 +907,7 @@ impl InsertM {
return Ok(Step::Continue);
}
if self.stage == InsStage::Attribs
&& self.values.len() >= self.attdefs.len()
&& self.asked >= self.attdefs.len()
&& let (Some(n), Some(a), Some(sc), Some(r)) = (self.name.clone(), self.at, self.scale, self.rotation)
{
let h = insert_scaled(s, &n, a, self.scale3(sc), r, self.base, &self.values, self.grid())?;
@@ -948,6 +958,8 @@ impl InsertM {
s.echo(format!("Block \"{name}\" not found."));
return Ok(());
};
// A program cannot click the dialog: it asks at the command line, as ATTDIA 0 does.
self.dialog = s.settings.attdia && self.person;
self.attdefs = if self.explode || !s.settings.attreq {
Vec::new()
} else {
@@ -962,6 +974,7 @@ impl InsertM {
})
.collect()
};
self.asked = 0;
self.name = Some(b.name.clone());
self.stage = InsStage::Point;
Ok(())
@@ -1051,7 +1064,7 @@ impl Interactive for InsertM {
InsStage::Cell(a) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a),
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::NUMBER),
InsStage::Attribs => {
let (_, prompt, default, _) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default();
let (_, prompt, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
let p = Prompt::new(if prompt.is_empty() { "Enter attribute value".into() } else { prompt }, Accept::TEXT);
// No default shown when there is none ("Value:", AutoCAD 2024), not "<>".
if default.is_empty() { p } else { p.default(default) }
@@ -1258,12 +1271,16 @@ impl Interactive for InsertM {
}
}
InsStage::Attribs => {
let (tag, _, default, _) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default();
let (tag, _, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
let v = match i {
Input::Text(t) => t,
// A canvas click is no answer to a text prompt: the dialog stays up and the
// attribute is asked for again, as Verify does. Enter keeps the default.
Input::Point(_) => return Ok(Step::Continue),
_ => default,
};
self.values.insert(tag, Value::String(v));
self.asked += 1;
return self.advance(s);
}
// Enter keeps the value typed.
@@ -1301,6 +1318,18 @@ impl Interactive for InsertM {
self.grid().apply(&mut ins);
vec![EntityKind::Insert(ins)]
}
fn attribute_entry(&self) -> Option<AttribEntry> {
// Only before the first answer: values typed at the command line go on there.
if !self.dialog || self.stage != InsStage::Attribs || self.asked > 0 || self.attdefs.is_empty() {
return None;
}
let rows = self
.attdefs
.iter()
.map(|(tag, prompt, default, verify)| AttribAsk { tag: tag.clone(), prompt: prompt.clone(), default: default.clone(), verify: *verify })
.collect();
Some(AttribEntry::idle(self.name.clone().unwrap_or_default(), rows))
}
}
mod attribs;
+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, s.viewport_frozen(), 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(())
}
}
+3
View File
@@ -171,6 +171,8 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
frontier.extend(override_arrows(dm));
}
EntityKind::MLeader(m) => frontier.extend(m.block.as_ref().map(|b| b.block.clone())),
// A dimension kept as read draws, and is saved with, the block it names (#3438).
EntityKind::Unknown(u) => frontier.extend(u.dimension_block().map(str::to_string)),
_ => {}
}
}
@@ -188,6 +190,7 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
frontier.extend(override_arrows(dm));
}
EntityKind::MLeader(m) => frontier.extend(m.block.as_ref().map(|b| b.block.clone())),
EntityKind::Unknown(u) => frontier.extend(u.dimension_block().map(str::to_string)),
_ => {}
}
}
+3 -5
View File
@@ -9,10 +9,7 @@ use super::helpers::{arc, circle, line, lwpoly, polygon_from_edge, polygon_typed
use super::machines::number;
use super::pline_opts::{Outcome, PlineAsk};
use super::{
CommandSpec, bad, bool_or, distinct_points, f64_or, f64_req, find_command, point_param, point_req, point_value, points_param, size_param,
str_param,
};
use super::{CommandSpec, bad, bool_or, distinct_points, f64_or, f64_req, point_param, point_req, point_value, points_param, size_param, str_param};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step, snap};
@@ -32,7 +29,8 @@ use line_pline::{LineM, PlineM, run_line, run_pline};
use point::{DonutM, PointM, RayM, run_donut, run_point, run_ray};
use polygon::{PolygonM, run_polygon};
use solid::{SolidM, run_solid};
use spline::{SplineM, run_spline};
pub(super) use spline::SplineM;
use spline::run_spline;
use text::{MTextM, TextM, run_mtext, run_text};
pub(crate) use text::{justify, justify_prompt};
+34 -22
View File
@@ -1,7 +1,7 @@
use super::{
Accept, EntityKind, Input, Interactive, Prompt, Result, Session, Spline, Step, Value, Vec2, added, bad, bool_or, distinct_points, find_command,
points_param,
Accept, EntityKind, Input, Interactive, Prompt, Result, Session, Spline, Step, Value, Vec2, added, bad, bool_or, distinct_points, points_param,
};
use crate::cmd::draw2::SplineCvM;
pub(super) fn run_spline(s: &mut Session, p: &Value) -> Result<Value> {
if p.get("object").is_some() {
@@ -26,11 +26,11 @@ pub(super) fn run_spline(s: &mut Session, p: &Value) -> Result<Value> {
}
#[derive(Default)]
pub(super) struct SplineM {
pub(in crate::cmd) struct SplineM {
pts: Vec<Vec2>,
asking_method: bool,
/// `Method` > `CV` hands over to the control-vertex machine (`spline.cv`).
delegate: Option<Box<dyn Interactive>>,
/// Both entry points share Method and Object; CV handles its own points and degree.
cv: Option<SplineCvM>,
/// Knots, end tangents and fit tolerance chosen so far.
opts: cadcraft_geom::FitOptions,
/// An option asking a further question (Knots, Tangency, toLerance, Object).
@@ -38,6 +38,10 @@ pub(super) struct SplineM {
}
impl SplineM {
pub(in crate::cmd) fn cv() -> Self {
Self { cv: Some(SplineCvM::default()), ..Self::default() }
}
fn make(&self, closed: bool) -> Spline {
Spline::fit_with(&self.pts, closed, self.opts)
}
@@ -49,18 +53,25 @@ impl Interactive for SplineM {
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.opts.knots = crate::cmd::spline_opts::current_knots(s);
if let Some(cv) = &mut self.cv {
return cv.begin(s);
}
s.echo(format!("Current settings: Method=Fit Knots={}", self.opts.knots.name()));
Ok(Step::Continue)
}
fn prompt(&self, s: &Session) -> Prompt {
if let Some(d) = &self.delegate {
return d.prompt(s);
}
if let Some(a) = &self.ask {
return a.prompt(&self.opts, &self.pts);
}
if self.asking_method {
return Prompt::new("Enter spline creation method", crate::cmd::curves::KW).kw(&["Fit", "CV"]).default("Fit");
return Prompt::new("Enter spline creation method", crate::cmd::curves::KW).kw(&["Fit", "CV"]).default(if self.cv.is_some() {
"CV"
} else {
"Fit"
});
}
if let Some(cv) = &self.cv {
return cv.prompt(s);
}
match self.pts.len() {
0 => Prompt::new("Specify first point", Accept::POINT).kw(&["Method", "Knots", "Object"]),
@@ -72,9 +83,6 @@ impl Interactive for SplineM {
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if let Some(d) = &mut self.delegate {
return d.input(s, i);
}
if let Some(a) = &mut self.ask {
use crate::cmd::spline_opts::Outcome;
return match a.input(s, i, &mut self.opts, &self.pts)? {
@@ -96,21 +104,25 @@ impl Interactive for SplineM {
if self.asking_method {
match i {
Input::Keyword(k) if k == "CV" => {
let Some(factory) = find_command("spline.cv").and_then(|c| c.interactive) else {
return Err(crate::EngineError::Other("CV: not available yet".into()));
};
let mut m = factory(s)?;
self.asking_method = false;
let step = m.begin(s)?;
self.delegate = Some(m);
return Ok(step);
return self.cv.get_or_insert_with(SplineCvM::default).begin(s);
}
Input::Keyword(_) | Input::Enter => self.asking_method = false,
Input::Keyword(k) if k == "Fit" => {
self.asking_method = false;
self.cv = None;
return self.begin(s);
}
Input::Enter => self.asking_method = false,
Input::Text(_) => return Err(crate::EngineError::Other("Invalid option keyword.".into())),
_ => {}
}
return Ok(Step::Continue);
}
if let Some(cv) = &mut self.cv
&& !matches!(&i, Input::Keyword(k) if k == "Method" || k == "Object")
{
return cv.input(s, i);
}
match i {
Input::Point(p) => {
self.pts.push(p);
@@ -148,8 +160,8 @@ impl Interactive for SplineM {
}
}
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
if let Some(d) = &self.delegate {
return d.preview(s, c);
if let Some(cv) = &self.cv {
return cv.preview(s, c);
}
if self.pts.is_empty() {
return Vec::new();
+3 -2
View File
@@ -28,7 +28,8 @@ mod xline;
pub(crate) use arc::arc_machine;
use arc::{ArcContinueM, ArcV, run_arc_continue, run_arc_variant, seq};
use centermark::{CenterM, run_centerline, run_centermark};
use curves3d::{HelixM, Poly3dM, SplineCvM, run_3dpoly, run_helix, run_spline_cv};
pub(super) use curves3d::SplineCvM;
use curves3d::{HelixM, Poly3dM, run_3dpoly, run_helix, run_spline_cv};
use divide::{DivideM, run_divide, run_measure};
use ellipse::{run_ellipse_arc, run_ellipse_axis};
pub(crate) use rect::{RectM2, run_rectang2};
@@ -149,7 +150,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("spline.cv", "Control Vertices", run_spline_cv)
.menu(&["Draw", "Spline", "Control Vertices"])
.params("{control: [[x,y],...], degree?: 1..10 (default 3), closed?}")
.interactive(|_| Ok(Box::new(SplineCvM::default()))),
.interactive(|_| Ok(Box::new(super::draw::SplineM::cv()))),
CommandSpec::new("centermark", "Center Mark", run_centermark)
.menu(&["Draw", "Center Mark"])
.params("{handle | handles} (circles/arcs; lines on the CENTER linetype)")
+5 -3
View File
@@ -284,7 +284,7 @@ pub(super) fn run_spline_cv(s: &mut Session, p: &Value) -> Result<Value> {
}
#[derive(Default)]
pub(super) struct SplineCvM {
pub(in crate::cmd) struct SplineCvM {
pts: Vec<Vec2>,
degree: Option<usize>,
asking_degree: bool,
@@ -312,7 +312,9 @@ impl Interactive for SplineCvM {
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if self.asking_degree {
if let Input::Text(t) = &i {
let d = number(t).filter(|d| (1.0..=10.0).contains(d)).ok_or_else(|| other("Degree must be 1..10."))?;
let d = number(t)
.filter(|d| d.fract() == 0.0 && (1.0..=10.0).contains(d))
.ok_or_else(|| other("Degree must be a whole number from 1 to 10."))?;
self.degree = Some(d as usize);
}
self.asking_degree = false;
@@ -340,7 +342,7 @@ impl Interactive for SplineCvM {
s.add_entity(EntityKind::Spline(sp))?;
return Ok(Step::Done);
}
_ => s.echo(format!("{k}: use SPLINE for fit points.")),
_ => return Err(other("Invalid option keyword.")),
}
Ok(Step::Continue)
}
+143 -11
View File
@@ -4,15 +4,15 @@
//! the drawing as a crossed-out frame.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, PoisonError};
use cadcraft_doc::{Drawing, EntityKind, Image, Raster};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
use super::file::base64_decode;
use super::{CommandSpec, bad, f64_or, point_param, str_param};
use super::{CommandSpec, bad, point_value, str_param};
use crate::{Result, Session};
/// Most image files loaded per drawing.
@@ -27,6 +27,9 @@ const MAX_IMAGE_BASE64: u64 = MAX_IMAGE_BYTES.div_ceil(3) * 4;
const MAX_IMAGE_TEXT: u64 = MAX_IMAGE_BASE64 + MAX_IMAGE_BASE64 / 16;
/// Most decoded pixel bytes kept per drawing; images past it stay unloaded.
const MAX_LOADED_BYTES: u64 = 2 << 30;
/// Most bytes one decoded image takes: the image reader decodes at most 128 million pixels, four
/// bytes each (`cadcraft_io::raster::MAX_IMAGE_PIXELS`).
const MAX_DECODED_BYTES: u64 = 512_000_000;
/// Most image files decoded at the same time when a drawing opens.
const MAX_LOADERS: usize = 4;
/// Longest image path taken from a caller.
@@ -183,13 +186,11 @@ fn over_limit(path: &str) -> String {
/// what opening a drawing with large images waits for). The results are in the order of `paths`.
fn decode_files(paths: &[&str], host: Option<&str>) -> Vec<std::result::Result<Raster, String>> {
// Decoded bytes so far, shared by the loaders: past the limit no further file is started.
let decoded_bytes = AtomicU64::new(0);
let budget = Budget::default();
let load = |path: &str| -> std::result::Result<Raster, String> {
if decoded_bytes.load(Ordering::Relaxed) > MAX_LOADED_BYTES {
return Err(format!("not loaded (more than {} MB of images)", MAX_LOADED_BYTES >> 20));
}
let mut decoding = budget.start().ok_or_else(|| format!("not loaded (more than {} MB of images)", MAX_LOADED_BYTES >> 20))?;
let r = read_file(path, host).and_then(|bytes| decode(&bytes))?;
decoded_bytes.fetch_add(bytes_of(&r), Ordering::Relaxed);
decoding.bytes = bytes_of(&r);
Ok(r)
};
let mut results: Vec<Option<std::result::Result<Raster, String>>> = paths.iter().map(|_| None).collect();
@@ -224,6 +225,83 @@ fn decode_files(paths: &[&str], host: Option<&str>) -> Vec<std::result::Result<R
results.into_iter().zip(paths).map(|(result, path)| result.unwrap_or_else(|| load(path))).collect()
}
/// The decoded bytes the loaders of one drawing share.
#[derive(Default)]
struct Budget {
spent: Mutex<Spent>,
/// Signaled when a file finishes decoding.
finished: Condvar,
}
/// Decoded bytes so far, and how many files are being decoded.
#[derive(Default)]
struct Spent {
decoded: u64,
decoding: u64,
}
/// Whether a loader may start decoding a file.
#[derive(Debug, PartialEq)]
enum Admit {
Start,
/// Not until another file finishes.
Wait,
/// The images decoded so far are past the limit.
Full,
}
impl Spent {
/// A file starts while the images decoded so far, and the largest image each file being
/// decoded can become, fit under `limit`. A file always starts when no other one is being
/// decoded, so that the images run past `limit` by one image at most.
fn admit(&mut self, limit: u64, largest: u64) -> Admit {
if self.decoded > limit {
return Admit::Full;
}
let reserved = self.decoding.saturating_add(1).saturating_mul(largest);
if self.decoding > 0 && self.decoded.saturating_add(reserved) > limit {
return Admit::Wait;
}
self.decoding = self.decoding.saturating_add(1);
Admit::Start
}
/// A file finished decoding into `bytes` (0 when it failed).
fn finish(&mut self, bytes: u64) {
self.decoding = self.decoding.saturating_sub(1);
self.decoded = self.decoded.saturating_add(bytes);
}
}
impl Budget {
/// Wait until a file may start decoding; `None` once the images decoded so far are past the
/// limit.
fn start(&self) -> Option<Decoding<'_>> {
let mut spent = self.spent.lock().unwrap_or_else(PoisonError::into_inner);
loop {
match spent.admit(MAX_LOADED_BYTES, MAX_DECODED_BYTES) {
Admit::Start => return Some(Decoding { budget: self, bytes: 0 }),
Admit::Full => return None,
Admit::Wait => spent = self.finished.wait(spent).unwrap_or_else(PoisonError::into_inner),
}
}
}
}
/// A file being decoded. Dropping it counts `bytes` as decoded and lets a waiting loader check
/// again, also when the decoding failed.
struct Decoding<'a> {
budget: &'a Budget,
bytes: u64,
}
impl Drop for Decoding<'_> {
fn drop(&mut self) {
self.budget.spent.lock().unwrap_or_else(PoisonError::into_inner).finish(self.bytes);
self.budget.finished.notify_all();
}
}
/// How many files are decoded at once: one per processor, at most [`MAX_LOADERS`] (each large
/// image needs several hundred megabytes while it is decoded) and no more than there are files.
fn loader_count(files: usize) -> usize {
@@ -268,6 +346,9 @@ pub(crate) fn run_imageattach(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(ID, "`path` is too long"));
}
let place = placement(p)?;
if p.get("name").is_some_and(|n| !(n.is_null() || n.is_string())) {
return Err(bad(ID, "`name` must be text"));
}
let raster = pixels(s, p, &path)?;
let (w, h) = (f64::from(raster.width()), f64::from(raster.height()));
// One pixel in drawing units, along the image's bottom edge (`u`) and its left edge (`v`).
@@ -305,18 +386,32 @@ struct Placement {
/// `at`, `rotation` and the width (`width`, else `scale`: an image is one unit wide at scale 1).
fn placement(p: &Value) -> Result<Placement> {
let at = point_param(p, "at").unwrap_or(Vec2::ZERO);
let at = match p.get("at") {
None | Some(Value::Null) => Vec2::ZERO,
Some(v) => point_value(v).ok_or_else(|| bad(ID, "`at` must be a point"))?,
};
if !(at.x.is_finite() && at.y.is_finite()) {
return Err(bad(ID, "`at` must be a point"));
}
// `scale` is checked even when `width` takes precedence over it.
let scale = number(p, "scale")?;
let width = match p.get("width") {
Some(v) => v.as_f64().filter(|w| w.is_finite()).ok_or_else(|| bad(ID, "`width` must be a number"))?,
None => f64_or(p, "scale", 1.0),
None => scale.unwrap_or(1.0),
};
if !(width.is_finite() && width > 0.0) {
return Err(bad(ID, "`scale` and `width` must be greater than zero"));
}
Ok(Placement { at, rotation: f64_or(p, "rotation", 0.0).to_radians(), width })
let rotation = number(p, "rotation")?.unwrap_or(0.0);
Ok(Placement { at, rotation: rotation.to_radians(), width })
}
/// The number `key` of `p`: `None` when it is omitted or null, an error when it is not a number.
fn number(p: &Value, key: &str) -> Result<Option<f64>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_f64().filter(|x| x.is_finite()).map(Some).ok_or_else(|| bad(ID, format!("`{key}` must be a number"))),
}
}
/// The pixels of the image at `path`: decoded from `data` when the caller hands the file over,
@@ -384,3 +479,40 @@ fn describe(d: &Drawing, path: &str, host: Option<&str>) -> Value {
};
json!({ "path": path, "foundAt": found_at, "status": status, "pixels": loaded.map(|r| json!([r.width(), r.height()])) })
}
#[cfg(test)]
mod tests {
use super::*;
/// A file starts only while the largest image each file being decoded can become still fits,
/// one file always starts when none is being decoded, and none starts past the limit.
#[test]
fn loaders_start_files_within_the_limit() {
let mut s = Spent::default();
// Room for two of the largest images.
assert_eq!(s.admit(10, 4), Admit::Start);
assert_eq!(s.admit(10, 4), Admit::Start);
assert_eq!(s.admit(10, 4), Admit::Wait);
s.finish(3);
assert_eq!(s.admit(10, 4), Admit::Wait, "3 decoded and two files that can become 4 each are past 10");
s.finish(5);
// Over the limit only by the one file being decoded.
assert_eq!(s.admit(10, 4), Admit::Start);
s.finish(4);
assert_eq!(s.admit(10, 4), Admit::Full);
// A failed file counts nothing.
let mut s = Spent::default();
assert_eq!(s.admit(10, 4), Admit::Start);
s.finish(0);
assert_eq!((s.decoded, s.decoding), (0, 0));
}
/// Files that fail still let the other loaders go on: every file gets a result.
#[test]
fn decode_files_finishes_when_every_file_fails() {
let paths = ["a.png", "b.png", "c.png", "d.png", "e.png", "f.png"];
let results = decode_files(&paths, None);
assert_eq!(results.len(), paths.len());
assert!(results.iter().all(std::result::Result::is_err), "none of these files exists");
}
}
+63 -6
View File
@@ -4,7 +4,7 @@ mod prompts;
mod state_prompts;
use cadcraft_color::Color;
use cadcraft_doc::{Layer, Lineweight};
use cadcraft_doc::{EntityKind, Layer, Lineweight};
use serde_json::{Value, json};
use super::machines::SelectRun;
@@ -101,7 +101,8 @@ fn run_list(s: &mut Session, _p: &Value) -> Result<Value> {
Ok(json!({ "layers": layers, "states": d.layer_states.iter().map(|st| st.name.clone()).collect::<Vec<_>>() }))
}
/// Lower-case names of layers that have objects on them (model, layouts and block definitions).
/// Lower-case names of layers that have objects on them (model, layouts and block definitions),
/// or that proxy graphics draw on: AutoCAD keeps those too.
pub fn used_layers(d: &cadcraft_doc::Drawing) -> std::collections::HashSet<String> {
let mut set = std::collections::HashSet::new();
let ents = d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter()));
@@ -113,6 +114,9 @@ pub fn used_layers(d: &cadcraft_doc::Drawing) -> std::collections::HashSet<Strin
for layer in super::blocks::object_attribs(e).iter().filter_map(|a| a.props.layer.as_ref()) {
set.insert(layer.to_ascii_lowercase());
}
if let EntityKind::Unknown(u) = &e.kind {
set.extend(u.graphics.iter().map(|g| g.common.layer.to_ascii_lowercase()));
}
}
set
}
@@ -258,6 +262,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
}
}
merge::rename_in_viewports(d, &old, &nn);
d.rename_proxy_layer(&old, &nn);
if cur.eq_ignore_ascii_case(&old) {
d.header.set_str("CLAYER", &nn);
}
@@ -302,10 +307,7 @@ fn run_delete(s: &mut Session, p: &Value) -> Result<Value> {
if name == "0" || name.eq_ignore_ascii_case("Defpoints") || d.header.str("CLAYER", "0").eq_ignore_ascii_case(&name) {
return Err(bad("layer.delete", "cannot delete layer 0, Defpoints or the current layer"));
}
let used = d.model.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name))
|| d.layouts.iter().any(|l| l.entities.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name)))
|| d.blocks.values().any(|b| b.entities.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name)));
if used {
if used_layers(d).contains(&name.to_ascii_lowercase()) {
return Err(bad("layer.delete", "layer has objects on it"));
}
d.layers.retain(|l| !l.name.eq_ignore_ascii_case(&name));
@@ -778,6 +780,61 @@ mod tests {
assert!(s.doc().unwrap().layer("A").is_some());
}
/// A session with layers A, B and C and a proxy on layer 0 whose graphics draw a line on B
/// (#3094).
fn proxy_on_b() -> Session {
use cadcraft_doc::{Common, Entity, EntityKind, Handle, Line, Space, Unknown};
let mut s = Session::new();
for name in ["A", "B", "C"] {
s.execute("layer.new", &json!({ "name": name })).unwrap();
}
let line = Entity {
handle: Handle(0),
common: Common { layer: "B".into(), ..Common::default() },
kind: EntityKind::Line(Line { a: cadcraft_doc::geom::Vec3::ZERO, b: cadcraft_doc::geom::Vec3::new(1.0, 0.0, 0.0) }),
};
let proxy = EntityKind::Unknown(Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: vec![line] });
s.doc_mut().unwrap().add(&Space::Model, Common::default(), proxy).unwrap();
s
}
fn graphics_layer(s: &Session) -> String {
s.doc()
.unwrap()
.model
.iter()
.find_map(|e| match &e.kind {
cadcraft_doc::EntityKind::Unknown(u) => u.graphics.first().map(|g| g.common.layer.clone()),
_ => None,
})
.unwrap()
}
/// As in AutoCAD, PURGE and layer.delete keep a layer only proxy graphics draw on.
#[test]
fn layers_proxy_graphics_draw_on_are_in_use() {
let mut s = proxy_on_b();
assert!(s.execute("layer.delete", &json!({ "name": "B" })).is_err());
s.execute("purge", &json!({})).unwrap();
let d = s.doc().unwrap();
assert!(d.layer("B").is_some() && d.layer("A").is_none() && d.layer("C").is_none());
}
/// RENAME and LAYMRG take the graphics with the layer, LAYDEL drops them to layer 0.
#[test]
fn rename_merge_and_laydel_move_proxy_graphics() {
let mut s = proxy_on_b();
s.doc_mut().unwrap().proxy_layers = vec!["0".into(), "A".into(), "B".into(), "C".into()];
s.execute("layer.set", &json!({ "name": "B", "newName": "B2" })).unwrap();
assert_eq!(graphics_layer(&s), "B2");
assert_eq!(s.doc().unwrap().proxy_layers, ["0", "A", "B2", "C"]);
s.execute("laymrg", &json!({ "from": "B2", "to": "C" })).unwrap();
assert_eq!(graphics_layer(&s), "C");
assert_eq!(s.doc().unwrap().proxy_layers, ["0", "A", "C", "C"]);
s.execute("laydel", &json!({ "name": "C" })).unwrap();
assert_eq!(graphics_layer(&s), "0");
}
#[test]
fn rename_repoints_paper_space_and_block_entities() {
let mut s = Session::new();
+9
View File
@@ -175,6 +175,10 @@ pub(super) fn run_laymrg(s: &mut Session, p: &Value) -> Result<Value> {
hs.len()
});
forget_in_viewports(d, &set);
// Proxy graphics drawn on a merged layer move to the target, as its objects do.
for source in &sources {
d.rename_proxy_layer(source, &target);
}
d.layers.retain(|l| !set.contains(&l.name.to_ascii_lowercase()));
let mut msg = format!("Merged {} into \"{target}\": {} moved.", quoted(&sources), plural(moved, "object"));
if set.contains(&d.header.str("CLAYER", "0").to_ascii_lowercase()) {
@@ -202,6 +206,11 @@ pub(super) fn run_laydel(s: &mut Session, p: &Value) -> Result<Value> {
hs.len()
});
forget_in_viewports(d, &set);
// A proxy isn't deleted for drawing on a deleted layer (its parts can't be); they fall back
// to layer 0, the proxy's own layer.
for source in &sources {
d.rename_proxy_layer(source, "0");
}
d.layers.retain(|l| !set.contains(&l.name.to_ascii_lowercase()));
s.set_selection(Vec::new());
let msg = format!("Deleted {} and {}.", quoted(&sources), plural(erased, "object"));
+1 -1
View File
@@ -36,7 +36,7 @@ pub(crate) use oops::{Erased, erase_kept};
use select_then::{DisplaceM, Op, SelectThen};
use stretch::{StretchM, run_stretch};
pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities};
use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
use transform::{mirror_entities, mirror_kind, run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
pub(crate) use trim::{CUT_ONCE, Edges, extend, json_pick_error, trim};
pub fn specs() -> Vec<CommandSpec> {
+23 -14
View File
@@ -2,7 +2,8 @@ use super::break_join::join;
use super::explode::explode;
use super::transform::{at_elevation, erase, scale_entities, transform_entities};
use super::{
Accept, EngineError, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Vec2, line, number,
Accept, EngineError, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Vec2, line,
mirror_entities, mirror_kind, number,
};
// ---------------- interactive ----------------
@@ -248,10 +249,11 @@ impl SelectThen {
}
}
/// Objects whose text MIRROR keeps readable instead of mirroring it with the geometry.
fn keeps_reading_when_mirrored(k: &EntityKind) -> bool {
/// Objects MIRROR must preview individually: readable text and hatches retaining fill direction.
fn needs_mirror_preview(k: &EntityKind) -> bool {
match k {
EntityKind::Insert(i) => !i.attribs.is_empty(),
EntityKind::Hatch(h) => !h.solid || h.gradient.is_some(),
k => matches!(
k,
EntityKind::Text(_)
@@ -265,8 +267,8 @@ fn keeps_reading_when_mirrored(k: &EntityKind) -> bool {
}
}
/// Text objects transformed for each frame of a MIRROR preview (on the CPU); more are not drawn.
const MAX_MIRROR_TEXT_PREVIEW: usize = 1000;
/// Objects transformed for each frame of a MIRROR preview (on the CPU); more are not drawn.
const MAX_MIRROR_OBJECT_PREVIEW: usize = 1000;
/// A finite length greater than zero (rejects 0, negatives, NaN and infinity).
fn positive_length(v: Option<f64>) -> Option<f64> {
@@ -347,6 +349,7 @@ impl Interactive for SelectThen {
_ => Prompt::new("", Accept::POINT),
}
}
/// Advance the selected transform command, applying MIRROR fill policy at commit.
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if !self.sel.done {
match self.sel.feed(s, &i)? {
@@ -364,7 +367,7 @@ impl Interactive for SelectThen {
if self.ask_erase {
let yes = matches!(&i, Input::Keyword(k) if k == "Yes") || matches!(&i, Input::Text(t) if t.trim().to_ascii_lowercase().starts_with('y'));
let (a, b) = (self.pts[0], self.pts[1]);
transform_entities(s, &self.objs, &Mat3::mirror(a, b), !yes)?;
mirror_entities(s, &self.objs, &Mat3::mirror(a, b), !yes)?;
s.set_selection(Vec::new());
return Ok(Step::Done);
}
@@ -456,6 +459,7 @@ impl Interactive for SelectThen {
_ => Ok(Step::Continue),
}
}
/// Build bounded transform previews, retaining readable text and hatch fill directions.
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
if self.op == Op::Rotate && self.reference {
return self.rotate_reference_preview(s, c);
@@ -484,13 +488,18 @@ impl Interactive for SelectThen {
.filter_map(|h| d.entity(*h))
.map(|e| {
let mut k = e.kind.clone();
k.transform(&m);
if self.op == Op::Mirror {
mirror_kind(&mut k, &m);
} else {
k.transform(&m);
}
k
})
.collect();
out.push(line(base, c));
out
}
/// Separate shared GPU transforms from objects that need an individual MIRROR preview.
fn drag(&self, s: &Session, c: Vec2) -> Option<crate::prompt::Drag> {
if (self.op == Op::Rotate && self.reference) || !self.sel.done {
return None;
@@ -508,19 +517,19 @@ impl Interactive for SelectThen {
if self.op != Op::Mirror {
return Some(crate::prompt::Drag { handles: self.objs.clone(), matrix, extra, clipboard: false });
}
// Mirrored text keeps reading left to right (MIRRTEXT 0), which the matrix alone can't
// draw: those objects are transformed one by one, the rest is mirrored on the GPU.
// Readable text and unchanged hatch directions cannot be drawn by reflecting their
// already-rendered primitives: preview those objects individually, the rest on the GPU.
let d = s.doc().ok()?;
let mut handles = Vec::with_capacity(self.objs.len());
let mut texts = 0;
let mut individual = 0;
for h in &self.objs {
let Some(e) = d.entity(*h) else { continue };
if !keeps_reading_when_mirrored(&e.kind) {
if !needs_mirror_preview(&e.kind) {
handles.push(*h);
} else if texts < MAX_MIRROR_TEXT_PREVIEW {
texts += 1;
} else if individual < MAX_MIRROR_OBJECT_PREVIEW {
individual += 1;
let mut k = e.kind.clone();
k.transform(&matrix);
mirror_kind(&mut k, &matrix);
extra.push(k);
}
}
+26 -1
View File
@@ -1,3 +1,4 @@
use cadcraft_doc::EntityKind;
use cadcraft_geom::Vec3;
use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, erase_kept, f64_req, json, point_param, point_req, targets};
@@ -9,6 +10,29 @@ pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy:
edit_entities(s, hs, copy, |e| e.kind.transform(m))
}
/// MIRROR's default hatch policy retains the fill direction while reflecting its boundary.
/// Keep this in the command layer: a reflection of an entire inserted block still transforms
/// all of its contents, rather than applying the policy for individually selected hatches.
pub(super) fn mirror_kind(k: &mut EntityKind, m: &Mat3) {
let angles = match k {
EntityKind::Hatch(h) => Some((h.angle, h.gradient.as_ref().map(|g| g.angle))),
_ => None,
};
k.transform(m);
if let (EntityKind::Hatch(h), Some((angle, gradient_angle))) = (k, angles) {
h.angle = angle;
if let (Some(g), Some(angle)) = (&mut h.gradient, gradient_angle) {
g.angle = angle;
}
}
}
/// Reflect selected entities with the command policy that retains individual hatch fill directions.
pub(super) fn mirror_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<Vec<Handle>> {
refuse_ole_frames(s, hs, m, copy)?;
edit_entities(s, hs, copy, |e| mirror_kind(&mut e.kind, m))
}
/// Scale `hs` by `f` about `base` in 3D, as AutoCAD 2024's SCALE does: about the base point's XY,
/// and every height of the objects about its Z, their thickness too.
pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64, copy: bool) -> Result<Vec<Handle>> {
@@ -151,6 +175,7 @@ pub(super) fn run_scale(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
/// Validate MIRROR parameters and apply the reflection, optionally replacing the source entities.
pub(super) fn run_mirror(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let a = point_req("mirror", p, "p1")?;
@@ -159,6 +184,6 @@ pub(super) fn run_mirror(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("mirror", "mirror line points coincide"));
}
let erase_src = bool_or(p, "erase", false);
let r = transform_entities(s, &hs, &Mat3::mirror(a, b), !erase_src)?;
let r = mirror_entities(s, &hs, &Mat3::mirror(a, b), !erase_src)?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
+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;
@@ -128,6 +137,15 @@ impl Interactive for Guarded {
None
})
}
fn attribute_entry(&self) -> Option<crate::prompt::AttribEntry> {
if self.broken.get().is_some() {
return None;
}
catch_unwind(AssertUnwindSafe(|| self.inner.attribute_entry())).unwrap_or_else(|_| {
self.broken.set(Some("panic in prompt"));
None
})
}
}
#[cfg(test)]
+24 -1
View File
@@ -55,7 +55,7 @@ pub use cadcraft_render as render;
pub use cmd::blocks::WblockPicks;
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices};
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use prompt::{Accept, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
pub use prompt::{Accept, AttribAsk, AttribEntry, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
mod doc_state;
mod error;
@@ -80,6 +80,18 @@ pub fn build_version() -> &'static str {
&VERSION
}
/// Who started the command running now ([`Session::start`]): a person at the command line or
/// from a menu, toolbar or palette, or a program (a script, an AutoLISP `(command …)`, a JSON
/// call). The origin is fixed when the command starts and kept for its whole life: only a
/// person's INSERT opens the Edit Attributes dialog, since nobody is there to answer one that a
/// program opened, and nobody has seen it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Origin {
#[default]
Person,
Program,
}
/// The editor session: open drawings, settings, the running command and the command log.
pub struct Session {
pub docs: Vec<DocState>,
@@ -91,11 +103,20 @@ pub struct Session {
pub running: Option<Running>,
/// How many commands were started, nested transparent ones left out.
pub commands_started: u64,
/// Who started the command running now ([`Origin`]): a command keeps the origin it started
/// with, so a scripted or LISP-started INSERT never opens a dialog, even when the user then
/// answers its prompts by hand.
command_origin: Origin,
/// The last command that ended by itself, not cancelled: its number in `commands_started`, and
/// whether it took new handles (it added to the drawing, and nothing took that back).
pub last_finished: Option<(u64, bool)>,
/// A script is running ([`Session::script`]); a SCRIPT command inside it is refused.
in_script: bool,
/// The LISP evaluator is running ([`Session::lisp_drive`]): what a routine feeds the command
/// line — the command it starts, or a `'command` token it types into a running one — is the
/// program's input, so [`Session::start`] records [`Origin::Program`] for it. Saved and
/// restored around each slice of a routine, so nesting keeps the outer answer.
program_input: bool,
/// The command suspended while a transparent command (`'ZOOM`, `'PAN`…) prompts inside it;
/// it resumes when that command ends. One level, as in AutoCAD.
pub suspended: Option<Running>,
@@ -192,8 +213,10 @@ impl Session {
settings: Settings::default(),
running: None,
commands_started: 0,
command_origin: Origin::Person,
last_finished: None,
in_script: false,
program_input: false,
suspended: None,
log: Vec::new(),
last_command: None,
+6
View File
@@ -363,11 +363,17 @@ impl Session {
let mut env = self.lisp_env_take();
value::set_string_budget(run.string_bytes, self.lisp.limits.string_bytes);
value::set_cell_limit(self.lisp.limits.cells.max(run.cells_at_start));
// What the routine feeds the command line is the program's input: the command it
// starts, even when another one is running and the token reaches
// [`Session::typed`] first, never opens a dialog. Restored after the slice, a panic
// in it included, so a person's later command keeps its own origin.
let program_input = std::mem::replace(&mut self.program_input, true);
let outcome = {
let machine = &mut run.machine;
let mut ctx = Ctx { s: self, env: &mut env, depth: 0 };
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| machine.run(&mut ctx, SLICE)))
};
self.program_input = program_input;
run.string_bytes = value::string_bytes_used();
let outcome = match outcome {
Ok(o) => o,
+5 -3
View File
@@ -70,7 +70,9 @@ fn items(p: &PickSet) -> Vec<Handle> {
/// selection set picks objects (a name, alone or with a point as `entsel` gives it, also answers
/// a prompt picking one object: [`Session::input_object`]), and `pause` waits for the user. A
/// command not finished by the arguments stays active for the next `command` call. No
/// arguments: cancel the active command.
/// arguments: cancel the active command. Whatever it feeds is the program's input
/// ([`crate::Origin::Program`]): the command it starts here, and the one a `'command` token
/// starts while another command runs, never open a dialog.
pub fn command(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
if a.is_empty() {
if ctx.s.running.is_some() {
@@ -91,7 +93,7 @@ pub fn command(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
}
Value::Str(s) => {
let r = if ctx.s.running.is_none() {
if s.trim().is_empty() { Ok(()) } else { ctx.s.start(s) }
if s.trim().is_empty() { Ok(()) } else { ctx.s.start_programmatic(s) }
} else if s.is_empty() {
ctx.s.input(Input::Enter)
} else {
@@ -813,7 +815,7 @@ fn interactive_ssget(ctx: &mut Ctx<'_>, filter: Option<Value>) -> Result<Flow, L
if ctx.s.running.is_some() {
return Ok(Flow::Value(Value::Nil));
}
if let Err(e) = ctx.s.start("select") {
if let Err(e) = ctx.s.start_programmatic("select") {
return Err(LispError::new(e.to_string()));
}
let f = super::eval::lookup(ctx.env, &super::value::Sym::new("SSGET"));
+61
View File
@@ -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`].
@@ -348,6 +362,11 @@ pub trait Interactive: Send {
fn display_only(&self, _s: &Session) -> Option<DisplayOnly> {
None
}
/// The attribute values the command waits for, all at once, when the UI should ask for them
/// in the Edit Attributes dialog (INSERT with ATTDIA 1). Typed answers still work.
fn attribute_entry(&self) -> Option<AttribEntry> {
None
}
}
/// See [`Interactive::display_only`]: the only things drawn in the current view while a command
@@ -389,6 +408,48 @@ pub enum EditorKind {
Dimension { measured: String },
}
/// See [`Interactive::attribute_entry`]: the block being inserted and the attributes asked for,
/// in order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AttribEntry {
pub block: String,
pub rows: Vec<AttribAsk>,
/// The drawing the command runs in ([`crate::DocState::uid`]) and its number in
/// [`Session::commands_started`], stamped by [`Session::attribute_entry`]: a dialog draft
/// belongs to one command, so a command started afterwards never takes it.
pub drawing: u64,
pub command: u64,
}
/// One attribute an INSERT asks for: its tag, prompt and default value; the value of a Verify
/// one is asked again once every value is in.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AttribAsk {
pub tag: String,
pub prompt: String,
pub default: String,
pub verify: bool,
}
impl AttribEntry {
/// An entry as the command builds it, before [`Session::attribute_entry`] stamps the drawing
/// and command number it belongs to.
pub(crate) fn idle(block: String, rows: Vec<AttribAsk>) -> Self {
AttribEntry { block, rows, drawing: 0, command: 0 }
}
/// The answers that give the attributes `values` (one per row, in order; a missing one is
/// the default) when typed in turn: every value, then each Verify attribute's again, as
/// INSERT asks them once the dialog has shown the values.
pub fn answers(&self, values: &[String]) -> Vec<String> {
let value = |i: usize| values.get(i).cloned().unwrap_or_else(|| self.rows.get(i).map(|r| r.default.clone()).unwrap_or_default());
let mut out: Vec<String> = (0..self.rows.len()).map(value).collect();
let verify: Vec<String> = self.rows.iter().enumerate().filter(|(_, r)| r.verify).map(|(i, _)| value(i)).collect();
out.extend(verify);
out
}
}
/// See [`Interactive::drag`].
#[derive(Clone, Debug)]
pub struct Drag {
+630 -12
View File
@@ -6,26 +6,64 @@ use cadcraft_geom::{Bounds2, Line, Vec2, point_in_polygon};
use crate::spatial::{self, SpatialIndex};
use crate::{Accept, Prompt};
/// A dimension kept as read whose graphics are a reference to its `*D` block (#3438).
fn draws_a_block(e: &Entity) -> bool {
matches!(&e.kind, EntityKind::Unknown(u) if u.graphics.iter().any(|g| matches!(g.kind, EntityKind::Insert(_))))
}
/// Polylines approximating an entity for hit testing, tessellated at `tol`.
pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec<Vec<Vec2>> {
if matches!(e.kind, EntityKind::Insert(_)) {
let list = insert_geometry(d, e, tol);
return list
.prims
.iter()
.flat_map(|p| match p.kind {
cadcraft_render::Kind::Tris | cadcraft_render::Kind::Mask => {
list.points(p).as_chunks::<3>().0.iter().map(|t| vec![t[0], t[1], t[2], t[0]]).collect()
}
cadcraft_render::Kind::Infinite { ray } => match list.points(p) {
[base, dir] => {
let far = 1e9;
vec![vec![if ray { *base } else { *base - *dir * far }, *base + *dir * far]]
}
_ => Vec::new(),
},
// An image's points are its unclipped corners: it is hit on the outline of what
// it shows, so a clipped-away part doesn't pick the reference.
cadcraft_render::Kind::Image { index } => match list.images.get(index as usize) {
Some(img) if img.clips.is_empty() => {
let [a, b, c, d] = img.corners();
vec![vec![a, b, c, d, a]]
}
Some(img) => shown_image_tris(img).as_chunks::<3>().0.iter().map(|t| vec![t[0], t[1], t[2], t[0]]).collect(),
None => Vec::new(),
},
_ => vec![list.points(p).to_vec()],
})
.collect();
}
match &e.kind {
EntityKind::Text(_)
| EntityKind::MText(_)
| EntityKind::Insert(_)
| EntityKind::Dimension(_)
| EntityKind::AttDef(_)
| EntityKind::Table(_)
| EntityKind::Tolerance(_)
| EntityKind::MLeader(_)
| EntityKind::Image(_) => {
// Text-like objects are hit inside their box.
| EntityKind::Image(_)
| EntityKind::Unknown(_)
if !matches!(e.kind, EntityKind::Unknown(_)) || draws_a_block(e) =>
{
// Text-like objects are hit inside their box; a dimension kept as read that draws its
// block, like a dimension.
let b = entity_bounds(d, e, 0);
if b.is_empty() {
return Vec::new();
}
let c = b.corners();
let mut v = vec![vec![c[0], c[1], c[2], c[3], c[0]]];
if matches!(e.kind, EntityKind::Dimension(_) | EntityKind::Insert(_) | EntityKind::MLeader(_)) {
if matches!(e.kind, EntityKind::Dimension(_) | EntityKind::MLeader(_)) || draws_a_block(e) {
let list = cadcraft_render::build_entities(
d,
std::iter::once(e),
@@ -84,6 +122,44 @@ pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec<Vec<Vec2>> {
}
}
fn insert_geometry(d: &Drawing, e: &Entity, tol: f64) -> cadcraft_render::DisplayList {
cadcraft_render::build_entities(d, std::iter::once(e), &cadcraft_render::Options { tolerance: tol, linetypes: false, ..Default::default() })
}
/// The part of an image its clips leave showing, as triangles (three points each); empty when a
/// clip has no outline to cut with.
fn shown_image_tris(img: &cadcraft_render::DImage) -> Vec<Vec2> {
let [a, b, c, d] = img.corners();
let mut tris = vec![a, b, c, a, c, d];
for outline in &img.clips {
let Some(clip) = cadcraft_render::clip::PolyClip::new(outline) else { return Vec::new() };
tris = clip.clip_triangles(&tris);
if tris.is_empty() {
break;
}
}
tris
}
fn insert_fill_hits_box(d: &Drawing, e: &Entity, bx: &Bounds2, tol: f64) -> bool {
let list = insert_geometry(d, e, tol);
list.prims.iter().any(|p| {
if let cadcraft_render::Kind::Image { index } = p.kind {
let Some(img) = list.images.get(index as usize) else { return false };
return !cadcraft_render::clip::clip_triangles(&shown_image_tris(img), bx).is_empty();
}
if !matches!(p.kind, cadcraft_render::Kind::Tris | cadcraft_render::Kind::Mask) {
return false;
}
list.points(p).as_chunks::<3>().0.iter().any(|t| {
let triangle = [t[0], t[1], t[2]];
bx.corners().iter().any(|q| point_in_polygon(&triangle, *q))
|| triangle.iter().any(|q| bx.contains(*q))
|| (0..3).any(|i| seg_hits_box(triangle[i], triangle[(i + 1) % 3], bx))
})
})
}
fn dist_to_polyline(pts: &[Vec2], p: Vec2) -> f64 {
if pts.len() == 1 {
return pts.first().map(|q| q.dist(p)).unwrap_or(f64::INFINITY);
@@ -97,7 +173,7 @@ pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 {
let mut best = polys.iter().map(|pl| dist_to_polyline(pl, p)).fold(f64::INFINITY, f64::min);
let filled = matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::Table(_))
|| matches!(e.kind, EntityKind::Tolerance(_));
if (filled && entity_bounds(d, e, 0).contains(p)) || in_text(d, e, p) {
if (filled && entity_bounds(d, e, 0).contains(p)) || in_blank_mtext(d, e, p) || in_text(d, e, p) {
best = 0.0;
}
// A solid hatch fills its loops with odd parity under its island style, as it is drawn, not
@@ -185,10 +261,125 @@ pub(crate) fn kept_as_read(k: &EntityKind) -> bool {
/// Entities to test, in the order to test them, each with its bounds when already known.
pub(crate) type Cands<'a> = Box<dyn Iterator<Item = (&'a Entity, Option<Bounds2>)> + 'a>;
pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option<Bounds2>) -> Bounds2 {
known.unwrap_or_else(|| entity_bounds(d, e, 0))
/// Whether an MTEXT's contents draw nothing (empty, or only spaces and `\~`): it has no glyph
/// strokes, and the document's bounds for it are empty so it stays out of the drawing extents.
/// Called for every MTEXT when the spatial index is built, so it does not allocate.
fn is_blank_mtext(t: &cadcraft_doc::MText) -> bool {
t.contents.split(r"\~").all(|s| s.chars().all(char::is_whitespace))
}
/// The frame a blank MTEXT is picked in (#2810), for a top-level MTEXT and for a multileader's
/// MTEXT content: its insertion point, rotation and the box before turning (`x0, x1, y0, y1`
/// about the insertion point): its width (the text height when it has none) by its text height,
/// placed by its attachment point, at the size it draws at the current annotation scale (the
/// shared `anno_scaled`, which also moves a multileader's text about its landing). `None` for any
/// other entity, a multileader without text content, a blank MTEXT without a usable size or
/// position, or an annotative one the current annotation scale hides.
fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> {
// Kind and blankness first: scaling clones the entity, so only blank text pays for it.
let text = match &e.kind {
EntityKind::MText(t) => t,
EntityKind::MLeader(m) => m.text.as_ref()?,
_ => return None,
};
if !is_blank_mtext(text) {
return None;
}
let f = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Plain => 1.0,
cadcraft_doc::AnnoDraw::Scaled(f) if f.is_finite() && f > 0.0 => f,
cadcraft_doc::AnnoDraw::Scaled(_) => 1.0,
cadcraft_doc::AnnoDraw::Hidden => return None,
};
let scaled;
let e = if f != 1.0 {
scaled = cadcraft_doc::anno_scaled(e, f);
&scaled
} else {
e
};
let t = match &e.kind {
EntityKind::MText(t) => t,
EntityKind::MLeader(m) => m.text.as_ref()?,
_ => return None,
};
if !t.height.is_finite() || t.height <= 0.0 || !t.insert.xy().is_finite() || !t.rotation.is_finite() {
return None;
}
let w = if t.width.is_finite() && t.width > 0.0 { t.width } else { t.height };
let h = t.height;
let insert = t.insert.xy();
if !w.is_finite() || !h.is_finite() || !insert.is_finite() {
return None;
}
let dx = match t.attach {
2 | 5 | 8 => -w / 2.0,
3 | 6 | 9 => -w,
_ => 0.0,
};
let top = match t.attach {
4..=6 => h / 2.0,
7..=9 => h,
_ => 0.0,
};
// A top-level MTEXT that matches the layout orientation is drawn upright (the renderer draws
// non-blank text that way), so its blank frame is too; a multileader keeps its text's stored rotation.
let rotation = if matches!(e.kind, EntityKind::MText(_)) && e.common.matches_layout_orientation() { 0.0 } else { t.rotation };
Some((insert, rotation, [dx, dx + w, top - h, top]))
}
/// The box around a blank MTEXT's turned frame (a top-level MTEXT or a multileader's MTEXT
/// content), for the spatial index and windows (a crossing window may catch a little extra near a
/// corner, as it does for other text).
fn blank_mtext_box(d: &Drawing, e: &Entity) -> Option<Bounds2> {
let (o, rot, [x0, x1, y0, y1]) = blank_mtext_frame(d, e)?;
let corners = [Vec2::new(x0, y1), Vec2::new(x1, y1), Vec2::new(x1, y0), Vec2::new(x0, y0)];
Some(Bounds2::from_points(corners.map(|c| o + c.rotate(rot))))
}
/// Whether `p` is on a blank MTEXT or a multileader's blank MTEXT content: inside its box turned
/// with the text, not the larger box around it.
fn in_blank_mtext(d: &Drawing, e: &Entity, p: Vec2) -> bool {
let Some((o, rot, [x0, x1, y0, y1])) = blank_mtext_frame(d, e) else { return false };
let q = (p - o).rotate(-rot);
q.x >= x0 && q.x <= x1 && q.y >= y0 && q.y <= y1
}
/// Drawn bounds extended by a blank MTEXT frame, including a multileader's text content.
/// Use the same bounds for a scan and for the spatial index.
pub(crate) fn pick_bounds(d: &Drawing, e: &Entity, drawn: Bounds2) -> Bounds2 {
match blank_mtext_box(d, e) {
Some(frame) => drawn.union(&frame),
None => drawn,
}
}
/// The insertion points snap's INS mode offers for a blank MTEXT or multileader (the stored
/// points); empty for any other entity.
fn blank_snap_points(e: &Entity) -> Vec<Vec2> {
// select.rs blank_snap_points must offer the same points as snap.rs's INS arms.
match &e.kind {
EntityKind::MText(t) if is_blank_mtext(t) => vec![t.insert.xy()],
EntityKind::MLeader(m) if m.text.as_ref().is_some_and(is_blank_mtext) => {
m.text.iter().map(|t| t.insert.xy()).chain(m.block.iter().map(|b| b.insert.xy())).collect()
}
_ => Vec::new(),
}
}
/// Whether `e` is within reach of a snap probe only through its blank MTEXT frame: the drawn
/// geometry (expanded by `aperture`) misses `probe`, and no insertion point INS would offer (text
/// or block content) is a candidate: one counts only when `ins` is on and it is within `aperture`
/// of `cursor`, the distance snap accepts a candidate by (a corner of the square probe is not).
/// Such an entity is for picking and selection, not a snap candidate.
pub(crate) fn blank_frame_only(d: &Drawing, e: &Entity, probe: &Bounds2, cursor: Vec2, aperture: f64, ins: bool) -> bool {
let points = blank_snap_points(e);
!points.is_empty() && !(ins && points.iter().any(|p| p.dist(cursor) <= aperture)) && !entity_bounds(d, e, 0).expand(aperture).intersects(probe)
}
pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option<Bounds2>) -> Bounds2 {
known.unwrap_or_else(|| pick_bounds(d, e, entity_bounds(d, e, 0)))
}
pub(crate) fn is_infinite(e: &Entity) -> bool {
matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_))
}
@@ -344,8 +535,15 @@ pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option<Bounds2>, bx: &Bo
pl.windows(2).any(|w| w.first().zip(w.get(1)).is_some_and(|(a, b)| seg_hits_box(*a, *b, bx)))
}
});
// A crossing box entirely inside a text/block bounding rectangle also selects it.
if hit || (eb.contains_box(bx) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Insert(_))) {
// A crossing box inside a text bounding rectangle selects the text.
if hit
|| (eb.contains_box(bx) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_)))
|| (matches!(e.kind, EntityKind::Insert(_)) && insert_fill_hits_box(d, e, bx, tol))
{
return true;
}
// Likewise inside a blank MTEXT's frame (a multileader's too), where picking also selects it.
if blank_mtext_box(d, e).is_some_and(|frame| frame.contains_box(bx)) {
return true;
}
// SOLID/TRACE are filled polygons. A crossing window wholly within the
@@ -557,7 +755,7 @@ impl SelectMode {
#[cfg(test)]
mod tests {
use super::*;
use cadcraft_doc::{Common, RayLine};
use cadcraft_doc::{Common, Image, Raster, RayLine};
use cadcraft_geom::Vec3;
fn fence_hits(kind: EntityKind, fence: [(f64, f64); 2]) -> usize {
@@ -600,6 +798,272 @@ mod tests {
assert_eq!(pick(&d, &Space::Model, Vec2::new(41.3, 50.0), 1.0), Some(line));
}
fn mtext_at(contents: &str, attach: u8, rotation: f64) -> EntityKind {
EntityKind::MText(cadcraft_doc::MText {
insert: Vec3::new(0.0, 0.0, 0.0),
height: 2.5,
width: 10.0,
attach,
rotation,
style: "Standard".into(),
contents: contents.into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
})
}
/// A blank MTEXT has no strokes and empty drawn bounds, but it is still an object: a click
/// inside its width x height box picks it, and a click outside does not (#2810).
#[test]
fn a_blank_mtext_is_picked_inside_its_box() {
let blank = |c: &str| matches!(mtext_at(c, 1, 0.0), EntityKind::MText(t) if is_blank_mtext(&t));
assert!(!blank(r"a\~"));
assert!(blank(r"\~ \~"));
for contents in ["", " ", r"\~ "] {
let mut d = Drawing::new_metric();
let h = d.add(&Space::Model, Common::default(), mtext_at(contents, 1, 0.0)).unwrap();
let at = |x: f64, y: f64| pick(&d, &Space::Model, Vec2::new(x, y), 0.1);
assert_eq!(at(5.0, -1.0), Some(h), "{contents:?}");
assert_eq!(at(0.5, -2.0), Some(h), "{contents:?}");
assert_eq!(at(5.0, 3.0), None, "above the box, {contents:?}");
assert_eq!(at(12.0, -1.0), None, "right of the box, {contents:?}");
assert_eq!(pick_all(&d, &Space::Model, Vec2::new(5.0, -1.0), 0.1), vec![h]);
let w = Bounds2::new(Vec2::new(4.0, -2.0), Vec2::new(6.0, -1.0));
assert_eq!(select_window(&d, &Space::Model, w, true), vec![h], "crossing {contents:?}");
}
}
#[test]
fn a_blank_mleader_text_is_picked_inside_its_box() {
for contents in [" ", ""] {
let mut s = crate::Session::new();
let result = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap();
let h = Handle::parse_hex(result["handle"].as_str().unwrap()).unwrap();
// The command omits the text object for an empty string. Preserve the box here to
// exercise a stored empty MTEXT, which can still exist in an imported MLEADER.
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") };
m.text.as_mut().unwrap().contents = contents.into();
})
.unwrap();
let d = s.doc().unwrap();
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
let t = m.text.as_ref().unwrap();
let p = t.insert.xy() + Vec2::new(t.height / 2.0, -t.height / 4.0);
let aperture = t.height / 100.0;
assert_eq!(pick(d, &Space::Model, p, aperture), Some(h), "{contents:?}");
let d = s.doc_mut().unwrap();
for i in 0..spatial::MIN_INDEXED {
let y = 100.0 + i as f64;
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(50.0, y, 0.0), b: Vec3::new(60.0, y, 0.0) });
d.add(&Space::Model, Common::default(), line).unwrap();
}
assert!(spatial::index(d, &Space::Model).is_some());
assert_eq!(pick(d, &Space::Model, p, aperture), Some(h), "indexed {contents:?}");
}
}
#[test]
fn a_pick_away_from_normal_mleader_text_and_lines_misses() {
let mut s = crate::Session::new();
let result = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 10]], "text": "Visible" })).unwrap();
let h = Handle::parse_hex(result["handle"].as_str().unwrap()).unwrap();
assert_eq!(pick(s.doc().unwrap(), &Space::Model, Vec2::new(2.0, 8.0), 0.05), None);
// Give the text a wide box: a click inside it, right of the glyphs and off the leader, is
// still a miss, since only blank text is picked by its frame.
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") };
m.text.as_mut().unwrap().width = 5.0;
})
.unwrap();
let d = s.doc().unwrap();
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
let t = m.text.as_ref().unwrap();
let p = t.insert.xy() + Vec2::new(t.width * 0.8, 0.0);
assert_eq!(pick(d, &Space::Model, p, 0.02), None, "right of the glyphs, inside the frame");
assert_eq!(pick(d, &Space::Model, t.insert.xy() + Vec2::new(0.3, 0.0), 0.02), Some(h), "on the glyphs");
}
/// Only blank MTEXT has a frame: an annotative non-blank MTEXT and an annotative LINE have none
/// (and the kind and blankness are decided before any annotation scaling).
#[test]
fn only_blank_mtext_has_a_frame_even_when_annotative() {
let mut d = Drawing::new_metric();
d.header.set_str("CANNOSCALE", "1:2");
let half = d.anno_scale("1:2").cloned().unwrap();
let common = || Common { anno_scales: vec![half.clone()], ..Common::default() };
let text = d.add(&Space::Model, common(), mtext_at("Visible", 1, 0.0)).unwrap();
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(5.0, 0.0, 0.0) });
let line = d.add(&Space::Model, common(), line).unwrap();
let blank = d.add(&Space::Model, common(), mtext_at(" ", 1, 0.0)).unwrap();
for (h, framed) in [(text, false), (line, false), (blank, true)] {
let e = d.entity(h).unwrap();
assert_eq!(blank_mtext_frame(&d, e).is_some(), framed);
}
}
/// A multileader whose text is blank, with the text 6 units right of the landing, 4 wide and
/// 2 high, attached top-left.
fn blank_mleader(s: &mut crate::Session) -> Handle {
let result = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap();
let h = Handle::parse_hex(result["handle"].as_str().unwrap()).unwrap();
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") };
let landing = m.landing;
let t = m.text.as_mut().unwrap();
t.insert = landing + Vec3::new(6.0, 0.0, 0.0);
t.width = 4.0;
t.height = 2.0;
t.attach = 1;
t.rotation = 0.0;
})
.unwrap();
h
}
/// A crossing window wholly inside a blank multileader text's box selects it, as a click does.
#[test]
fn a_crossing_window_inside_a_blank_mleader_text_box_selects_it() {
let mut s = crate::Session::new();
let h = blank_mleader(&mut s);
let d = s.doc().unwrap();
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
let o = m.text.as_ref().unwrap().insert.xy();
let inside = Bounds2::new(o + Vec2::new(1.0, -1.5), o + Vec2::new(2.0, -0.5));
assert_eq!(select_window(d, &Space::Model, inside, true), vec![h]);
let outside = Bounds2::new(o + Vec2::new(5.0, -1.5), o + Vec2::new(6.0, -0.5));
assert!(select_window(d, &Space::Model, outside, true).is_empty());
}
/// An annotative multileader's blank text is picked where it draws at the current annotation
/// scale: its size and its offset from the landing both scale.
#[test]
fn an_annotative_blank_mleader_text_is_picked_at_its_drawn_offset_and_size() {
let mut s = crate::Session::new();
let h = blank_mleader(&mut s);
let d = s.doc_mut().unwrap();
d.header.set_str("CANNOSCALE", "1:2");
let half = d.anno_scale("1:2").cloned().unwrap();
d.modify_entity(h, |e| e.common.anno_scales = vec![half]).unwrap();
let d = s.doc().unwrap();
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
let l = m.landing.xy();
// At 1:2 the box is 8 x 4 from the landing + (12, 0) (top-left): x 12..20, y -4..0.
let at = |x: f64, y: f64| pick(d, &Space::Model, l + Vec2::new(x, y), 0.02);
assert_eq!(at(16.0, -1.0), Some(h), "inside the scaled box, outside the unscaled one");
assert_eq!(at(19.5, -3.5), Some(h), "far corner of the scaled box");
assert_eq!(at(8.0, -1.0), None, "inside the unscaled box, outside the scaled one");
assert_eq!(at(22.0, -1.0), None, "right of the scaled box");
}
/// The box follows the attachment point and the rotation, and a width of 0 falls back to the
/// text height.
#[test]
fn a_blank_mtext_box_follows_attachment_and_rotation() {
let mut d = Drawing::new_metric();
// Middle-centre: the box spans x -5..5, y -1.25..1.25.
let h = d.add(&Space::Model, Common::default(), mtext_at(" ", 5, 0.0)).unwrap();
let at = |d: &Drawing, x: f64, y: f64| pick(d, &Space::Model, Vec2::new(x, y), 0.05);
assert_eq!(at(&d, -4.0, 1.0), Some(h));
assert_eq!(at(&d, 4.0, -1.0), Some(h));
assert_eq!(at(&d, 4.0, 2.0), None);
// Turned a quarter turn about the insertion point: the box spans x -1.25..1.25, y -5..5.
let mut d = Drawing::new_metric();
let h = d.add(&Space::Model, Common::default(), mtext_at(" ", 5, std::f64::consts::FRAC_PI_2)).unwrap();
assert_eq!(at(&d, 1.0, 4.0), Some(h));
assert_eq!(at(&d, 4.0, 1.0), None);
// No width: as wide as the text is high.
let mut d = Drawing::new_metric();
let EntityKind::MText(mut t) = mtext_at("", 1, 0.0) else { panic!("mtext") };
t.width = 0.0;
let h = d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
assert_eq!(at(&d, 2.0, -1.0), Some(h));
assert_eq!(at(&d, 5.0, -1.0), None);
}
/// A top-level MTEXT that matches the layout orientation is drawn upright, ignoring its stored
/// rotation, so its frame is the unturned one (the renderer and the extents do the same).
#[test]
fn rotated_blank_mtext_matching_layout_orientation_is_picked_in_its_unrotated_frame() {
let mut d = Drawing::new_metric();
let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() };
let common = Common { xdata: vec![tag(1001, "AcadAnnoPO"), tag(1070, "1")], ..Common::default() };
let h = d.add(&Space::Model, common, mtext_at(" ", 1, std::f64::consts::FRAC_PI_2)).unwrap();
let at = |x: f64, y: f64| pick(&d, &Space::Model, Vec2::new(x, y), 0.05);
// Unrotated frame x 0..10, y -2.5..0; the rotated one would be x 0..2.5, y 0..10.
assert_eq!(at(5.0, -1.0), Some(h), "inside the unrotated frame");
assert_eq!(at(1.0, 5.0), None, "inside only the rotated frame");
}
/// A turned blank MTEXT is hit in its turned box, not in the axis-aligned box around it (whose
/// empty corners lie off the text).
#[test]
fn a_turned_blank_mtext_is_picked_in_its_turned_box() {
let mut d = Drawing::new_metric();
let h = d.add(&Space::Model, Common::default(), mtext_at(" ", 1, 30f64.to_radians())).unwrap();
let at = |x: f64, y: f64| pick(&d, &Space::Model, Vec2::new(x, y), 0.05);
// Local (5, -1.25), the centre of the box.
assert_eq!(at(4.955, 1.418), Some(h));
// Inside the box around the turned one, but local (2.87, 2.96) is above the text.
assert_eq!(at(1.0, 4.0), None);
}
/// An annotative blank MTEXT is picked in the box it draws at the current annotation scale,
/// and not at all while that scale hides it.
#[test]
fn an_annotative_blank_mtext_is_picked_at_its_drawn_size() {
let mut d = Drawing::new_metric();
d.header.set_str("CANNOSCALE", "1:2");
let half = d.anno_scale("1:2").cloned().unwrap();
let common = Common { anno_scales: vec![half], ..Common::default() };
// Middle-centre at 1:2: twice the size, x -10..10, y -2.5..2.5.
let h = d.add(&Space::Model, common, mtext_at(" ", 5, 0.0)).unwrap();
let at = |d: &Drawing, x: f64, y: f64| pick(d, &Space::Model, Vec2::new(x, y), 0.05);
assert_eq!(at(&d, 8.0, 2.0), Some(h), "inside the scaled box");
assert_eq!(at(&d, 11.0, 0.0), None, "outside the scaled box");
let w = Bounds2::new(Vec2::new(7.0, 1.0), Vec2::new(9.0, 2.0));
assert_eq!(select_window(&d, &Space::Model, w, true), vec![h], "crossing the scaled box");
// At 1:1 with only supported scales shown, the object is hidden: nothing to pick.
d.header.set_str("CANNOSCALE", "1:1");
d.header.set_i64("ANNOALLVISIBLE", 0);
assert_eq!(at(&d, 0.0, 0.0), None, "hidden");
let w = Bounds2::new(Vec2::new(-1.0, -1.0), Vec2::new(1.0, 1.0));
assert!(select_window(&d, &Space::Model, w, true).is_empty(), "hidden, crossing");
}
/// A drawing large enough for the spatial index must still offer a blank MTEXT as a candidate.
#[test]
fn a_blank_mtext_is_picked_in_an_indexed_drawing() {
let mut d = Drawing::new_metric();
for i in 0..(crate::spatial::MIN_INDEXED + 10) {
let y = 100.0 + i as f64;
let l = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(50.0, y, 0.0), b: Vec3::new(60.0, y, 0.0) });
d.add(&Space::Model, Common::default(), l).unwrap();
}
let h = d.add(&Space::Model, Common::default(), mtext_at("", 1, 0.0)).unwrap();
assert!(spatial::index(&d, &Space::Model).is_some());
assert_eq!(pick(&d, &Space::Model, Vec2::new(5.0, -1.0), 0.1), Some(h));
assert_eq!(pick(&d, &Space::Model, Vec2::new(5.0, 3.0), 0.1), None);
}
/// Text with words is still picked by its drawn box only.
#[test]
fn a_click_far_from_a_normal_mtext_misses() {
let mut d = Drawing::new_metric();
let h = d.add(&Space::Model, Common::default(), mtext_at("AB", 1, 0.0)).unwrap();
assert_eq!(pick(&d, &Space::Model, Vec2::new(1.0, -1.0), 0.1), Some(h));
assert_eq!(pick(&d, &Space::Model, Vec2::new(8.0, -1.0), 0.1), None);
assert_eq!(pick(&d, &Space::Model, Vec2::new(1.0, 5.0), 0.1), None);
}
/// An OLE2FRAME draws as its frame, so a click on an edge picks it (review on #2587); a click in
/// the middle of the frame, or on a frame without both corners, does not.
#[test]
@@ -652,8 +1116,8 @@ mod tests {
let e = d.entity(h).unwrap();
let drawn = cadcraft_render::build_entities(&d, std::iter::once(e.as_ref()), &cadcraft_render::Options { text: false, ..Default::default() });
assert!(drawn.prims.len() > 10_000, "the pattern draws {} dashes", drawn.prims.len());
// The line, and the block's bounding rectangle.
assert_eq!(hit_polylines(&d, e, 0.01).len(), 2);
// Hit testing uses the line without laying out every dash.
assert_eq!(hit_polylines(&d, e, 0.01).len(), 1);
}
/// A dashed line in a block is hit across its gaps, as one outside a block is.
@@ -668,6 +1132,126 @@ mod tests {
let gap = end + (start - end) * 0.5;
assert_eq!(pick(&d, &Space::Model, gap, end.dist(start) / 8.0), Some(h));
}
#[test]
fn crossing_a_transformed_block_requires_its_drawn_geometry() {
let mut d = Drawing::new_metric();
let mut block = cadcraft_doc::Block::new("two lines");
for y in [0.0, 5.0] {
block.entities.push(Entity::new(
Handle(10 + y as u64),
EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) }),
));
}
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
let insert = cadcraft_doc::Insert {
block: "two lines".into(),
insert: Vec3::new(30.0, 40.0, 0.0),
scale: Vec3::new(2.0, 2.0, 1.0),
rotation: std::f64::consts::FRAC_PI_2,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
let bx = |a, b| Bounds2::new(a, b);
let empty = bx(Vec2::new(24.0, 48.0), Vec2::new(26.0, 52.0));
let crossed = bx(Vec2::new(19.0, 48.0), Vec2::new(21.0, 52.0));
assert!(select_window(&d, &Space::Model, empty, true).is_empty());
assert_eq!(select_window(&d, &Space::Model, crossed, true), vec![h]);
assert!(select_window(&d, &Space::Model, crossed, false).is_empty());
assert_eq!(pick(&d, &Space::Model, Vec2::new(25.0, 40.0), 0.1), None);
}
#[test]
fn crossing_a_block_fill_uses_the_filled_shape() {
let mut d = Drawing::new_metric();
let mut block = cadcraft_doc::Block::new("filled triangle");
let a = Vec3::new(0.0, 0.0, 0.0);
let b = Vec3::new(10.0, 0.0, 0.0);
let c = Vec3::new(0.0, 10.0, 0.0);
block.entities.push(Entity::new(Handle(10), EntityKind::Solid(cadcraft_doc::Solid { corners: [a, b, c, c] })));
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
let insert = cadcraft_doc::Insert {
block: "filled triangle".into(),
insert: Vec3::new(0.0, 0.0, 0.0),
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
let empty = Bounds2::new(Vec2::new(7.0, 7.0), Vec2::new(8.0, 8.0));
let filled = Bounds2::new(Vec2::new(2.0, 2.0), Vec2::new(3.0, 3.0));
assert!(select_window(&d, &Space::Model, empty, true).is_empty());
assert_eq!(select_window(&d, &Space::Model, filled, true), vec![h]);
}
#[test]
fn crossing_a_block_ray_and_xline_uses_their_direction() {
for (kind, behind) in [(true, false), (false, true)] {
let mut d = Drawing::new_metric();
let mut block = cadcraft_doc::Block::new("infinite");
let line = RayLine { base: Vec3::new(100.0, 100.0, 0.0), dir: Vec3::new(1.0, 0.0, 0.0) };
block.entities.push(Entity::new(Handle(10), if kind { EntityKind::Ray(line) } else { EntityKind::XLine(line) }));
block
.entities
.push(Entity::new(Handle(11), EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(200.0, 0.0, 0.0) })));
block.entities.push(Entity::new(
Handle(12),
EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(200.0, 0.0, 0.0), b: Vec3::new(200.0, 200.0, 0.0) }),
));
block.entities.push(Entity::new(
Handle(13),
EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(200.0, 200.0, 0.0), b: Vec3::new(0.0, 200.0, 0.0) }),
));
block
.entities
.push(Entity::new(Handle(14), EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 200.0, 0.0), b: Vec3::new(0.0, 0.0, 0.0) })));
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
let insert = cadcraft_doc::Insert { block: "infinite".into(), ..Default::default() };
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
let ahead = Bounds2::new(Vec2::new(149.0, 99.0), Vec2::new(151.0, 101.0));
let back = Bounds2::new(Vec2::new(49.0, 99.0), Vec2::new(51.0, 101.0));
assert_eq!(select_window(&d, &Space::Model, ahead, true), vec![h]);
assert_eq!(select_window(&d, &Space::Model, back, true).contains(&h), behind);
}
}
#[test]
fn crossing_a_block_image_respects_its_clip() {
let mut d = Drawing::new_metric();
d.rasters.insert("map.png", std::sync::Arc::new(Raster::new(2, 2, vec![255; 16]).unwrap()));
let mut block = cadcraft_doc::Block::new("picture");
block.entities.push(Entity::new(
Handle(10),
EntityKind::Image(Image {
insert: Vec3::ZERO,
u: Vec3::new(5.0, 0.0, 0.0),
v: Vec3::new(0.0, 5.0, 0.0),
size: Vec2::new(2.0, 2.0),
path: "map.png".into(),
clipping: true,
clip: vec![Vec2::new(-0.5, -0.5), Vec2::new(0.5, 1.5)],
..Default::default()
}),
));
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
let h = d
.add(&Space::Model, Common::default(), EntityKind::Insert(cadcraft_doc::Insert { block: "picture".into(), ..Default::default() }))
.unwrap();
let visible = Bounds2::new(Vec2::new(2.0, 4.0), Vec2::new(3.0, 6.0));
let hidden = Bounds2::new(Vec2::new(7.0, 4.0), Vec2::new(8.0, 6.0));
assert_eq!(select_window(&d, &Space::Model, visible, true), vec![h]);
assert!(select_window(&d, &Space::Model, hidden, true).is_empty());
}
}
#[cfg(test)]
@@ -817,4 +1401,38 @@ mod hatch_pattern_pick_tests {
let d = solid_hatch(loops(), 2);
assert!(pick(&d, &Space::Model, Vec2::new(5.0, 5.0), 0.05).is_some());
}
/// A window around everything a blank multileader draws (its geometry and its text frame)
/// selects it, at either annotation scale: the stored insertion points snap offers do not
/// widen the box a window has to contain (#2810).
#[test]
fn window_around_a_blank_multileader_still_selects_it() {
use cadcraft_geom::Vec3;
for scale in ["1:2", "2:1"] {
let mut s = crate::Session::new();
let r = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
let d = s.doc_mut().unwrap();
d.header.set_str("CANNOSCALE", scale);
let sc = d.anno_scale(scale).cloned().unwrap();
d.modify_entity(h, |e| {
e.common.anno_scales = vec![sc];
let EntityKind::MLeader(m) = &mut e.kind else { return };
let landing = m.landing;
if let Some(t) = m.text.as_mut() {
t.insert = landing + Vec3::new(6.0, 0.0, 0.0);
t.width = 4.0;
t.height = 2.0;
t.attach = 1;
t.rotation = 0.0;
}
})
.unwrap();
let d = &*d;
let e = d.entity(h).unwrap();
let frame = blank_mtext_box(d, e).expect("a blank multileader has a frame");
let bx = entity_bounds(d, e, 0).union(&frame).expand(0.01);
assert!(select_window(d, &Space::Model, bx, false).contains(&h), "scale {scale}");
}
}
}
+2 -2
View File
@@ -3,8 +3,8 @@ use super::error::{EngineError, Result};
use super::running::{PendingWindow, Running};
use super::view::View;
use super::{
Arc, Bounds2, Drag, Drawing, Entity, Handle, Input, Prompt, Session, Space, Step, Value, Vec2, assoc, cmd, find_command, guard, lisp, pointmod,
prompt, select, snap, sysvars, units,
Arc, Bounds2, Drag, Drawing, Entity, Handle, Input, Origin, Prompt, Session, Space, Step, Value, Vec2, assoc, cmd, find_command, guard, lisp,
pointmod, prompt, select, snap, sysvars, units,
};
mod cmdline;
+48 -5
View File
@@ -1,8 +1,8 @@
use crate::DisplayOnly;
use super::{
Arc, Bounds2, Drag, Drawing, EngineError, Entity, Handle, Input, PendingWindow, Prompt, Result, Running, Session, Snapshot, Step, Value, Vec2,
assoc, cmd, find_command, guard, pointmod, select, snap, sysvars,
Arc, Bounds2, Drag, Drawing, EngineError, Entity, Handle, Input, Origin, PendingWindow, Prompt, Result, Running, Session, Snapshot, Step, Value,
Vec2, assoc, cmd, find_command, guard, pointmod, select, snap, sysvars,
};
impl Session {
@@ -41,8 +41,29 @@ impl Session {
blocks.keys().find(|k| *k == word).or_else(|| blocks.keys().find(|k| same(k))).cloned()
}
/// Start a command by name or alias as if typed at the command line.
/// Who started the command running now ([`Origin`]): fixed when it started, so a scripted or
/// LISP-started command keeps its origin while it prompts.
pub fn command_origin(&self) -> Origin {
self.command_origin
}
/// Start a command by name or alias as if typed at the command line. A script's commands are
/// the program's ([`Origin::Program`]), as those of [`Session::start_programmatic`] are, and so
/// is a command started by a token a LISP routine feeds through [`Session::typed`]: `(command
/// "LINE" "0,0" "'-INSERT" …)` replaces LINE with an INSERT the routine started.
pub fn start(&mut self, name: &str) -> Result<()> {
let origin = if self.in_script || self.program_input { Origin::Program } else { Origin::Person };
self.start_from(name, origin)
}
/// Start a command as a program does: an AutoLISP `(command …)` cannot answer a dialog, so
/// none opens for what it starts, even after the routine ends.
pub fn start_programmatic(&mut self, name: &str) -> Result<()> {
self.start_from(name, Origin::Program)
}
/// [`Session::start`] with the command's origin recorded for its whole life.
fn start_from(&mut self, name: &str, origin: Origin) -> Result<()> {
self.last_polar = None;
self.pick_hint = None;
let name = name.trim();
@@ -74,7 +95,7 @@ impl Session {
// A bare system variable name (ORTHOMODE, GRIDMODE…) acts as SETVAR on that variable.
let var = lower.to_ascii_uppercase();
if !name.starts_with(['_', '.', '-']) && sysvars::get(self, &var).is_some() {
self.start(if transparent { "'setvar" } else { "setvar" })?;
self.start_from(if transparent { "'setvar" } else { "setvar" }, origin)?;
return self.input(Input::Text(var));
}
return Err(EngineError::UnknownCommand(typed.to_string()));
@@ -101,10 +122,15 @@ impl Session {
return self.input(Input::Keyword("Undo".into()));
}
if !nested {
self.commands_started = self.commands_started.wrapping_add(1);
// The command this one replaces is cancelled first: its cancellation can run a paused
// LISP routine's `*error*` handler, and a handler that starts a command records that
// command's Program origin. Origin and number go in after it, so they describe this
// start and the factory below still sees the origin this command was started with.
if self.running.is_some() {
self.cancel();
}
self.commands_started = self.commands_started.wrapping_add(1);
self.command_origin = origin;
}
(spec.enabled)(self).map_err(|m| EngineError::Disabled(spec.id.into(), m))?;
if let Some(why) = cmd::blocks::bedit::refused_in_editor(self, spec.id) {
@@ -541,6 +567,17 @@ impl Session {
self.running.as_ref().and_then(|r| r.machine.text_editor())
}
/// The attribute values the running command asks for in the Edit Attributes dialog
/// ([`Interactive::attribute_entry`]), stamped with the drawing it runs in and its number in
/// [`Session::commands_started`]: a dialog draft kept for a cancelled command never belongs
/// to the one started after it, even for the same block.
pub fn attribute_entry(&self) -> Option<crate::AttribEntry> {
let mut entry = self.running.as_ref().and_then(|r| r.machine.attribute_entry())?;
entry.drawing = self.docs.get(self.active).map_or(0, |d| d.uid);
entry.command = self.commands_started;
Some(entry)
}
pub fn current_prompt(&self) -> Option<Prompt> {
if let Some(p) = self.lisp_prompt() {
return Some(p);
@@ -608,6 +645,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.
+4
View File
@@ -138,6 +138,9 @@ pub struct Settings {
/// ATTREQ: 0 inserts blocks with their attributes' default values instead of asking for them
/// (default: 1).
pub attreq: bool,
/// ATTDIA: INSERT typed or from a menu asks for attribute values in the Edit Attributes
/// dialog; on by default, as in AutoCAD (Initial value 1).
pub attdia: bool,
}
impl Default for Settings {
@@ -205,6 +208,7 @@ impl Default for Settings {
ucs_angle: 0.0,
auditctl: false,
attreq: true,
attdia: true,
}
}
}
+274 -18
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;
@@ -385,7 +385,7 @@ fn osnap_in_with_prims(
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?;
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).
@@ -475,9 +475,60 @@ 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. Objects on the layers `frozen` in the active viewport aren't drawn there,
/// so they are passed over.
pub(crate) fn nearest_with_direction(
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
frozen: &[String],
skip: Handle,
) -> Option<(Vec2, Vec2)> {
let ix = crate::spatial::index(d, space);
let (_, prims) = gather_in(d, space, &ix, cursor, aperture, 0, frozen, 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, ray } = p {
let len = dir.len();
if len > 1e-12 {
let u = *dir * (1.0 / len);
// A ray runs one way from its base: behind it, its base is the nearest point.
let t = (cursor - *base).dot(u);
consider(*base + u * if *ray { t.max(0.0) } else { t }, 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,
@@ -486,6 +537,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();
@@ -493,13 +545,19 @@ 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);
if !inf && !crate::select::bounds_of(d, e, known).expand(aperture).intersects(&probe) {
continue;
}
// A blank MTEXT frame covering the cursor is for picking: it neither uses up the candidate
// limit nor the intersection slots unless its drawn geometry is in reach, or INS is on and an
// insertion point is within the aperture.
if !inf && crate::select::blank_frame_only(d, e, &probe, cursor, aperture, osmode & mode::INS != 0) {
continue;
}
count += 1;
if count > 2000 {
break;
@@ -515,6 +573,7 @@ fn gather_in(
}
EntityKind::AttDef(a) => cands.push((mode::INS, a.text.justify_point())),
// A multileader: its text's insertion point, or its block content's.
// select.rs blank_snap_points must offer the same points.
EntityKind::MLeader(m) => {
cands.extend(m.text.iter().map(|t| (mode::INS, t.insert.xy())));
cands.extend(m.block.iter().map(|b| (mode::INS, b.insert.xy())));
@@ -531,6 +590,15 @@ fn gather_in(
if let EntityKind::Dimension(dm) = &e.kind {
sink.dimension(d, dm, &mut budget, frozen);
}
// A dimension kept as read draws its block through a reference in its graphics (#3438),
// and snaps to the objects inside it the same way.
if let EntityKind::Unknown(u) = &e.kind {
for g in &u.graphics {
if let EntityKind::Insert(ins) = &g.kind {
block_leaves(d, ins, &Mat3::IDENTITY, 0, &mut budget, frozen, &mut |k, m| sink.object(k, Some(m)));
}
}
}
}
Some((cands, near_prims))
}
@@ -772,20 +840,7 @@ impl Sink<'_> {
fn dimension(&mut self, d: &Drawing, dm: &cadcraft_doc::Dimension, budget: &mut usize, frozen: &[String]) {
match dm.block.as_ref().and_then(|n| d.block(n)) {
Some(blk) => {
// The block holds world geometry: a reference at its own base point places it as is.
let ins = Insert {
block: blk.name.clone(),
insert: blk.base,
scale: cadcraft_geom::Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
block_leaves(d, &ins, &Mat3::IDENTITY, 0, budget, frozen, &mut |k, m| self.object(k, Some(m)));
block_leaves(d, &dimension_reference(blk, dm), &Mat3::IDENTITY, 0, budget, frozen, &mut |k, m| self.object(k, Some(m)));
}
None => {
let g = cadcraft_render::dimension_in(d, dm);
@@ -862,6 +917,18 @@ fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut
match &be.kind {
EntityKind::AttDef(_) => {}
EntityKind::Insert(inner) => block_leaves(d, inner, &mm, depth + 1, budget, frozen, f),
// A dimension draws its block, as at the top level.
EntityKind::Dimension(dm) if let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n)) => {
block_leaves(d, &dimension_reference(blk, dm), &mm, depth + 1, budget, frozen, f);
}
k @ EntityKind::Unknown(u) => {
f(k, &mm);
for g in &u.graphics {
if let EntityKind::Insert(inner) = &g.kind {
block_leaves(d, inner, &mm, depth + 1, budget, frozen, f);
}
}
}
k => f(k, &mm),
}
}
@@ -869,6 +936,24 @@ fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut
}
}
/// The reference that places a dimension's block as the renderer draws it: the block holds world
/// geometry, moved by the insertion point (DXF group 12, which an older AutoCAD sets for a moved
/// dimension; #2634).
fn dimension_reference(blk: &cadcraft_doc::Block, dm: &cadcraft_doc::Dimension) -> Insert {
Insert {
block: blk.name.clone(),
insert: blk.base + dm.insertion_point,
scale: cadcraft_geom::Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}
}
/// Whether `p` comes within `aperture` of the box `probe`.
fn prim_near(p: &Prim, probe: &Bounds2, aperture: f64) -> bool {
let b = match p {
@@ -1171,6 +1256,27 @@ mod tests {
d
}
#[test]
fn alignment_targets_stay_on_a_ray_and_off_frozen_layers() {
let mut d = Drawing::new_imperial();
let ray = |base: (f64, f64)| EntityKind::Ray(cadcraft_doc::RayLine { base: Vec3::new(base.0, base.1, 0.0), dir: Vec3::new(1.0, 0.0, 0.0) });
d.add(&Space::Model, Common::default(), ray((0.0, 0.0))).unwrap();
// Behind the ray: its base is the nearest point, out of a small aperture.
assert_eq!(nearest_with_direction(&d, &Space::Model, Vec2::new(-5.0, 0.0), 0.5, &[], Handle(0)), None);
let (at, _) = nearest_with_direction(&d, &Space::Model, Vec2::new(-0.2, 0.1), 0.5, &[], Handle(0)).unwrap();
assert!(at.dist(Vec2::ZERO) < 1e-12, "{at:?}");
let (at, _) = nearest_with_direction(&d, &Space::Model, Vec2::new(5.0, 0.1), 0.5, &[], Handle(0)).unwrap();
assert!(at.dist(Vec2::new(5.0, 0.0)) < 1e-12, "{at:?}");
// A line on a layer frozen in the viewport isn't a target.
let mut d = drawing();
d.ensure_layer("Hidden");
let c = Common { layer: "Hidden".into(), ..Common::default() };
let l = EntityKind::Line(Line { a: Vec3::new(0.0, 30.0, 0.0), b: Vec3::new(10.0, 30.0, 0.0) });
d.add(&Space::Model, c, l).unwrap();
assert!(nearest_with_direction(&d, &Space::Model, Vec2::new(5.0, 30.1), 0.5, &[], Handle(0)).is_some());
assert_eq!(nearest_with_direction(&d, &Space::Model, Vec2::new(5.0, 30.1), 0.5, &["HIDDEN".to_string()], Handle(0)), None);
}
#[test]
fn endpoint_and_mid() {
let d = drawing();
@@ -1180,6 +1286,156 @@ mod tests {
assert_eq!(m.point, Vec2::new(5.0, 0.0));
}
/// Blank MTEXT frames over the cursor are for picking: thousands of them, with their insertion
/// points out of reach, must not crowd a real endpoint out of the snap candidates (#2810).
#[test]
fn blank_mtext_frames_do_not_crowd_out_snap_candidates() {
for line_first in [true, false] {
let mut d = Drawing::new_metric();
let line = EntityKind::Line(Line { a: Vec3::new(5.2, -1.0, 0.0), b: Vec3::new(30.0, -1.0, 0.0) });
if line_first {
d.add(&Space::Model, Common::default(), line.clone()).unwrap();
}
for _ in 0..2100 {
let t = cadcraft_doc::MText {
insert: Vec3::new(0.0, 0.0, 0.0),
height: 2.5,
width: 10.0,
attach: 1,
rotation: 0.0,
style: "Standard".into(),
contents: " ".into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
};
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
}
if !line_first {
d.add(&Space::Model, Common::default(), line).unwrap();
}
// The cursor is inside every box (x 0..10, y -2.5..0), 0.2 from the line's end.
let h = osnap(&d, &Space::Model, Vec2::new(5.0, -1.0), 0.5, mode::END, None, false).unwrap();
assert_eq!(h.point, Vec2::new(5.2, -1.0), "line first: {line_first}");
// A blank MTEXT whose insertion point is in the aperture keeps its INS snap.
let h = osnap(&d, &Space::Model, Vec2::new(0.1, -0.1), 0.5, mode::INS, None, false).unwrap();
assert_eq!(h.point, Vec2::new(0.0, 0.0), "line first: {line_first}");
}
}
/// 2001 blank MTEXT frames covering `cursor` (insertion points at `ins_at`), drawn before a
/// LINE whose end is at `cursor`: the END snap found with `osmode`.
fn crowded_blank_frames_end_snap(ins_at: Vec2, cursor: Vec2, aperture: f64, osmode: u32) -> Option<Vec2> {
let mut d = Drawing::new_metric();
for _ in 0..2001 {
let t = cadcraft_doc::MText {
insert: Vec3::new(ins_at.x, ins_at.y, 0.0),
height: 2.5,
width: 10.0,
attach: 1,
rotation: 0.0,
style: "Standard".into(),
contents: " ".into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
};
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
}
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::new(cursor.x, cursor.y, 0.0), b: Vec3::new(30.0, cursor.y, 0.0) }))
.unwrap();
osnap(&d, &Space::Model, cursor, aperture, osmode, None, false).map(|h| h.point)
}
/// An insertion point in a corner of the square probe is farther than the aperture from the
/// cursor, so snap would never accept it: its frame must not crowd out an END snap.
#[test]
fn blank_insertion_points_in_the_probe_corner_do_not_crowd_out_an_end_snap() {
let cursor = Vec2::new(5.0, -1.0);
let ap = 0.5;
let corner = Vec2::new(cursor.x - 0.9 * ap, cursor.y + 0.9 * ap);
assert!(corner.dist(cursor) > ap, "outside the circle, inside the square probe");
assert_eq!(crowded_blank_frames_end_snap(corner, cursor, ap, mode::END | mode::INS), Some(cursor));
}
/// With INS off a blank MTEXT's insertion point is no snap candidate, even right at the cursor.
#[test]
fn blank_insertion_points_with_ins_off_do_not_crowd_out_an_end_snap() {
let cursor = Vec2::new(5.0, -1.0);
assert_eq!(crowded_blank_frames_end_snap(cursor, cursor, 0.5, mode::END), Some(cursor));
}
/// A blank annotative multileader (text 6 right of its landing, 4 x 2, at 1:2) among 2100 blank
/// MTEXT frames over the cursor. `block_at` also gives it a block content at that offset from
/// the landing. Returns the INS snap at `landing + probe` (aperture 0.5).
fn crowded_blank_mleader_ins(block_at: Option<f64>, probe: Vec2) -> Option<Vec2> {
let mut s = crate::Session::new();
let r = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap();
let h = cadcraft_doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
let landing = {
let d = s.doc_mut().unwrap();
if block_at.is_some() {
// A block whose geometry (a line 60 long) covers its base point, at the stored insertion
// and, drawn at 1:2 about the landing, at the scaled one too.
let mut blk = cadcraft_doc::Block::new("BLK");
let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(60.0, 0.0, 0.0) });
blk.entities.push(cadcraft_doc::Entity::new(cadcraft_doc::Handle(1), line));
d.blocks.insert("BLK".into(), std::sync::Arc::new(blk));
}
d.header.set_str("CANNOSCALE", "1:2");
let half = d.anno_scale("1:2").cloned().unwrap();
d.modify_entity(h, |e| {
e.common.anno_scales = vec![half];
let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") };
let landing = m.landing;
let t = m.text.as_mut().unwrap();
t.insert = landing + Vec3::new(6.0, 0.0, 0.0);
t.width = 4.0;
t.height = 2.0;
t.attach = 1;
t.rotation = 0.0;
if let Some(x) = block_at {
m.block = Some(cadcraft_doc::Insert {
block: "BLK".into(),
insert: landing + Vec3::new(x, 0.0, 0.0),
scale: Vec3::new(1.0, 1.0, 1.0),
..Default::default()
});
}
})
.unwrap();
let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") };
m.landing.xy()
};
let cursor = landing + probe;
// Blank frames (10 x 2.5, top-left at the insert) cover the cursor; their inserts do not.
let d = s.doc_mut().unwrap();
for _ in 0..2100 {
let t = cadcraft_doc::MText {
insert: Vec3::new(cursor.x - 5.0, cursor.y + 1.0, 0.0),
height: 2.5,
width: 10.0,
attach: 1,
rotation: 0.0,
style: "Standard".into(),
contents: " ".into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
};
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
}
osnap(d, &Space::Model, cursor, 0.5, mode::INS, None, false).map(|h| h.point - landing)
}
/// An annotative blank multileader keeps its INS snap (the stored, unscaled insertion point)
/// among thousands of blank frames, and so does its block content.
#[test]
fn annotative_blank_mleader_keeps_its_ins_snaps_among_blank_frames() {
assert_eq!(crowded_blank_mleader_ins(None, Vec2::new(6.1, -0.1)), Some(Vec2::new(6.0, 0.0)), "text");
assert_eq!(crowded_blank_mleader_ins(Some(30.0), Vec2::new(30.1, -0.1)), Some(Vec2::new(30.0, 0.0)), "block");
}
#[test]
fn intersection() {
let d = drawing();
+2 -1
View File
@@ -53,7 +53,8 @@ impl ChunkIx {
if matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_)) {
infinite.push(u32::try_from(i).unwrap_or(u32::MAX));
}
entity_bounds_cached(d, e, 0, &mut cache)
let b = entity_bounds_cached(d, e, 0, &mut cache);
crate::select::pick_bounds(d, e, b)
})
.collect();
let serial = NEXT_SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+4 -1
View File
@@ -89,8 +89,11 @@ const LINEWEIGHTS: [i64; 24] = [0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53,
/// On/off session settings: name, read, write.
type Toggle = (&'static str, fn(&Settings) -> bool, fn(&mut Settings, bool));
const SETTINGS: &[Toggle] = &[
("AUDITCTL", |s| s.auditctl, |s, v| s.auditctl = v),
// ATTDIA 1 (the default): INSERT typed or from a menu asks for attribute values in the Edit
// Attributes dialog; 0: at the command line. ATTREQ 0: INSERT gives every attribute its default.
("ATTDIA", |s| s.attdia, |s, v| s.attdia = v),
("ATTREQ", |s| s.attreq, |s, v| s.attreq = v),
("AUDITCTL", |s| s.auditctl, |s, v| s.auditctl = v),
("TRANSPARENCYDISPLAY", |s| s.transparency_display, |s, v| s.transparency_display = v),
];
+21
View File
@@ -323,5 +323,26 @@ fn clipboard_travels_as_text() {
t.execute("pasteorig", &json!({})).unwrap();
assert_eq!(t.doc().unwrap().model.len(), 2);
assert!(t.doc().unwrap().block("DOOR").is_some() && t.doc().unwrap().layer("HINGE").is_some());
// A paste asked for from a menu or by name reads the system clipboard first, so text from
// another window replaces a copy made here earlier; text that is not a DXF drawing does not.
let mut u = Session::empty();
u.open_drawing(drawing_b(), "B", None);
assert!(u.execute("pasteclip", &json!({})).is_err(), "nothing to paste yet");
assert!(clipboard::load_system_text(&mut u, &text));
u.execute("pasteclip", &json!({})).unwrap();
assert_eq!(u.doc().unwrap().model.len(), 2, "the system clipboard's objects were pasted");
let mut v = Session::empty();
v.open_drawing(drawing_b(), "B", None);
let local = line(v.doc_mut().unwrap(), "0", (1.0, 1.0), (2.0, 2.0));
let local_handle = local.handle.hex();
v.doc_mut().unwrap().model.push(local);
v.execute("copyclip", &json!({ "handles": [local_handle] })).unwrap();
assert_eq!(v.clipboard.len(), 1);
assert!(!clipboard::load_system_text(&mut v, "just some words"), "not a drawing");
assert_eq!(v.clipboard.len(), 1, "the copy made here stays");
assert!(clipboard::load_system_text(&mut v, &text));
assert_eq!(v.clipboard.len(), 2, "newer text from another window replaces it");
assert!(v.clipboard_source.as_ref().is_some_and(|c| c.uid.is_none()));
let _ = a;
}
+115
View File
@@ -0,0 +1,115 @@
//! DIMASSOC 1 creates dimension objects without coupling them to source geometry; 2 couples them.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Dimension, EntityKind, Handle};
use serde_json::{Value, json};
/// Read the single entity handle returned by a dimension command.
fn handle(v: &Value) -> Handle {
Handle::parse_hex(v["handle"].as_str().unwrap()).unwrap()
}
/// Clone the asserted dimension so later edits can be compared with its previous state.
fn dimension(s: &Session, h: Handle) -> Dimension {
match &s.doc().unwrap().entity(h).unwrap().kind {
EntityKind::Dimension(d) => d.clone(),
other => panic!("expected dimension, got {other:?}"),
}
}
/// Create a synthetic source line and return its first entity handle.
fn line(s: &mut Session, a: [i32; 2], b: [i32; 2]) -> Handle {
let v = s.execute("line", &json!({"points": [a, b]})).unwrap();
Handle::parse_hex(v["handles"][0].as_str().unwrap()).unwrap()
}
/// Set the drawing-wide associativity mode before creating the test dimensions.
fn mode(s: &mut Session, n: i32) {
s.execute("setvar", &json!({"name": "DIMASSOC", "value": n})).unwrap();
}
/// Typed and JSON dimensions retain their mode through DXF, source edits, undo and redo.
#[test]
fn linear_dimensions_respect_the_mode_through_edits_and_dxf() {
for n in [1, 2] {
for typed in [false, true] {
let mut s = Session::new();
mode(&mut s, n);
let source = line(&mut s, [0, 0], [10, 0]);
let d = if typed {
s.cmdline("dimlinear 0,0 10,0 5,4").unwrap();
s.last_dim.unwrap()
} else {
handle(&s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 4]})).unwrap())
};
assert_eq!(dimension(&s, d).assoc.len(), if n == 2 { 2 } else { 0 }, "mode{n}, typed{typed}");
let saved = cadcraft_io::write_dxf(s.doc().unwrap());
let has_link = saved.lines().any(|l| l.trim() == "DIMASSOC");
assert_eq!(has_link, n == 2, "mode{n}: only associative dimensions save a DIMASSOC object");
let mut reopened = Session::new();
reopened.open_drawing(cadcraft_io::read_dxf(saved.as_bytes()).unwrap(), "roundtrip.dxf", None);
for session in [&mut s, &mut reopened] {
session.execute("properties.set", &json!({"handles": [source.hex()], "end": [15, 0]})).unwrap();
let edited = dimension(session, d);
assert_eq!(edited.p14.x, if n == 2 { 15.0 } else { 10.0 });
assert_eq!(cadcraft_engine::render::dimension_in(session.doc().unwrap(), &edited).measurement, if n == 2 { 15.0 } else { 10.0 });
session.undo().unwrap();
assert_eq!(dimension(session, d).p14.x, 10.0);
session.redo().unwrap();
assert_eq!(dimension(session, d).p14.x, edited.p14.x);
}
}
}
}
/// Continue, Baseline and Quick Dimension attach source links only in mode 2.
#[test]
fn indexed_chains_and_qdim_respect_the_mode() {
for n in [1, 2] {
for cmd in ["dimcontinue", "dimbaseline", "qdim"] {
let mut s = Session::new();
mode(&mut s, n);
let source = line(&mut s, [0, 0], [10, 0]);
s.execute("point", &json!({"at": [20, 0]})).unwrap();
s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 4]})).unwrap();
let params = if cmd == "qdim" { json!({"handles": [source.hex()], "at": [5, 6]}) } else { json!({"points": [[20, 0]]}) };
let out = s.execute(cmd, &params).unwrap();
let hs = out["handles"].as_array().unwrap();
assert!(!hs.is_empty());
for h in hs {
let d = dimension(&s, Handle::parse_hex(h.as_str().unwrap()).unwrap());
assert_eq!(d.assoc.len(), if n == 2 { 2 } else { 0 }, "mode{n}, {cmd}");
}
}
}
}
/// Even explicitly selected angular source lines produce associations only in mode 2.
#[test]
fn explicit_angular_links_respect_the_mode() {
for n in [1, 2] {
let mut s = Session::new();
mode(&mut s, n);
let a = line(&mut s, [0, 0], [10, 0]);
let b = line(&mut s, [0, 0], [0, 10]);
let d = handle(&s.execute("dimangular", &json!({"lines": [a.hex(), b.hex()], "at": [4, 4]})).unwrap());
assert_eq!(dimension(&s, d).assoc.len(), if n == 2 { 4 } else { 0 });
}
}
/// Changing the creation mode preserves old links and does not disable explicit reassociation.
#[test]
fn mode_change_keeps_existing_links_and_allows_explicit_reassociation() {
let mut s = Session::new();
let source = line(&mut s, [0, 0], [10, 0]);
let params = json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 4]});
let existing = handle(&s.execute("dimlinear", &params).unwrap());
mode(&mut s, 1);
let new = handle(&s.execute("dimlinear", &params).unwrap());
assert_eq!(dimension(&s, existing).assoc.len(), 2);
assert!(dimension(&s, new).assoc.is_empty());
s.execute("dimreassociate", &json!({"handles": [new.hex()]})).unwrap();
assert_eq!(dimension(&s, new).assoc.len(), 2);
s.execute("properties.set", &json!({"handles": [source.hex()], "end": [15, 0]})).unwrap();
assert_eq!(dimension(&s, existing).p14.x, 15.0);
assert_eq!(dimension(&s, new).p14.x, 15.0);
}
+7
View File
@@ -133,6 +133,13 @@ fn bad_input_is_refused_and_changes_nothing() {
json!({ "path": "a.png", "data": data, "width": -3 }),
json!({ "path": "a.png", "data": data, "width": "wide" }),
json!({ "path": "a.png", "data": data, "width": 1e-320 }),
// A value of the wrong type is refused, not taken as omitted.
json!({ "path": "a.png", "data": data, "scale": "big" }),
json!({ "path": "a.png", "data": data, "width": 2, "scale": "big" }),
json!({ "path": "a.png", "data": data, "rotation": "right" }),
json!({ "path": "a.png", "data": data, "at": "nowhere" }),
json!({ "path": "a.png", "data": data, "at": [1] }),
json!({ "path": "a.png", "data": data, "name": 7 }),
json!({ "path": "x".repeat(5000), "data": data }),
] {
assert!(s.execute("imageattach", &p).is_err(), "{p}");
+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");
}
@@ -36,13 +36,16 @@ fn baseline_spacing_follows_overrides_and_dimscale() {
assert!(near(dli, 1.0), "SETVAR DIMDLI sets the spacing: {dli}");
let zero = baseline_spacing(&[("dimstyle", json!({"name": "Standard", "DIMSCALE": 0}))]);
assert!(near(zero, 0.38), "DIMSCALE 0 in model space is scale 1, not a collapsed spacing: {zero}");
}
// DIMSPACE's default spacing (twice DIMDLI) uses the same scale.
#[test]
fn dimspace_auto_uses_unit_scale_for_zero_dimscale_in_model_space() {
let mut s = Session::new();
s.execute("dimstyle", &json!({"name": "Standard", "DIMSCALE": 0})).unwrap();
let text_height = 0.25;
s.execute("dimstyle", &json!({"name": "Standard", "DIMTXT": text_height, "DIMSCALE": 0})).unwrap();
let a = s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [30, 0], "at": [15, 5]})).unwrap();
let b = s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [50, 0], "at": [25, 6]})).unwrap();
s.execute("dimspace", &json!({"base": a["handle"], "handles": [b["handle"]]})).unwrap();
let gap = dim_line_y(&s, &b["handle"]) - dim_line_y(&s, &a["handle"]);
assert!(near(gap, 0.76), "{gap}");
assert!((gap - 2.0 * text_height).abs() < 1e-9, "{gap}");
}
+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);
}
@@ -0,0 +1,425 @@
//! INSERT and the attribute modes (gap F17): Preset and constant attributes take their values
//! without asking, ATTREQ 0 gives every attribute its default, ATTDIA 0 asks at the command line
//! (a Verify attribute's value again once every value is in) and ATTDIA 1 (the default) asks for
//! the values all at once in the Edit Attributes dialog (`Session::attribute_entry`), typed
//! answers still working. The JSON form never asks. ATTREQ and ATTDIA are user settings, as in
//! AutoCAD (DWG keeps them in its header only before R2000).
use std::sync::Arc;
use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, Handle, Text};
use cadcraft_engine::geom::{Vec2, Vec3};
use cadcraft_engine::{AttribAsk, Input, Origin, Session};
use serde_json::json;
fn def(tag: &str, prompt: &str, default: &str, y: f64, constant: bool, modes: AttribModes) -> Attrib {
Attrib {
tag: tag.into(),
text: Text {
insert: Vec3::new(0.0, y, 0.0),
align_pt: None,
height: 1.0,
value: default.into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
},
invisible: false,
constant,
prompt: prompt.into(),
props: Default::default(),
multiline: None,
modes,
}
}
/// Block T with the definitions A (Verify), B (Preset), C (plain) and D (constant); ATTREQ and
/// ATTDIA as given (their defaults, ATTREQ 1 and ATTDIA 1, otherwise).
fn session(attreq: Option<bool>, attdia: Option<bool>) -> Session {
let mut d = cadcraft_engine::doc::Drawing::new_imperial();
let mut b = Block::new("T");
let none = AttribModes::default();
for a in [
def("A", "First", "1", 2.0, false, AttribModes { verify: true, ..none }),
def("B", "Second", "two", 4.0, false, AttribModes { preset: true, ..none }),
def("C", "Third", "3", 6.0, false, none),
def("D", "", "fixed", 8.0, true, none),
] {
let h = d.new_handle();
b.entities.push(Entity::new(h, EntityKind::AttDef(a)));
}
d.blocks.insert("T".into(), Arc::new(b));
let mut s = Session::empty();
s.open_drawing(d, "attribs", None);
if let Some(v) = attreq {
s.settings.attreq = v;
}
if let Some(v) = attdia {
s.settings.attdia = v;
}
s
}
/// Start INSERT of T at 100,0 and answer the scale and rotation prompts.
fn insert_up_to_the_attributes(s: &mut Session) {
s.start("insert").unwrap();
s.cmdline("T").unwrap();
s.input(Input::Point(Vec2::new(100.0, 0.0))).unwrap();
s.input(Input::Enter).unwrap(); // X scale 1
s.input(Input::Enter).unwrap(); // Y scale = X
s.input(Input::Enter).unwrap(); // rotation 0
}
/// The attribute values of the last block reference, in order.
fn values(s: &Session) -> Vec<(String, String)> {
let d = s.doc().unwrap();
let Some(EntityKind::Insert(i)) = d.model.iter().filter(|e| matches!(e.kind, EntityKind::Insert(_))).last().map(|e| e.kind.clone()) else {
panic!("no block reference")
};
i.attribs.iter().map(|a| (a.tag.clone(), a.text.value.clone())).collect()
}
fn pairs(v: &[(&str, &str)]) -> Vec<(String, String)> {
v.iter().map(|(t, v)| (t.to_string(), v.to_string())).collect()
}
#[test]
fn a_fresh_session_reads_attdia_1() {
// AutoCAD 2026's ATTDIA page: Type Integer, Saved in Registry, Initial value 1.
let mut s = session(None, None);
assert_eq!(s.execute("getvar", &json!({ "name": "ATTDIA" })).unwrap()["value"], 1);
assert!(s.settings.attdia);
}
#[test]
fn typed_insert_asks_verify_again_and_skips_preset_and_constant() {
// ATTDIA 0 set explicitly, so the command line asks.
let mut s = session(Some(true), Some(false));
assert_eq!(s.execute("getvar", &json!({ "name": "ATTDIA" })).unwrap()["value"], 0);
assert_eq!(s.execute("getvar", &json!({ "name": "ATTREQ" })).unwrap()["value"], 1);
insert_up_to_the_attributes(&mut s);
assert!(s.attribute_entry().is_none(), "ATTDIA 0: no dialog");
assert_eq!(s.prompt_text(), "INSERT First <1>:", "A first");
s.input(Input::Text("10".into())).unwrap();
assert_eq!(s.prompt_text(), "INSERT Third <3>:", "B is Preset: not asked");
s.input(Input::Enter).unwrap(); // C takes its default
// Then the Verify attributes, with the values typed.
assert_eq!(s.prompt_text(), "INSERT First <10>:");
s.input(Input::Text("11".into())).unwrap(); // the value typed at Verify replaces it
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "11"), ("B", "two"), ("C", "3")]));
// Enter at Verify keeps the value given; Enter at A takes its default, verified.
insert_up_to_the_attributes(&mut s);
s.input(Input::Enter).unwrap();
s.input(Input::Text("c".into())).unwrap();
assert_eq!(s.prompt_text(), "INSERT First <1>:");
s.input(Input::Enter).unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "1"), ("B", "two"), ("C", "c")]));
// A script answers in turn too.
s.script("-INSERT T 0,50 1 1 0\na\nc\nz\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "z"), ("B", "two"), ("C", "c")]));
}
#[test]
fn a_point_does_not_answer_an_attribute_prompt() {
// A canvas click reaches INSERT as Input::Point while a text-only attribute prompt waits.
// It is no answer: the prompt stays, and only Enter keeps the default.
let mut s = session(Some(true), Some(false));
insert_up_to_the_attributes(&mut s);
assert_eq!(s.prompt_text(), "INSERT First <1>:");
s.input(Input::Point(Vec2::new(20.0, 20.0))).unwrap();
assert_eq!(s.prompt_text(), "INSERT First <1>:", "the click did not take A's default");
assert!(s.attribute_entry().is_none(), "ATTDIA 0: no dialog");
s.input(Input::Text("10".into())).unwrap();
assert_eq!(s.prompt_text(), "INSERT Third <3>:", "A was answered by the typed text");
s.input(Input::Enter).unwrap(); // C takes its default
assert_eq!(s.prompt_text(), "INSERT First <10>:", "then A's Verify");
s.input(Input::Enter).unwrap(); // Verify keeps the value typed
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "10"), ("B", "two"), ("C", "3")]));
}
#[test]
fn attreq_0_gives_every_attribute_its_default() {
let mut s = session(Some(false), None);
insert_up_to_the_attributes(&mut s);
assert!(s.running.is_none(), "no attribute prompt: {}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "1"), ("B", "two"), ("C", "3")]));
// SETVAR changes it.
s.execute("setvar", &json!({ "name": "ATTREQ", "value": 1 })).unwrap();
s.execute("setvar", &json!({ "name": "ATTDIA", "value": 0 })).unwrap();
insert_up_to_the_attributes(&mut s);
assert_eq!(s.prompt_text(), "INSERT First <1>:");
}
#[test]
fn attdia_1_asks_for_every_value_at_once_and_typed_answers_still_work() {
let mut s = session(None, None);
s.execute("setvar", &json!({ "name": "ATTDIA", "value": 1 })).unwrap();
assert_eq!(s.execute("getvar", &json!({ "name": "ATTDIA" })).unwrap()["value"], 1);
s.start("insert").unwrap();
s.cmdline("T").unwrap();
assert!(s.attribute_entry().is_none(), "not before the attribute prompts");
s.input(Input::Point(Vec2::new(100.0, 0.0))).unwrap();
s.input(Input::Enter).unwrap();
s.input(Input::Enter).unwrap();
s.input(Input::Enter).unwrap();
let e = s.attribute_entry().expect("the dialog's rows");
assert_eq!(e.block, "T");
let ask =
|tag: &str, prompt: &str, default: &str, verify: bool| AttribAsk { tag: tag.into(), prompt: prompt.into(), default: default.into(), verify };
assert_eq!(e.rows, vec![ask("A", "First", "1", true), ask("C", "Third", "3", false)]);
// The dialog's OK: every value, then the Verify attribute's again.
let answers = e.answers(&["x".into(), String::new()]);
assert_eq!(answers, ["x", "", "x"]);
for a in answers {
s.input(Input::Text(a)).unwrap();
}
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "x"), ("B", "two"), ("C", "")]));
// Typed instead: the dialog goes away after the first answer.
insert_up_to_the_attributes(&mut s);
assert!(s.attribute_entry().is_some());
s.input(Input::Text("typed".into())).unwrap();
assert!(s.attribute_entry().is_none());
s.input(Input::Enter).unwrap(); // C takes its default
s.input(Input::Enter).unwrap(); // Verify keeps the value typed
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "typed"), ("B", "two"), ("C", "3")]));
// Cancel from the dialog inserts nothing.
let before = s.doc().unwrap().model.len();
insert_up_to_the_attributes(&mut s);
s.cancel();
assert!(s.running.is_none());
assert_eq!(s.doc().unwrap().model.len(), before);
}
#[test]
fn json_insert_never_asks_whatever_attreq_and_attdia_say() {
for (req, dia) in [(false, false), (true, true)] {
let mut s = session(Some(req), Some(dia));
let r = s.execute("insert", &json!({ "name": "T", "at": [0, 0], "attribs": { "a": "given", "B": "preset given" } })).unwrap();
assert!(r["handle"].is_string());
assert!(s.running.is_none() && s.attribute_entry().is_none());
assert_eq!(values(&s), pairs(&[("A", "given"), ("B", "preset given"), ("C", "3")]));
}
}
#[test]
fn hostile_values_never_panic() {
let mut s = session(None, Some(true));
insert_up_to_the_attributes(&mut s);
let e = s.attribute_entry().expect("asks");
// Too few answers take the defaults, too many are ignored.
assert_eq!(e.answers(&[]), ["1", "3", "1"]);
assert_eq!(e.answers(&["p".into(), "q".into(), "r".into()]), ["p", "q", "p"]);
s.cancel();
for bad in [json!(2), json!(-1), json!("x"), json!(null), json!(1.5)] {
assert!(s.execute("setvar", &json!({ "name": "ATTDIA", "value": bad })).is_err(), "{bad}");
assert!(s.execute("setvar", &json!({ "name": "ATTREQ", "value": bad })).is_err(), "{bad}");
}
assert!(s.settings.attdia && s.settings.attreq, "a refused value changes nothing");
// An INSERT of a block with only Preset and constant attributes asks nothing.
let mut d = cadcraft_engine::doc::Drawing::new_imperial();
let mut b = Block::new("P");
let h: Handle = d.new_handle();
b.entities.push(Entity::new(h, EntityKind::AttDef(def("P", "p", "v", 0.0, false, AttribModes { preset: true, ..AttribModes::default() }))));
d.blocks.insert("P".into(), Arc::new(b));
let mut s = Session::empty();
s.open_drawing(d, "preset", None);
s.script("-INSERT P 0,0 1 1 0\n").unwrap();
assert!(s.running.is_none() && s.attribute_entry().is_none());
assert_eq!(values(&s), pairs(&[("P", "v")]));
}
#[test]
fn a_script_never_asks_in_the_dialog() {
// A script cannot click a dialog: ATTDIA 1 keeps its prompts at the command line, even when
// the script ends with INSERT still waiting for the first attribute.
let mut s = session(None, Some(true));
s.script("-INSERT T 0,50 1 1 0\n").unwrap();
assert_eq!(s.prompt_text(), "INSERT First <1>:", "INSERT still waits after the script");
assert!(s.attribute_entry().is_none(), "a scripted INSERT never opens the dialog");
// The command the script started keeps answering at the command line.
s.input(Input::Text("a".into())).unwrap();
s.input(Input::Text("c".into())).unwrap();
s.input(Input::Text("a".into())).unwrap(); // A's Verify
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "a"), ("B", "two"), ("C", "c")]));
// A typed INSERT with ATTDIA 1 still asks in the dialog.
insert_up_to_the_attributes(&mut s);
assert!(s.attribute_entry().is_some(), "a typed INSERT asks in the dialog");
}
#[test]
fn a_lisp_insert_never_asks_in_the_dialog() {
// (command "-INSERT" …) runs INSERT outside Session::script: the routine cannot click a
// dialog, and it finishes before the first attribute answer.
let mut s = session(None, Some(true));
let r = s.execute("lisp", &json!({ "code": "(command \"-INSERT\" \"T\" \"0,50\" 1 1 0)" })).unwrap();
assert!(r.get("error").is_none(), "{r}");
assert_eq!(s.prompt_text(), "INSERT First <1>:", "INSERT waits at the command line");
assert!(s.attribute_entry().is_none(), "a LISP-started INSERT never opens the dialog");
// The command keeps answering at the command line after the routine ended.
s.input(Input::Text("a".into())).unwrap();
s.input(Input::Text("c".into())).unwrap();
s.input(Input::Text("a".into())).unwrap(); // A's Verify
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s), pairs(&[("A", "a"), ("B", "two"), ("C", "c")]));
// A typed INSERT with ATTDIA 1 asks in the dialog again.
insert_up_to_the_attributes(&mut s);
assert!(s.attribute_entry().is_some(), "a typed INSERT asks in the dialog");
s.cancel();
// A LISP expression typed at the command line is the same program: no dialog.
s.cmdline("(command \"-INSERT\" \"T\" \"0,60\" 1 1 0)").unwrap();
assert_eq!(s.prompt_text(), "INSERT First <1>:");
assert!(s.attribute_entry().is_none(), "a typed (command …) never opens the dialog");
s.cancel();
}
/// A routine that types a command into a running LINE: `(command "LINE" "0,0" spelling …)`.
/// `extra` answers MINSERT's grid, and the arguments after it answer the attribute prompts.
fn lisp_token_replaces_line(spelling: &str, extra: &str) -> Session {
let mut s = session(None, Some(true));
let code = format!("(command \"LINE\" \"0,0\" \"{spelling}\" \"T\" \"0,50\" 1 1 0{extra})");
let r = s.execute("lisp", &json!({ "code": code })).unwrap();
assert!(r.get("error").is_none(), "{spelling}: {r}");
s
}
/// Answer the attribute prompts the routine's INSERT left waiting, as the person at the
/// command line would.
fn answer_the_routines_insert(s: &mut Session) {
s.input(Input::Text("a".into())).unwrap();
s.input(Input::Text("c".into())).unwrap();
s.input(Input::Text("a".into())).unwrap(); // A's Verify
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(s), pairs(&[("A", "a"), ("B", "two"), ("C", "c")]));
}
#[test]
fn a_lisp_insert_token_replacing_a_command_never_asks_in_the_dialog() {
// The token reaches the typed-input path while LINE runs, not the idle start: the INSERT
// that replaces LINE is still the routine's, so ATTDIA 1 opens no dialog nobody can click.
let mut s = lisp_token_replaces_line("'-INSERT", "");
assert_eq!(s.prompt_text(), "INSERT First <1>:", "asked at the command line");
assert!(s.attribute_entry().is_none(), "a LISP token never opens the dialog");
// The command keeps answering at the command line after the routine ended.
answer_the_routines_insert(&mut s);
}
#[test]
fn a_lisp_minsert_token_replacing_a_command_never_asks_in_the_dialog() {
let mut s = lisp_token_replaces_line("'MINSERT", " 1 1");
assert_eq!(s.prompt_text(), "MINSERT First <1>:", "asked at the command line");
assert!(s.attribute_entry().is_none(), "a LISP token never opens the dialog");
answer_the_routines_insert(&mut s);
}
#[test]
fn a_person_typing_a_transparent_insert_still_asks_in_the_dialog() {
// The tokens the routine feeds above, typed by a person: the INSERT that replaces LINE is
// theirs, so ATTDIA 1 asks in the dialog.
let mut s = session(None, Some(true));
s.cmdline("LINE 0,0 '-INSERT T 0,50 1 1 0").unwrap();
assert!(s.running.is_some(), "{}", s.prompt_text());
assert!(s.attribute_entry().is_some(), "a typed transparent INSERT asks in the dialog");
s.cancel();
}
/// A person typing `'NAME T …` while a routine waits in `(command "LINE" "0,0" pause)`
/// cancels it; the routine's `*error*` handler then starts a LINE of its own. The handler's
/// command is the program's, and it must not take the origin or number of the person's start.
/// `extra` answers MINSERT's rows and columns.
fn person_replaces_paused_lisp(spelling: &str, extra: &str) -> Session {
let mut s = session(None, Some(true));
s.cmdline("(defun *error* (msg) (command \"LINE\" \"1,1\" \"2,2\" \"\"))").unwrap();
s.cmdline("(command \"LINE\" \"0,0\" pause)").unwrap();
assert!(s.running.is_some(), "the routine's LINE waits for the person: {}", s.prompt_text());
// The person replaces the waiting routine with their own command.
s.cmdline(&format!("'{spelling} T 0,50 1 1 0{extra}")).unwrap();
assert!(s.running.is_some(), "{}", s.prompt_text());
// The handler's LINE is the only one drawn: the paused LINE was cancelled at its first
// point, and the handler's own command ran as the program's (nobody typed 1,1 or 2,2).
let lines: Vec<(Vec2, Vec2)> = s
.doc()
.unwrap()
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(l) => Some((l.a.xy(), l.b.xy())),
_ => None,
})
.collect();
assert_eq!(lines, vec![(Vec2::new(1.0, 1.0), Vec2::new(2.0, 2.0))], "the error handler's LINE is drawn, and the paused one added nothing");
s
}
#[test]
fn a_person_replacing_paused_lisp_keeps_their_insert_dialog() {
let s = person_replaces_paused_lisp("-INSERT", "");
assert_eq!(s.command_origin(), Origin::Person, "the person's INSERT is not the handler's command");
let e = s.attribute_entry().expect("ATTDIA 1: the person's INSERT asks in the dialog");
// The handler's LINE finished as a command of its own; the INSERT's answers belong to a
// later number, so the dialog a cancelled command left behind is not taken.
assert_eq!(s.last_finished.map(|(command, _)| command), Some(e.command.wrapping_sub(1)), "the handler's LINE keeps its own number");
}
#[test]
fn a_person_replacing_paused_lisp_keeps_their_minsert_dialog() {
let s = person_replaces_paused_lisp("MINSERT", " 1 1");
assert_eq!(s.command_origin(), Origin::Person, "the person's MINSERT is not the handler's command");
let e = s.attribute_entry().expect("ATTDIA 1: the person's MINSERT asks in the dialog");
assert_eq!(s.last_finished.map(|(command, _)| command), Some(e.command.wrapping_sub(1)), "the handler's LINE keeps its own number");
}
#[test]
fn an_entry_belongs_to_the_drawing_and_command_that_asked() {
let mut s = session(None, Some(true));
insert_up_to_the_attributes(&mut s);
let first = s.attribute_entry().expect("asks");
assert_eq!(first.drawing, s.state().unwrap().uid);
assert_eq!(first.command, s.commands_started);
// Asked again in a later frame: the same owner.
assert_eq!(s.attribute_entry().map(|e| (e.drawing, e.command)), Some((first.drawing, first.command)));
// Cancelled and started again: a new number, so the old dialog's draft is not taken.
s.cancel();
insert_up_to_the_attributes(&mut s);
let second = s.attribute_entry().expect("asks again");
assert_eq!(second.block, "T");
assert_ne!((second.drawing, second.command), (first.drawing, first.command));
// Another drawing's INSERT is another owner too.
let mut other = session(None, Some(true));
insert_up_to_the_attributes(&mut other);
let third = other.attribute_entry().expect("asks there");
assert_eq!(third.drawing, other.state().unwrap().uid);
assert_ne!(third.drawing, first.drawing);
}
#[test]
fn two_definitions_with_one_tag_are_both_asked_once() {
// INSERT counted its answers by tag: the second X was asked for ever.
let mut d = cadcraft_engine::doc::Drawing::new_imperial();
let mut b = Block::new("DUP");
for (prompt, y) in [("first", 0.0), ("second", 2.0)] {
let h = d.new_handle();
b.entities.push(Entity::new(h, EntityKind::AttDef(def("X", prompt, "d", y, false, AttribModes::default()))));
}
d.blocks.insert("DUP".into(), Arc::new(b));
let mut s = Session::empty();
s.open_drawing(d, "dup", None);
s.settings.attdia = false;
s.script("-INSERT DUP 0,0 1 1 0\na\nb\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(values(&s).len(), 2);
}
@@ -0,0 +1,44 @@
//! A dimension kept as read (LARGE_RADIAL_DIMENSION, ARC_DIMENSION) draws its `*D` block through
//! a reference in its graphics (#3438); object snaps reach the objects inside that block.
use cadcraft_engine::doc::Space;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::snap::{self, mode};
#[test]
fn a_kept_dimension_snaps_to_its_blocks_objects() {
// The block's base point isn't the origin; its line is where the dimension draws it.
let dxf = "0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n8\n0\n2\n*D1\n70\n1\n10\n100\n20\n50\n3\n*D1\n0\nLINE\n8\n0\n10\n110\n20\n60\n11\n120\n21\n70\n0\nENDBLK\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n0\nLARGE_RADIAL_DIMENSION\n5\n41\n100\nAcDbEntity\n8\n0\n100\nAcDbDimension\n2\n*D1\n0\nENDSEC\n0\nEOF\n";
let d = cadcraft_io::read_dxf(dxf.as_bytes()).expect("read");
let at = |p: Vec2, m: u32| snap::osnap(&d, &Space::Model, p + Vec2::new(0.02, -0.01), 0.1, m, None, false).map(|h| (h.point, h.mode));
let end = Vec2::new(120.0, 70.0);
assert!(at(end, mode::END).is_some_and(|(p, m)| m == mode::END && p.dist(end) < 1e-9), "{:?}", at(end, mode::END));
let mid = Vec2::new(115.0, 65.0);
assert!(at(mid, mode::MID).is_some_and(|(p, m)| m == mode::MID && p.dist(mid) < 1e-9), "{:?}", at(mid, mode::MID));
}
/// A DIMENSION inside a block snaps to the objects of its own `*D` block, as it is drawn; so does
/// one moved by an older AutoCAD (group 12), translated by the move as the renderer draws it.
#[test]
fn dimensions_in_blocks_snap_to_their_blocks_objects() {
let dim = |handle: &str, offset: (f64, f64)| {
format!(
"0\nDIMENSION\n5\n{handle}\n100\nAcDbEntity\n8\n0\n100\nAcDbDimension\n2\n*D2\n10\n5\n20\n7\n30\n0\n11\n5\n21\n8\n31\n0\n12\n{}\n22\n{}\n32\n0\n70\n1\n100\nAcDbAlignedDimension\n13\n0\n23\n7\n33\n0\n14\n10\n24\n7\n34\n0\n",
offset.0, offset.1
)
};
let dxf = format!(
"0\nSECTION\n2\nBLOCKS\n\
0\nBLOCK\n8\n0\n2\n*D2\n70\n1\n10\n0\n20\n0\n3\n*D2\n0\nLINE\n8\n0\n10\n0\n20\n7\n11\n10\n21\n7\n0\nENDBLK\n\
0\nBLOCK\n8\n0\n2\nNEST\n70\n0\n10\n0\n20\n0\n3\nNEST\n{}0\nENDBLK\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n0\nINSERT\n5\n70\n8\n0\n2\nNEST\n10\n100\n20\n0\n{}0\nENDSEC\n0\nEOF\n",
dim("60", (0.0, 0.0)),
dim("61", (0.0, 50.0)),
);
let d = cadcraft_io::read_dxf(dxf.as_bytes()).expect("read");
let at = |p: Vec2, m: u32| snap::osnap(&d, &Space::Model, p + Vec2::new(0.02, -0.01), 0.1, m, None, false).map(|h| (h.point, h.mode));
for (p, m) in [(Vec2::new(110.0, 7.0), mode::END), (Vec2::new(105.0, 7.0), mode::MID), (Vec2::new(10.0, 57.0), mode::END)] {
assert!(at(p, m).is_some_and(|(q, k)| k == m && q.dist(p) < 1e-9), "{p:?}: {:?}", at(p, m));
}
}
+4
View File
@@ -76,12 +76,14 @@ mod hidden_grip_targets;
mod inquiry_keywords;
mod inquiry_variables;
mod inquiry_z;
mod insert_attrib_entry;
mod insert_attribute_prompts;
mod insert_enter;
mod insert_prompts;
mod isometric;
mod join_close;
mod json_param_validation;
mod kept_dimension_snaps;
mod layer_cmdline;
mod layer_merge_delete;
mod layer_state_cmdline;
@@ -134,6 +136,7 @@ mod properties_set_locked;
mod properties_set_text_dims;
mod props_bad_lineweight;
mod props_insert_scale_attribs;
mod purge_kept_dimension_blocks;
mod purge_mlinestyles;
mod purge_prompts;
mod qdim;
@@ -147,6 +150,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;
@@ -0,0 +1,31 @@
//! PURGE keeps the `*D` block a dimension kept as read names (LARGE_RADIAL_DIMENSION,
//! ARC_DIMENSION): the dimension draws it, and AutoCAD needs it to read the file (#3438, #1161).
use std::sync::Arc;
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Block, Common, Entity, EntityKind, Handle, Line, RawTag, Space, Unknown};
use cadcraft_engine::geom::Vec3;
use serde_json::json;
#[test]
fn purge_keeps_the_block_a_kept_dimension_names() {
let mut s = Session::new();
let d = s.doc_mut().unwrap();
for name in ["*D1", "*D2"] {
let mut b = Block::new(name);
b.entities.push(Entity::new(Handle(0x9000), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 1.0, 0.0) })));
d.blocks.insert(name.into(), Arc::new(b));
}
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let dim = Unknown {
dxf_type: "ARC_DIMENSION".into(),
tags: vec![tag(100, "AcDbEntity"), tag(8, "0"), tag(100, "AcDbDimension"), tag(2, "*D1"), tag(100, "AcDbArcDimension")],
graphics: Vec::new(),
};
d.add(&Space::Model, Common::default(), EntityKind::Unknown(dim)).unwrap();
s.execute("purge", &json!({})).unwrap();
let d = s.doc().unwrap();
assert!(d.block("*D1").is_some(), "the kept dimension's block stays");
assert!(d.block("*D2").is_none(), "an unused one goes");
}
@@ -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"));
}
+16
View File
@@ -30,3 +30,19 @@ fn programmatic_spline_control_count_is_limited() {
s.execute("spline", &json!({ "control": control(20_000) })).unwrap();
assert_eq!(s.doc().unwrap().model.len(), 1);
}
#[test]
fn cv_degree_prompt_retries_a_fractional_degree() {
for command in ["spline.cv d", "spline m cv d"] {
let mut s = Session::new();
s.cmdline(command).unwrap();
let degree_prompt = s.current_prompt().unwrap();
assert!(degree_prompt.accept.number);
s.cmdline("2.5").unwrap();
assert_eq!(s.current_prompt().unwrap().message, degree_prompt.message, "{command}");
s.cmdline("2 0,0 1,1 2,0 3,1").unwrap();
s.input(cadcraft_engine::Input::Enter).unwrap();
let d = s.doc().unwrap();
assert!(matches!(&d.model.iter().last().unwrap().kind, EntityKind::Spline(sp) if sp.degree == 2));
}
}
+34
View File
@@ -171,3 +171,37 @@ fn json_form_takes_the_fit_options() {
assert_eq!(sp.fit_opts.start_tangent, None);
assert_eq!(sp.fit_opts.end_tangent, Some(-Vec2::Y));
}
#[test]
fn cv_method_keeps_cv_on_enter_and_can_switch_back_to_fit() {
for entry in ["spline.cv", "spline m cv"] {
let mut s = Session::new();
s.cmdline(&format!("{entry} d 2 m")).unwrap();
s.cmdline("").unwrap();
s.cmdline("m fit 0,0 1,2 3,1").unwrap();
s.cmdline("").unwrap();
assert_eq!(last_spline(&s).fit.len(), 3, "{entry}");
s.cmdline(&format!("{entry} d 2 m")).unwrap();
s.cmdline("").unwrap();
s.cmdline("0,0 1,2 3,1 4,0").unwrap();
s.cmdline("").unwrap();
let cv = last_spline(&s);
assert!(cv.fit.is_empty() && cv.degree == 2, "{entry}");
}
}
#[test]
fn cv_object_converts_the_picked_polyline() {
for entry in ["spline.cv", "spline m cv"] {
let mut s = Session::new();
s.execute("pline", &json!({"vertices":[[0,0],[1,2],[3,1]]})).unwrap();
let h = s.doc().unwrap().model.iter().next().unwrap().handle;
s.cmdline(&format!("{entry} o")).unwrap();
assert!(s.current_prompt().unwrap().picks_objects(), "{entry}");
s.input(cadcraft_engine::Input::Pick(vec![h])).unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none() && s.doc().unwrap().model.len() == 1);
assert_eq!(last_spline(&s).fit.len(), 3);
}
}
@@ -0,0 +1,135 @@
//! MIRROR retains a hatch pattern's direction by default, while reflecting its boundary.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{EntityKind, Handle, Hatch};
use cadcraft_engine::geom::Vec2;
use serde_json::{Value, json};
/// Create a rectangular hatch with an oblique pattern direction for reflection checks.
fn fixture() -> (Session, Handle) {
fixture_with(json!({"pattern": "ANSI31", "angle": 30}))
}
/// Create a nonassociative rectangular hatch with the supplied synthetic fill parameters.
fn fixture_with(mut params: Value) -> (Session, Handle) {
let mut s = Session::new();
let outline = s.execute("rectang", &json!({"p1": [2, 1], "p2": [8, 4]})).unwrap()["handle"].clone();
params["handles"] = json!([outline]);
params["associative"] = json!(false);
let result = s.execute("hatch", &params).unwrap();
let h = result["handles"][0].as_str().unwrap();
let h = Handle::parse_hex(h).unwrap();
(s, h)
}
/// Clone the asserted hatch so its geometry and fill can be compared across edits.
fn hatch(s: &Session, h: Handle) -> Hatch {
match &s.doc().unwrap().entity(h).unwrap().kind {
EntityKind::Hatch(h) => h.clone(),
_ => panic!("expected hatch"),
}
}
/// A diagonal mirror reflects the boundary while retaining the fill direction through DXF readback.
#[test]
fn diagonal_mirror_keeps_pattern_direction_and_reflects_boundary() {
let (mut s, source) = fixture();
let before = hatch(&s, source);
let result = s.execute("mirror", &json!({"handles": [source.hex()], "p1": [0, 0], "p2": [10, 10]})).unwrap();
let mirrored = Handle::parse_hex(result["handles"][0].as_str().unwrap()).unwrap();
let after = hatch(&s, mirrored);
assert!((after.angle - before.angle).abs() < 1e-12, "pattern turned from {} to {} degrees", before.angle.to_degrees(), after.angle.to_degrees());
for (a, b) in before.loops[0].vertices.iter().zip(&after.loops[0].vertices) {
assert!((a.p.x - b.p.y).abs() < 1e-12);
assert!((a.p.y - b.p.x).abs() < 1e-12);
}
assert_eq!(hatch(&s, source), before, "retained source is unchanged");
let saved = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap();
let EntityKind::Hatch(saved) = &saved.entity(mirrored).unwrap().kind else { panic!("hatch lost on save") };
assert!((saved.angle - before.angle).abs() < 1e-12);
}
/// Typed MIRROR previews and committed geometry agree, including undo and redo.
#[test]
fn typed_mirror_previews_match_the_result_and_undo_redo() {
let (mut s, h) = fixture();
let before = hatch(&s, h);
s.set_selection(vec![h]);
s.cmdline("MIRROR 0,0").unwrap();
let cursor = Vec2::new(10., 10.);
let previews = s.preview(cursor);
let preview = previews
.iter()
.find_map(|e| match &e.kind {
EntityKind::Hatch(h) => Some(h),
_ => None,
})
.unwrap();
assert_eq!(preview.angle, before.angle);
let (drag, _) = s.drag(cursor).unwrap();
assert!(!drag.handles.contains(&h), "GPU reflection would turn the hatch pattern");
let drag_hatch = drag
.extra
.iter()
.find_map(|k| match k {
EntityKind::Hatch(h) => Some(h),
_ => None,
})
.unwrap();
assert_eq!(drag_hatch, preview);
s.cmdline("10,10").unwrap();
s.cmdline("Y").unwrap();
assert!(s.running.is_none());
let after = hatch(&s, h);
assert_eq!(&after, preview);
s.execute("undo", &json!({})).unwrap();
assert_eq!(hatch(&s, h), before);
s.execute("redo", &json!({})).unwrap();
assert_eq!(hatch(&s, h), after);
}
/// Patterned and gradient fills keep their definitions when the mirrored result replaces its source.
#[test]
fn another_pattern_and_gradient_directions_are_retained() {
for gradient in [false, true] {
let (mut s, h) = fixture();
if gradient {
s.execute("hatchedit", &json!({"handles": [h.hex()], "gradient": {"name": "LINEAR", "angle": 20}})).unwrap();
} else {
s.execute("hatchedit", &json!({"handles": [h.hex()], "pattern": "ANSI32"})).unwrap();
}
let before = hatch(&s, h);
s.execute("mirror", &json!({"handles": [h.hex()], "p1": [1, 2], "p2": [5, -1], "erase": true})).unwrap();
let after = hatch(&s, h);
assert_eq!(after.angle, before.angle);
assert_eq!(after.pattern, before.pattern);
assert_eq!(after.pattern_lines, before.pattern_lines);
assert_eq!(after.gradient, before.gradient);
}
}
/// Original asymmetric pattern families retain their line definitions under reflection.
#[test]
fn custom_pattern_line_families_are_not_reflected() {
let (mut s, h) = fixture_with(json!({
"pattern": "ORIGINAL", "angle": 30,
"patternText": "*ORIGINAL,Original asymmetric regression pattern\n17,0.2,0.4,0.3,0.8,0.5,-0.2\n67,0.1,0.3,0.2,0.9,0.1,-0.4\n"
}));
let before = hatch(&s, h);
assert_eq!(before.pattern_lines.len(), 2);
s.execute("mirror", &json!({"handles": [h.hex()], "p1": [0, 0], "p2": [10, 10], "erase": true})).unwrap();
let after = hatch(&s, h);
assert_eq!(after.angle, before.angle);
assert_eq!(after.pattern_lines, before.pattern_lines);
}
/// Solid hatches remain eligible for the shared GPU reflection preview.
#[test]
fn solid_fills_can_still_use_the_gpu_preview() {
let (mut s, h) = fixture_with(json!({"pattern": "SOLID"}));
s.set_selection(vec![h]);
s.cmdline("MIRROR 0,0").unwrap();
let (drag, _) = s.drag(Vec2::new(10., 10.)).unwrap();
assert!(drag.handles.contains(&h));
assert!(!drag.extra.iter().any(|k| matches!(k, EntityKind::Hatch(_))));
}
+2 -1
View File
@@ -17,7 +17,8 @@ fn read_file_refuses_a_name_that_is_not_unicode() {
let good = dir.join("good.dxf");
let bad = dir.join(OsString::from_vec(b"bad-\xff.dxf".to_vec()));
std::fs::write(&good, b"0\nEOF\n").unwrap();
std::fs::write(&bad, b"0\nEOF\n").unwrap();
// Validation precedes filesystem access; macOS filesystems may reject this name.
assert!(!bad.exists());
let e = read_file(&bad).err().expect("a non-Unicode name is refused");
assert!(e.contains("not valid Unicode") && e.contains("bad-"), "{e}");
assert!(read_file(&good).is_ok());
+124 -27
View File
@@ -134,10 +134,10 @@ fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64
*point += Vec2::new(offset_y * shear, offset_y);
}
let origin = Vec2::new(pen_x + glyph.dx * glyph_scale + offset_y * shear, offset_y);
let text = shows.get(n).copied().flatten().filter(|character| !character.is_whitespace()).and_then(|character| {
ttf::text_glyph_at(&outline, character, origin, normalized_height / outline.cap, scale_x, shear)
let texts = shows.get(n).into_iter().flatten().filter(|character| !character.is_whitespace()).filter_map(|character| {
ttf::text_glyph_at(&outline, *character, origin, normalized_height / outline.cap, scale_x, shear)
});
shaped.push_glyph(contours, text);
shaped.push_glyph(contours, texts);
}
let advance = glyph.advance * glyph_scale;
let (underline, overline) = flags(glyph.cluster);
@@ -249,46 +249,99 @@ fn shape_run(face: &Face, cs: &[char], r: Range<usize>, rtl: bool) -> Vec<Glyph>
/// longer one (a hostile run of thousands of stacked marks) take its characters in order.
const MAX_MATCHED_CLUSTER: usize = 32;
/// The character each glyph of a left-to-right run shows, for output that keeps text as text
/// The characters each glyph of a left-to-right run shows, for output that keeps text as text
/// ([`crate::TextGlyph`]). The shaper reorders, splits and substitutes glyphs inside a cluster
/// (a letter with its marks), so within each cluster a glyph that is a character's own glyph
/// takes that character first, then the other glyphs take the cluster's remaining characters in
/// order. Each character is shown once: a glyph left over (the second half of a split Thai sara
/// am) shows none and is drawn as an outline only.
fn glyph_chars(face: &Face, cs: &[char], glyphs: &[Glyph], end: usize) -> Vec<Option<char>> {
let mut out: Vec<Option<char>> = vec![None; glyphs.len()];
/// order, and characters left over (a ligature such as ฐ with sara u below) are shown by the
/// glyph before them. Each character is shown once, and the glyphs show the characters in typed
/// order wherever that leaves no fewer glyphs showing one, so text read back in drawing order is
/// the typed text: a split Thai sara am is drawn as nikhahit, then any tone mark, then sara aa,
/// so in น้ำ the sara aa shows ำ and the nikhahit, moved before the tone mark, shows none and is
/// drawn as an outline only.
fn glyph_chars(face: &Face, cs: &[char], glyphs: &[Glyph], end: usize) -> Vec<Vec<char>> {
let mut out: Vec<Vec<char>> = vec![Vec::new(); glyphs.len()];
let mut i = 0;
while let Some(cluster) = glyphs.get(i).map(|g| g.cluster) {
let j = glyphs.iter().skip(i).position(|g| g.cluster != cluster).map_or(glyphs.len(), |n| i + n);
// Clusters ascend in a left-to-right run: this one's characters end where the next starts.
let to = glyphs.get(j).map_or(end, |g| g.cluster).clamp(cluster, end.max(cluster));
let chars = cs.get(cluster..to).unwrap_or_default();
let mut free: Vec<Option<char>> = chars.iter().copied().map(Some).collect();
if chars.len() <= MAX_MATCHED_CLUSTER {
let ids = face.glyph_ids(chars);
for n in i..j {
let gid = glyphs.get(n).map(|g| g.gid);
let own = ids.iter().zip(&free).position(|(id, f)| f.is_some() && *id == gid);
if let (Some(p), Some(o)) = (own, out.get_mut(n)) {
*o = free.get_mut(p).and_then(Option::take);
}
}
}
let mut rest = free.into_iter().flatten();
for o in out.iter_mut().take(j).skip(i).filter(|o| o.is_none()) {
*o = rest.next();
let ids = if chars.len() <= MAX_MATCHED_CLUSTER { face.glyph_ids(chars) } else { Vec::new() };
let gids: Vec<u32> = glyphs.get(i..j).unwrap_or_default().iter().map(|g| g.gid).collect();
let any = cluster_chars(chars, &ids, &gids, false).unwrap_or_default();
// Output that keeps one character per glyph (render, PDF) writes each glyph's first: typed
// order must not leave fewer of them than the plain assignment.
let firsts = |s: &[Vec<char>]| s.iter().filter(|c| !c.is_empty()).count();
let shows = cluster_chars(chars, &ids, &gids, true).filter(|t| firsts(t) >= firsts(&any)).unwrap_or(any);
for (o, s) in out.iter_mut().skip(i).zip(shows) {
*o = s;
}
i = j;
}
out
}
/// The characters each glyph `gids` of one cluster shows, of the cluster's characters `chars`
/// with their own glyph ids `ids` (empty: none matched): a glyph that is a character's own glyph
/// takes that character first, then the other glyphs take the remaining characters in order,
/// and the cluster's last glyph takes those left over. `typed`: own glyphs are matched in typed
/// order only and a character with no glyph of its own between them goes with the glyph before
/// it, so the glyphs show the characters in typed order; `None` when a character comes before
/// every glyph that shows one (a vowel sign drawn before its consonant).
fn cluster_chars(chars: &[char], ids: &[Option<u32>], gids: &[u32], typed: bool) -> Option<Vec<Vec<char>>> {
let mut taken = vec![false; chars.len()];
let mut at: Vec<Vec<usize>> = vec![Vec::new(); gids.len()];
let mut from = 0;
for (a, gid) in at.iter_mut().zip(gids) {
let own = ids.iter().zip(&taken).enumerate().skip(from).find(|(_, (id, t))| !**t && **id == Some(*gid)).map(|(p, _)| p);
if let Some(p) = own {
a.push(p);
taken.get_mut(p).into_iter().for_each(|t| *t = true);
from = if typed { p + 1 } else { 0 };
}
}
// The characters before `next` are shown; `last` is the glyph that shows the latest one.
let (mut next, mut last): (usize, Option<usize>) = (0, None);
for k in 0..at.len() {
match at.get(k).and_then(|a| a.first()).copied() {
Some(p) if typed => {
if next < p {
at.get_mut(last?)?.extend(next..p);
}
(next, last) = (p + 1, Some(k));
}
Some(_) => {}
None => {
while !typed && taken.get(next) == Some(&true) {
next += 1;
}
if taken.get(next) == Some(&false) {
at.get_mut(k)?.push(next);
(next, last) = (next + 1, Some(k));
}
}
}
}
let rest: Vec<usize> = (next..chars.len()).filter(|p| taken.get(*p) == Some(&false)).collect();
if !rest.is_empty() {
at.last_mut()?.extend(rest);
}
Some(at.into_iter().map(|a| a.into_iter().filter_map(|p| chars.get(p).copied()).collect()).collect())
}
#[cfg(test)]
mod tests {
use super::*;
/// A single empty glyph with a positive advance, without relying on installed fonts.
fn empty_glyph_face() -> Face {
mapped_face(&[])
}
/// [`empty_glyph_face`] with a character map: each character to its glyph id (all ids draw
/// the one empty glyph).
fn mapped_face(map: &[(char, u32)]) -> Face {
let mut head = vec![0_u8; 54];
head[..4].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
head[18..20].copy_from_slice(&1000_u16.to_be_bytes());
@@ -297,7 +350,16 @@ mod tests {
hhea[4..6].copy_from_slice(&800_i16.to_be_bytes());
hhea[6..8].copy_from_slice(&(-200_i16).to_be_bytes());
hhea[34..36].copy_from_slice(&1_u16.to_be_bytes());
let mut cmap = Vec::from([0, 0, 0, 1, 0, 3, 0, 10, 0, 0, 0, 12, 0, 12, 0, 0]); // Format 12 at 12.
let len = u32::try_from(16 + 12 * map.len()).unwrap();
cmap.extend(len.to_be_bytes().into_iter().chain([0; 4]).chain(u32::try_from(map.len()).unwrap().to_be_bytes()));
let mut map = map.to_vec();
map.sort_unstable();
for (c, gid) in map {
cmap.extend([u32::from(c), u32::from(c), gid].into_iter().flat_map(u32::to_be_bytes));
}
let tables = [
(*b"cmap", cmap),
(*b"head", head),
(*b"hhea", hhea),
(*b"hmtx", vec![1, 244, 0, 0]), // Advance 500, left side bearing 0.
@@ -305,7 +367,7 @@ mod tests {
];
let mut bytes = vec![0_u8; 12 + tables.len() * 16];
bytes[..4].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
bytes[4..6].copy_from_slice(&4_u16.to_be_bytes());
bytes[4..6].copy_from_slice(&u16::try_from(tables.len()).unwrap().to_be_bytes());
bytes[6..8].copy_from_slice(&64_u16.to_be_bytes());
bytes[8..10].copy_from_slice(&2_u16.to_be_bytes());
for (i, (tag, data)) in tables.into_iter().enumerate() {
@@ -446,6 +508,38 @@ mod tests {
assert!(!needed("50x50 mm.") && !needed("Ünïcödé %%c25") && !needed(""));
}
/// The shaper splits sara am (ำ) into nikhahit and sara aa and draws the nikhahit before a
/// tone mark: in drawing order the glyphs still show the typed text, each character on a
/// glyph of its own, of its parts or before it (issue #2899). A glyph drawn before the
/// character it stands for (a vowel sign before its consonant) keeps its own character: no
/// character is moved onto another glyph to keep the order.
#[test]
fn reordered_glyphs_show_their_cluster_in_typed_order() {
let (no, mai_tho, sara_am, nikhahit, sara_aa) = ('\u{0E19}', '\u{0E49}', '\u{0E33}', '\u{0E4D}', '\u{0E32}');
let (deva_ka, deva_i, sara_u) = ('\u{0915}', '\u{093F}', '\u{0E38}');
let face = mapped_face(&[(no, 1), (mai_tho, 2), (sara_am, 3), (nikhahit, 4), (sara_aa, 5), (deva_ka, 6), (deva_i, 7), (sara_u, 8)]);
let with_gids = |gids: &[u32]| gids.iter().map(|gid| Glyph { gid: *gid, ..glyph(0) }).collect::<Vec<_>>();
let cs = [no, mai_tho, sara_am];
// What the shaper draws for น้ำ: no, nikhahit, mai tho, sara aa.
let shows = glyph_chars(&face, &cs, &with_gids(&[1, 4, 2, 5]), cs.len());
assert_eq!(shows.iter().flatten().collect::<String>(), "น้ำ");
assert_eq!(shows.get(2), Some(&vec![mai_tho]), "the tone mark's glyph shows the tone mark: {shows:?}");
// A sara u drawn into the letter's glyph goes with it, before the tone mark.
let cs = [no, sara_u, mai_tho];
let shows = glyph_chars(&face, &cs, &with_gids(&[1, 2]), cs.len());
assert_eq!(shows, [vec![no, sara_u], vec![mai_tho]]);
// Typed with the tone mark before sara u but drawn after it: in typed order the tone mark
// would only follow no on its glyph, and output that writes a glyph's first character
// would lose it, so each glyph keeps its own character.
let cs = [no, mai_tho, sara_u];
let shows = glyph_chars(&face, &cs, &with_gids(&[1, 8, 2]), cs.len());
assert_eq!(shows, [vec![no], vec![sara_u], vec![mai_tho]]);
// Devanagari ki: the vowel sign is drawn first.
let cs = [deva_ka, deva_i];
let shows = glyph_chars(&face, &cs, &with_gids(&[7, 6]), cs.len());
assert_eq!(shows, [vec![deva_i], vec![deva_ka]]);
}
fn glyph(cluster: usize) -> Glyph {
Glyph { gid: 0, cluster, advance: 500.0, dx: 0.0, dy: 0.0 }
}
@@ -459,17 +553,20 @@ mod tests {
// A run from index 1: cluster 1 has "ab" (two glyphs), cluster 3 has "cd" and a split
// character's extra glyph, which shows nothing.
let gs = Vec::from([1, 1, 3, 3, 3].map(glyph));
assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![Some('a'), Some('b'), Some('c'), Some('d'), None]);
assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![vec!['a'], vec!['b'], vec!['c'], vec!['d'], vec![]]);
// A ligature (ฐ with sara u below as one glyph) shows every character of its cluster.
let gs = Vec::from([1, 3].map(glyph));
assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![vec!['a', 'b'], vec!['c', 'd']]);
// Clusters out of order, past the run or past the line show nothing and don't panic.
let gs = Vec::from([3, 1, usize::MAX, 9].map(glyph));
assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![None, Some('a'), None, None]);
assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![vec![], vec!['a', 'b', 'c', 'd'], vec![], vec![]]);
assert!(glyph_chars(&face, &cs, &[], 5).is_empty());
// A cluster longer than the matching limit still shows each character once, in order.
let long: Vec<char> = std::iter::once('ก').chain(std::iter::repeat_n('\u{0E48}', MAX_CHARS)).collect();
let gs: Vec<Glyph> = (0..long.len()).map(|_| glyph(0)).collect();
let shows = glyph_chars(&face, &long, &gs, long.len());
assert_eq!(shows.first(), Some(&Some('ก')));
assert!(shows.iter().all(Option::is_some));
assert_eq!(shows.first(), Some(&vec!['ก']));
assert!(shows.iter().all(|s| s.len() == 1));
}
/// An installed font with Thai, or `None` (the tests then skip).
+7 -7
View File
@@ -408,15 +408,15 @@ pub struct TextGlyph {
}
impl Shaped {
/// Add a glyph outline and, when it is a font glyph, its [`TextGlyph`].
/// An empty outline is retained only when text metadata needs its slot.
pub(crate) fn push_glyph(&mut self, contours: Vec<Vec<Vec2>>, text: Option<TextGlyph>) {
if contours.is_empty() && text.is_none() {
/// Add a glyph outline and, when it is a font glyph, its [`TextGlyph`] (one per character it
/// shows: a ligature shows several). An empty outline is retained only when text metadata
/// needs its slot.
pub(crate) fn push_glyph(&mut self, contours: Vec<Vec<Vec2>>, text: impl IntoIterator<Item = TextGlyph>) {
let (outline, before) = (self.glyphs.len(), self.text.len());
self.text.extend(text.into_iter().map(|t| TextGlyph { outline, ..t }));
if contours.is_empty() && self.text.len() == before {
return;
}
if let Some(t) = text {
self.text.push(TextGlyph { outline: self.glyphs.len(), ..t });
}
self.glyphs.push(contours);
}
/// Apply a point transform to every vertex (an affine map: text glyphs keep their axes).
+144 -4
View File
@@ -903,6 +903,73 @@ pub fn object_records(d: &Drawing) -> Vec<ObjectRecord> {
.collect()
}
/// The `dependentOnObject` handle (first group 330 inside the `AcDbAssocDependency` subclass) of
/// a kept associative dependency, when it is non-null.
fn assoc_dependency_target(o: &ForeignObject) -> Option<String> {
let mut in_dep = false;
for r in &o.tags {
if r.code == 100 {
if in_dep {
break;
}
in_dep = r.value.trim().eq_ignore_ascii_case("AcDbAssocDependency");
} else if in_dep && r.code == 330 {
let v = norm(&r.value);
return (!v.is_empty() && v != "0").then_some(v);
}
}
None
}
/// The groups of an `AcDbAssocAction` subclass before its dependency count: `100 AcDbAssocAction`,
/// `90` version, `90` status, `330` network, `360` body, `90` index and `90` highest dependency index.
const ASSOC_ACTION_HEADER: [i32; 7] = [100, 90, 90, 330, 360, 90, 90];
/// If `tags[at]` is the dependency count (group 90) of an `AcDbAssocAction` subclass, returns the count.
/// The count is followed by one group per dependency: 360 for an owned dependency, 330 for one the
/// action does not own. acadrust writes this layout (`write_assoc_action` in acadrust 0.6.6's
/// `io/dxf/writer/section_writer/associative.rs`) and reads it back (`read_action` in
/// `io/dxf/reader/section_reader/associative.rs`). A DWG reaches this code through that writer, so a
/// kept action from a DWG has this form too.
///
/// The match is positional on purpose. When the class version is above 1, the list is followed by
/// `90 0`, `90 n` and n group-360 owned parameters. A loose match on a group 90 before handles also
/// takes that second list.
fn assoc_action_dep_count(tags: &[RawTag], at: usize) -> Option<usize> {
if at < ASSOC_ACTION_HEADER.len() || tags.get(at)?.code != 90 {
return None;
}
let start = at - ASSOC_ACTION_HEADER.len();
if !tags[start].value.trim().eq_ignore_ascii_case("AcDbAssocAction") {
return None;
}
if !ASSOC_ACTION_HEADER.iter().enumerate().all(|(k, &c)| tags[start + k].code == c) {
return None;
}
let count = usize::try_from(tags[at].value.trim().parse::<i64>().ok()?).ok()?;
let deps = tags.get(at + 1..at + 1 + count)?;
deps.iter().all(|t| matches!(t.code, 330 | 360)).then_some(count)
}
/// The index of a kept object's `100 AcDbAssocAction` marker. An associative network derives from
/// an action, so it has one too.
fn assoc_action_marker(tags: &[RawTag]) -> Option<usize> {
tags.iter().position(|t| t.code == 100 && t.value.trim().eq_ignore_ascii_case("AcDbAssocAction"))
}
/// The dependency list of a kept action that [`assoc_action_dep_count`] recognizes: the index of
/// its count group and the count.
fn assoc_action_list(tags: &[RawTag]) -> Option<(usize, usize)> {
let at = assoc_action_marker(tags)? + ASSOC_ACTION_HEADER.len();
Some((at, assoc_action_dep_count(tags, at)?))
}
/// Whether a kept object is an action whose dependency list has a form we do not know. Its list
/// cannot be rewritten, so the dependencies it owns are not pruned.
fn is_unknown_assoc_action(tags: &[RawTag]) -> bool {
assoc_action_marker(tags).is_some() && assoc_action_list(tags).is_none()
}
/// Remaps the kept data's handles onto a written file.
struct Map<'a> {
f: &'a Foreign,
@@ -954,6 +1021,7 @@ impl Map<'_> {
fn object(&self, o: &ForeignObject, out: &mut Vec<Tag>) {
out.push(Tag::s(0, o.kind.clone()));
let dict = is_dictionary(&o.kind);
let list = assoc_action_list(&o.tags);
let mut i = 0;
while let Some(r) = o.tags.get(i) {
i += 1;
@@ -997,6 +1065,16 @@ impl Map<'_> {
}
continue;
}
if let Some((_, count)) = list.filter(|&(at, _)| at == i - 1) {
// An entry keeps its own group code. A null entry stays null, because [`Map::get`]
// gives "0" only for a null handle. An entry whose object is gone is left out, and
// the count follows.
let live: Vec<Tag> = o.tags[i..i + count].iter().filter_map(|n| self.get(&n.value).map(|h| Tag::s(n.code, h))).collect();
out.push(Tag::i(90, i64::try_from(live.len()).unwrap_or(i64::MAX)));
out.extend(live);
i += count;
continue;
}
if r.code == 5 {
out.push(Tag::s(5, self.get(&r.value).unwrap_or_else(|| "0".into())));
continue;
@@ -1166,7 +1244,7 @@ pub(crate) fn finish(
(o.handle.hex(), head(&t).owner)
})
.collect();
let alive_memo = settle(&hard, |kept: &HashMap<String, bool>| {
let mut alive_memo = settle(&hard, |kept: &HashMap<String, bool>| {
// 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);
@@ -1207,6 +1285,64 @@ pub(crate) fn finish(
}
alive_memo
});
// Drop kept AcDbAssocDependency objects whose dependentOnObject is no longer written. Also drop
// the kept objects whose owner, as [`owner_of`] finds it, is a dropped dependency. Leaving an
// active dependency with its group 330 remapped to "0" breaks the associative reactor invariant.
let entities: HashSet<String> = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect();
// A dependency stays when an action of unknown form names it by group 330 or 360, or is its
// owner. That action's list and count stay as read, and only the dangling target becomes null.
// Each kept action is classified once, here.
let unknown_actions: Vec<&ForeignObject> = f.objects.iter().filter(|o| is_unknown_assoc_action(&o.tags)).collect();
let unknown_handles: HashSet<String> = unknown_actions.iter().map(|o| o.handle.hex()).collect();
let unknown_refs: HashSet<String> = unknown_actions
.iter()
.flat_map(|o| o.tags.iter().take_while(|t| t.code < 1000).filter(|t| matches!(t.code, 330 | 360)).map(|t| norm(&t.value)))
.collect();
let in_unknown_action =
|h: &str| unknown_refs.contains(h) || own.get(h).and_then(Option::as_deref).is_some_and(|owner| unknown_handles.contains(owner));
// Each pass that changes something drops at least one live object, so the loop ends.
loop {
let mut changed = false;
for o in &f.objects {
let h = o.handle.hex();
if alive_memo.get(&h) != Some(&true) || in_unknown_action(&h) {
continue;
}
let dead_target = assoc_dependency_target(o).is_some_and(|t| {
if objs.contains_key(&t) {
alive_memo.get(&t) != Some(&true)
} else if let Some(role) = handle(&t).and_then(|th| f.targets.get(&th)) {
!roles.contains_key(role)
} else {
!entities.contains(&t)
}
});
if dead_target {
alive_memo.insert(h, false);
changed = true;
}
}
if !changed {
break;
}
// The owner is found as for the first liveness pass ([`owner_of`]). A null-owner child goes
// with its hard owner, and a child with another live hard owner stays.
let mut cascade = true;
while cascade {
cascade = false;
for o in &f.objects {
let h = o.handle.hex();
if alive_memo.get(&h) != Some(&true) {
continue;
}
let owner = owner_of(own.get(&h).cloned().flatten(), &h, &hard, |x| alive_memo.get(x) == Some(&true));
if owner.is_some_and(|owner| objs.contains_key(&owner) && alive_memo.get(&owner) != Some(&true)) {
alive_memo.insert(h, false);
cascade = true;
}
}
}
}
// New handles for the written kept objects, above every written handle and the seed.
let mut fresh = Fresh::new(tags);
// The entities of unmodeled types join the records only below, so their handles are not in
@@ -1224,7 +1360,6 @@ pub(crate) fn finish(
}
}
let merged_into: HashMap<String, &ForeignObject> = merged.iter().filter_map(|(kept, own)| Some((own.clone(), *objs.get(kept)?))).collect();
let entities: HashSet<String> = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect();
let map = Map { f, alive, raw: objs.keys().cloned().collect(), roles, entities };
let mut out: Vec<Tag> = Vec::with_capacity(tags.len() + f.objects.iter().map(|o| o.tags.len() + 1).sum::<usize>());
let mut block = String::new();
@@ -1263,7 +1398,9 @@ pub(crate) fn finish(
let x = extra_for(f, &xd, r, b, &block);
let joined = joined_into(&merged_into, b);
if x.is_none() && Some(r.start) != root && joined.is_none() {
out.extend(b.iter().cloned());
out.extend(b.iter().map(|tag| {
if r.kind == "LAYOUT" && tag.code == 333 { Tag::s(333, map.get(&tag.str()).unwrap_or_else(|| "0".into())) } else { tag.clone() }
}));
continue;
}
record(&map, r, b, x.as_deref(), None, Some(r.start) == root, &mut out);
@@ -1379,6 +1516,8 @@ fn plan_unknown(
};
let br = |name: &str| roles.get(&("BLOCK_RECORD".to_string(), up(name))).cloned();
let first_at = |s: &cadcraft_doc::EntityStore| s.iter().find_map(|e| at.get(&e.handle.hex()).copied());
// The LAYER table as written: proxy graphics name layers by their index in it (#3094).
let written_layers: Vec<String> = recs.iter().filter(|r| r.sec == "TABLES" && r.kind == "LAYER").filter_map(|r| val(body(r), 2)).collect();
let layouts = d.paper_space_layouts();
// (entities, owner, paper space, end of the space, section)
let mut stores: Vec<(&cadcraft_doc::EntityStore, Option<String>, bool, Option<usize>, &str)> = Vec::new();
@@ -1406,7 +1545,8 @@ fn plan_unknown(
{
continue;
}
let t = unknown_entity(u, e, &owner, paper);
let remapped = u.with_proxy_layers(&d.proxy_layers, &written_layers).map(|tags| Unknown { tags, ..u.clone() });
let t = unknown_entity(remapped.as_ref().unwrap_or(u), e, &owner, paper);
if !t.is_empty() {
pending.push((sec.to_string(), t));
}
+62
View File
@@ -98,6 +98,64 @@ fn keep_file_order<T>(items: &mut [T], name: impl Fn(&T) -> &str, order: &[Strin
});
}
/// A dimension kept as read (LARGE_RADIAL_DIMENSION, ARC_DIMENSION) draws its `*D` block, as
/// AutoCAD does, in place of the proxy graphics it may carry: those can differ from what AutoCAD
/// shows (an exporter's picture without the arrowheads; #3438). Its graphics become one reference
/// to that block, with the dimension's handle, so it is drawn, measured and picked like a proxy.
/// A reference, not a copy of the contents: nested dimensions, the block's draw order and the
/// renderer's depth and size limits all apply as for any block reference.
fn draw_kept_dimensions_from_their_blocks(d: &mut Drawing) {
let pictures = |store: &cadcraft_doc::EntityStore, d: &Drawing| -> Vec<(Handle, Entity)> {
store
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Unknown(u) => {
let block = d.block(u.dimension_block()?)?;
// The block holds the dimension as drawn, in the dimension's coordinates: placed
// at its base point it draws where it is, as a DIMENSION's block does.
let reference = Insert { block: block.name.clone(), insert: block.base, ..Insert::default() };
// Everything ByBlock, so what the block gives ByBlock is the dimension's own.
let common = Common {
layer: "0".into(),
color: Color::ByBlock,
linetype: "ByBlock".into(),
lineweight: Lineweight::ByBlock,
transparency: Transparency::ByBlock,
plot_style: "ByBlock".into(),
..Common::default()
};
(!block.entities.is_empty()).then(|| (e.handle, Entity { handle: e.handle, common, kind: EntityKind::Insert(reference) }))
}
_ => None,
})
.collect()
};
let apply = |store: &mut cadcraft_doc::EntityStore, found: Vec<(Handle, Entity)>| {
for (h, reference) in found {
store.modify(h, |e| {
if let EntityKind::Unknown(u) = &mut e.kind {
u.graphics = vec![reference];
}
});
}
};
let found = pictures(&d.model, d);
apply(&mut d.model, found);
for i in 0..d.layouts.len() {
let found = pictures(&d.layouts[i].entities, d);
apply(&mut d.layouts[i].entities, found);
}
let names: Vec<String> = d.blocks.keys().cloned().collect();
for name in names {
let found = d.blocks.get(&name).map(|b| pictures(&b.entities, d)).unwrap_or_default();
if !found.is_empty()
&& let Some(b) = d.blocks.get_mut(&name)
{
apply(&mut std::sync::Arc::make_mut(b).entities, found);
}
}
}
/// Read a DXF file into a drawing.
pub fn read(bytes: &[u8]) -> Result<Drawing> {
read_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS)
@@ -205,6 +263,9 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
// Proxy graphics name layers and linetypes by their place in the file's tables, and saving
// writes them unchanged: the tables keep the file's order, with what CADCraft adds after it.
keep_file_order(&mut d.layers, |l| &l.name, &rx.proxy_tables.layers, &[]);
// Saving turns the graphics' layer indices from this order into the written table's, so
// removing or adding layers doesn't move them (#3094).
d.proxy_layers.clone_from(&rx.proxy_tables.layers);
keep_file_order(&mut d.linetypes, |l| &l.name, &rx.proxy_tables.linetypes, &["ByBlock", "ByLayer"]);
// A proxy text takes the first style on its font, so the styles keep the file's order too.
let styles: Vec<String> = rx.proxy_tables.styles.iter().map(|(n, _)| n.clone()).collect();
@@ -215,6 +276,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
let (paper_block_for, first_layout) = setup_layouts(&mut d, &mut layout_objs, &rx);
place_blocks(&mut d, blocks, &mut rx, &paper_block_for, &first_layout);
place_entities(&mut d, entities, &rx, &paper_block_for, &first_layout);
draw_kept_dimensions_from_their_blocks(&mut d);
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);
+29 -4
View File
@@ -119,15 +119,17 @@ pub(super) fn ocs_n(n: Vec3, p: Vec3) -> Vec3 {
/// billionth of the object's size and distance from the origin. A normal that is the Z axis
/// or the Z axis turned over moves nothing, and noise in one moves points by a negligible
/// amount, so those objects keep their arcs; however small the tilt, an object far enough from
/// the origin to be moved visibly is projected.
pub(super) fn tilted(n: Vec3, pts: impl IntoIterator<Item = Vec3>) -> bool {
if !n.is_finite() || n.len() < 1e-12 {
/// the origin to be moved visibly is projected. The points are only gathered for a normal off
/// the Z axis: along it (x and y exactly 0, as in nearly every drawing) nothing moves, and
/// sampling every arc of every object for that would be wasted.
pub(super) fn tilted<I: IntoIterator<Item = Vec3>>(n: Vec3, pts: impl FnOnce() -> I) -> bool {
if !n.is_finite() || n.len() < 1e-12 || (n.x == 0.0 && n.y == 0.0) {
return false;
}
let m = cadcraft_geom::Mat4::ocs(n);
let flip = if n.z < 0.0 { -1.0 } else { 1.0 };
let (mut moved, mut reach) = (0.0f64, 1.0f64);
for p in pts.into_iter().filter(|p| p.is_finite()) {
for p in pts().into_iter().filter(|p| p.is_finite()) {
let shown = Vec2::new(flip * p.x, p.y);
moved = moved.max((m.apply(p).xy() - shown).len());
reach = reach.max(p.x.abs()).max(p.y.abs()).max(p.z.abs());
@@ -204,3 +206,26 @@ pub(super) fn plan_of_tilted(n: Vec3, elevation: f64, vertices: &[PolyVertex], c
let z = if local.is_empty() { elevation } else { local.iter().map(|v| to_plan(v.p).z).sum::<f64>() / local.len() as f64 };
(local.into_iter().map(|v| PolyVertex { p: to_plan(v.p).xy(), ..v }).collect(), z)
}
#[cfg(test)]
mod tests {
use super::*;
/// A normal on the Z axis, either way up and of any length, moves no point, so [`tilted`]
/// answers without sampling the object's arcs; any other normal gathers them.
#[test]
fn a_normal_on_the_z_axis_gathers_no_points() {
let gathered = std::cell::Cell::new(0);
let pts = || {
gathered.set(gathered.get() + 1);
vec![Vec3::new(1.0, 2.0, 3.0)]
};
for n in [Vec3::Z, Vec3::new(0.0, 0.0, -1.0), Vec3::new(0.0, 0.0, 2.5), Vec3::new(-0.0, 0.0, -0.1)] {
assert!(!tilted(n, pts), "{n:?}");
}
assert_eq!(gathered.get(), 0);
assert!(tilted(Vec3::new(0.0, 0.5, -0.75f64.sqrt()), pts));
assert!(!tilted(Vec3::new(0.0, 1e-15, 1.0), pts), "noise in a plan normal still moves nothing visible");
assert_eq!(gathered.get(), 2);
}
}
+1
View File
@@ -213,6 +213,7 @@ pub(super) fn setup_layouts(d: &mut Drawing, layout_objs: &mut [LayoutDef], rx:
layout_objs.sort_by_key(|l| l.1);
for (name, order, br, page, limits) in layout_objs.iter() {
if name.eq_ignore_ascii_case("Model") {
d.model_page = Some(page.clone());
continue;
}
d.layouts.push(Layout { page: page.clone(), limits: *limits, ..Layout::new(name, *order) });
+13 -7
View File
@@ -84,7 +84,7 @@ fn lwpolyline(tags: &[Tag], c: &mut Common, t: &T) -> Option<EntityKind> {
verts.extend(cur);
let flags = t.i(70).unwrap_or(0);
let mut elevation = t.fd(38, 0.0);
if tilted(c.extrusion, run_points(&verts, elevation, flags & 1 != 0)) {
if tilted(c.extrusion, || run_points(&verts, elevation, flags & 1 != 0)) {
// 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);
@@ -244,7 +244,7 @@ pub(super) fn entity_with_table_budget(
"HATCH" => {
let mut k = hatch(tags, &t, curves)?;
if let EntityKind::Hatch(h) = &mut k
&& tilted(c.extrusion, h.loops.iter().flat_map(|l| run_points(&l.vertices, h.elevation, true)))
&& tilted(c.extrusion, || h.loops.iter().flat_map(|l| run_points(&l.vertices, h.elevation, true)))
{
// In a tilted plane (a terrain face, a slope): the boundary as seen from above,
// at its mean height, and the pattern direction and origin projected the same way.
@@ -382,8 +382,13 @@ pub(super) fn acad_table(tags: &[Tag], table_cells_left: &mut usize) -> Table {
let cell = body.get(i..end).unwrap_or(&[]);
i = end;
let c = T(cell);
let mut text: String = cell.iter().filter(|x| x.code == 2 || x.code == 3).map(Tag::str).collect();
text.push_str(&c.s(1).unwrap_or_default());
let text: String = if cell.iter().any(|x| x.code == 1) {
let mut text: String = cell.iter().filter(|x| x.code == 2 || x.code == 3).map(Tag::str).collect();
text.push_str(&c.s(1).unwrap_or_default());
text
} else {
cell.iter().filter(|x| x.code == 302 || x.code == 303).map(Tag::str).collect()
};
let span = |code: i32| c.i(code).and_then(|v| u32::try_from(v).ok());
// A merge starts at the cell whose span (rows 176, columns 175) is more than one cell.
// Its own merged flag (173) varies by writer: CADCraft sets it, while AutoCAD-style
@@ -489,8 +494,9 @@ pub(super) fn entity_plot_style(tags: &[Tag], rx: &Rx) -> Option<String> {
/// needs the file's handle maps.
pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityKind, rx: &mut Rx) {
match (kind, k) {
// Its proxy graphics, with the table indices resolved while the file's order is known.
("ACAD_PROXY_ENTITY", EntityKind::Unknown(u)) => {
// Its proxy graphics (a proxy's, or the picture another kept entity was saved with), with
// the table indices resolved while the file's order is known.
(_, EntityKind::Unknown(u)) => {
u.graphics = cadcraft_doc::proxy_entities(&u.proxy_graphics_bytes(), &rx.proxy_tables, h);
}
("DIMENSION", EntityKind::Dimension(dm)) => {
@@ -610,7 +616,7 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
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)) {
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;
+2 -1
View File
@@ -215,7 +215,8 @@ fn elliptic_edge(tags: &[Tag], index: &mut usize, vertices: &mut Vec<PolyVertex>
if !ccw {
points.reverse();
}
vertices.extend(points.into_iter().map(PolyVertex::new));
let skip = usize::from(vertices.last().zip(points.first()).is_some_and(|(last, point)| last.p.near(*point, 1e-9)));
vertices.extend(points.into_iter().skip(skip).map(PolyVertex::new));
}
fn spline_edge(tags: &[Tag], index: &mut usize, vertices: &mut Vec<PolyVertex>, budget: &mut EdgeBudget) {
+4
View File
@@ -445,6 +445,7 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
Some(0) => "display",
Some(1) => "extents",
Some(2) => "limits",
Some(3) => "view",
Some(4) => "window",
_ => "layout",
}
@@ -455,6 +456,9 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
// 0,0 is what a page without one writes, so it reads back as none.
p.image_origin =
t.f(148).zip(t.f(149)).map(|(x, y)| Vec2::new(x, y)).filter(|o| o.is_finite() && o.x.abs() < 1e12 && o.y.abs() < 1e12 && *o != Vec2::ZERO);
if let Some(start) = t.0.iter().position(|tag| tag.code == 100 && tag.str() == "AcDbPlotSettings") {
p.file_plot_settings = Some(Box::new(cadcraft_doc::FilePlotSettings { tags: t.0[start + 1..].to_vec(), page: p.clone() }));
}
p
}
+12
View File
@@ -296,6 +296,18 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) {
for (kind, tags) in recs {
let table = T(tags);
// Proxy graphics count every LAYER and LTYPE record, so one without a handle or a name
// keeps its place in the index lists (an empty name) and the records after it don't
// shift (#3094).
if table.s(5).is_none() || table.s(2).is_none() {
let name = table.s(2).unwrap_or_default();
match kind.as_str() {
"LAYER" => rx.proxy_tables.layers.push(name),
"LTYPE" if !name.eq_ignore_ascii_case("ByBlock") && !name.eq_ignore_ascii_case("ByLayer") => rx.proxy_tables.linetypes.push(name),
_ => {}
}
continue;
}
let (Some(handle), Some(name)) = (table.s(5), table.s(2)) else { continue };
match kind.as_str() {
"STYLE" => {
+3
View File
@@ -35,6 +35,9 @@ pub(super) fn dim_block_plan(d: &Drawing) -> DimBlockPlan {
}
EntityKind::MLeader(m) => used.extend(m.block.as_ref().map(|b| b.block.to_ascii_uppercase())),
EntityKind::Dimension(dm) if dims => used.extend(dm.block.as_ref().map(|n| n.to_ascii_uppercase())),
// A dimension kept as read (LARGE_RADIAL_DIMENSION, ARC_DIMENSION) is written with the
// block it names, which AutoCAD needs to read it (#1161).
EntityKind::Unknown(u) => used.extend(u.dimension_block().map(str::to_ascii_uppercase)),
_ => {}
};
for e in spaces.iter().flat_map(|s| s.iter()) {
+1
View File
@@ -53,6 +53,7 @@ pub(super) struct Ctx {
/// The version the file ends up in (the DWG version for a DWG save): it decides which
/// entity types exist (MULTILEADER from 2007).
pub(super) target: Version,
pub(super) modern_table_values: bool,
/// A VIEWPORT's frozen layers in group 341, as an R2000 DXF has them; otherwise 331 (DXF 2004
/// and later, and the DWG bridge, which reads only 331).
pub(super) frozen_341: bool,
+22 -4
View File
@@ -522,27 +522,45 @@ fn write_table_entity(w: &mut W, _d: &Drawing, e: &Entity, owner: &str, paper: b
let merge = cell.and_then(|x| x.merged).filter(|&(a, b)| a >= 1 && b >= 1 && (a, b) != (1, 1));
w.i(171, 1);
w.i(172, 0);
w.i(173, i64::from(covered || merge.is_some()));
w.i(173, i64::from(covered || (!cx.modern_table_values && merge.is_some())));
w.i(174, 0);
let (rs, cs) = if covered { (0, 0) } else { merge.map(|(a, b)| (span(a), span(b))).unwrap_or((1, 1)) };
w.i(175, cs);
w.i(176, rs);
w.i(91, 0);
if cx.modern_table_values {
w.i(92, 0);
}
w.i(178, 0);
w.f(145, 0.0);
if let Some(h) = cell.and_then(|x| x.text_height).filter(|h| h.is_finite() && *h > 0.0) {
w.f(140, h);
}
// Long text: 250-character code-2 chunks, the rest in code 1.
let chars: Vec<char> = cell.map(|x| x.text.chars().collect()).unwrap_or_default();
if cx.modern_table_values {
w.s(301, "CELL_VALUE");
w.i(93, 4);
w.i(90, 4);
}
let chars: Vec<char> = cell.filter(|_| !cx.modern_table_values || !covered).map(|x| x.text.chars().collect()).unwrap_or_default();
let chunks: Vec<String> = chars.chunks(250).map(|c| c.iter().collect()).collect();
let n = chunks.len();
for (i, ch) in chunks.into_iter().enumerate() {
for (i, ch) in chunks.iter().enumerate() {
w.s(if i + 1 == n { 1 } else { 2 }, ch);
}
if n == 0 {
w.s(1, "");
}
if cx.modern_table_values {
w.i(94, 0);
w.s(300, "");
for (i, ch) in chunks.iter().enumerate() {
w.s(if i + 1 == n { 302 } else { 303 }, ch);
}
if n == 0 {
w.s(302, "");
}
w.s(304, "ACVALUE_END");
}
}
}
w.s(1001, dxf_ext::APP);
+99 -13
View File
@@ -440,30 +440,33 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
let d = context.drawing;
let layout_dict = context.dictionary;
let h = data.handle;
let name = data.name;
let tab = data.tab;
let brh = data.block_record;
let flags = data.flags;
let page = data.page;
let view = data.view;
w.s(0, "LAYOUT");
w.s(5, h);
w.s(330, layout_dict.to_string());
w.s(100, "AcDbPlotSettings");
write_plot_settings(w, d, page, data.model);
write_layout_data(w, d, data, view);
}
fn write_plot_settings(w: &mut W, d: &Drawing, page: &PageSetup, model: bool) {
let start = w.t.len();
// Plot scale: a standard scale when fitting or 1:1, otherwise custom (142 paper units
// per 143 drawing units).
let scale = if page.scale.is_finite() && page.scale > 0.0 { page.scale } else { 1.0 };
// The file's standard scale (such as 1:50) while the scale is still the one read with it.
let file_standard = page.file_standard_scale.filter(|&(_, s)| !page.scale_to_fit && s == scale).map(|(code, _)| code);
let standard = page.scale_to_fit || scale == 1.0 || file_standard.is_some();
let plot_flags = plot_layout_flags(page, standard, data.model);
let plot_flags = plot_layout_flags(page, standard, model);
let plot_type = match page.plot_area.as_str() {
"display" => 0,
"extents" => 1,
"limits" => 2,
"view" => 3,
"window" => 4,
_ => 5,
};
w.s(0, "LAYOUT");
w.s(5, h);
w.s(330, layout_dict.to_string());
w.s(100, "AcDbPlotSettings");
w.s(1, "");
let device = page.device.trim();
w.s(2, if device.is_empty() || device.eq_ignore_ascii_case("None") { "none_device" } else { device });
@@ -500,6 +503,49 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
let origin = page.image_origin.filter(|o| o.is_finite()).unwrap_or(Vec2::ZERO);
w.f(148, origin.x);
w.f(149, origin.y);
if let Some(kept) = &page.file_plot_settings {
let current = w.t.split_off(start);
write_plot_settings(w, d, &kept.page, model);
let baseline = w.t.split_off(start);
let changed = |code| {
(matches!(code, 142 | 143 | 147) && page.scale != kept.page.scale)
|| (code == 72
&& (page.paper_mm != kept.page.paper_mm
|| (page.paper_mm.is_none()
&& kept
.tags
.iter()
.find(|tag| tag.code == 72)
.zip(current.iter().find(|tag| tag.code == 72))
.is_some_and(|(old, now)| matches!(old.i64(), 0 | 1) && old.i64() != now.i64()))))
|| current.iter().find(|tag| tag.code == code) != baseline.iter().find(|tag| tag.code == code)
};
for tag in &kept.tags {
if changed(tag.code) || (tag.code == 73 && !(0..=3).contains(&tag.i64())) {
if tag.code == 70
&& let Some((now, before)) = current.iter().find(|tag| tag.code == 70).zip(baseline.iter().find(|tag| tag.code == 70))
{
let mask = (now.i64() ^ before.i64()) | 1024;
w.i(70, (tag.i64() & !mask) | (now.i64() & mask));
continue;
}
w.t.extend(current.iter().filter(|new| new.code == tag.code).cloned());
} else if tag.code == 70 {
w.i(70, if model { tag.i64() | 1024 } else { tag.i64() & !1024 });
} else {
w.t.push(tag.clone());
}
}
w.t.extend(current.iter().filter(|tag| changed(tag.code) && !kept.tags.iter().any(|old| old.code == tag.code)).cloned());
}
}
fn write_layout_data(w: &mut W, d: &Drawing, data: LayoutWriteData<'_>, view: Option<(Vec2, f64)>) {
let name = data.name;
let tab = data.tab;
let flags = data.flags;
let brh = data.block_record;
let page = data.page;
w.s(100, "AcDbLayout");
w.s(1, name);
w.i(70, flags);
@@ -598,8 +644,8 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
w.s(3, &l.name);
w.s(350, layout_handles.get(i).cloned().unwrap_or_default());
}
// Model space has no page setup of its own: write what PLOT does for it, the drawing extents
// fitted to the paper (plot type 1, scaled to fit). The default page's "layout" area is
// A new drawing has no saved Model page setup: write the drawing extents fitted to the
// paper (plot type 1, scaled to fit), as PLOT does. The default page's "layout" area is
// plot type 5, "Layout information" (DXF Reference, PLOTSETTINGS group 74), which means
// nothing for model space: another program's Plot dialog then shows no plot area or scale.
let model_page = PageSetup { plot_area: "extents".into(), scale_to_fit: true, ..PageSetup::default() };
@@ -612,7 +658,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
tab: 0,
block_record: ms_br,
flags: 1,
page: &model_page,
page: d.model_page.as_ref().unwrap_or(&model_page),
view: None,
ucs: None,
limits: None,
@@ -1056,7 +1102,7 @@ pub(super) fn tags_kept_for(
.collect();
user_blocks.iter_mut().for_each(|b| b.1 = format!("{:X}", 0));
let user_blocks: Vec<(String, String, &Block)> = user_blocks.into_iter().map(|(n, _, b)| (n, w.h(), b)).collect();
let mut cx = Ctx { paper_views: paper_views(d), target, frozen_341, ..Ctx::default() };
let mut cx = Ctx { paper_views: paper_views(d), target, frozen_341, modern_table_values: !bridge && version >= Version::R2007, ..Ctx::default() };
cx.block_records = user_blocks.iter().map(|(n, h, _)| (n.to_ascii_uppercase(), h.clone())).collect();
let all_spaces: Vec<&EntityStore> = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).collect();
let mut dim_defs = dimension_block_definitions(d, &all_spaces, &dim_plan, &mut w, &mut cx);
@@ -1297,9 +1343,49 @@ pub(super) fn tags_kept_for(
crate::dxf_raw::data_store(&mut w.t, d, target >= Version::R2013);
add_class_instance_counts(&mut w.t, target);
mark_xrefs(&mut w.t, d);
plot_settings_compatibility(&mut w.t, target);
(w.t, kept)
}
fn plot_settings_compatibility(tags: &mut Vec<Tag>, target: Version) {
let mut objects = HashSet::new();
let mut section = String::new();
let mut section_start = false;
for tag in tags.iter() {
if tag.code == 0 {
section_start = tag.str() == "SECTION";
if tag.str() == "ENDSEC" {
section.clear();
}
} else if section_start && tag.code == 2 {
section = tag.str();
section_start = false;
} else if section == "OBJECTS" && tag.code == 5 {
objects.extend(u64::from_str_radix(tag.str().trim(), 16).ok().filter(|handle| *handle != 0));
}
}
let mut kind = String::new();
let mut subclass = String::new();
tags.retain(|tag| {
if tag.code == 0 {
kind = tag.str();
subclass.clear();
} else if tag.code == 100 {
subclass = tag.str();
}
if !matches!(kind.as_str(), "LAYOUT" | "PLOTSETTINGS") {
return true;
}
if subclass == "AcDbPlotSettings" && matches!(tag.code, 76..=78) {
return target >= Version::R2004;
}
if matches!(subclass.as_str(), "AcDbPlotSettings" | "AcDbLayout") && tag.code == 333 {
return target >= Version::R2007 && u64::from_str_radix(tag.str().trim(), 16).ok().is_some_and(|handle| objects.contains(&handle));
}
true
});
}
/// Paper size (groups 44, 45) and plot rotation (group 73) for a LAYOUT object. Page setups
/// keep a portrait size and a landscape flag. The values read from the file are written back
/// as they were while they still describe that size and orientation, whatever convention the
+508
View File
@@ -0,0 +1,508 @@
0 SECTION
2 HEADER
9 $ACADVER
1 AC1032
9 $HANDSEED
5 200
0 ENDSEC
0 SECTION
2 TABLES
0 TABLE
2 BLOCK_RECORD
5 1
330 0
100 AcDbSymbolTable
70 5
0 BLOCK_RECORD
5 1F
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 *Model_Space
340 0
0 BLOCK_RECORD
5 1E
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 *Paper_Space
340 0
0 BLOCK_RECORD
5 1D
102 {ACAD_XDICTIONARY
360 60
102 }
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 Row
340 0
70 0
280 1
281 1
0 BLOCK_RECORD
5 1C
102 {ACAD_XDICTIONARY
360 70
102 }
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 Fan
340 0
70 0
280 1
281 1
0 BLOCK_RECORD
5 1B
102 {ACAD_XDICTIONARY
360 80
102 }
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 Grid
340 0
70 0
280 1
281 1
0 ENDTAB
0 ENDSEC
0 SECTION
2 BLOCKS
0 BLOCK
5 20
330 1F
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 *Model_Space
70 0
10 0
20 0
30 0
3 *Model_Space
1
0 ENDBLK
5 21
330 1F
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 BLOCK
5 24
330 1D
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 Row
70 2
10 0
20 0
30 0
3 Row
1
0 LWPOLYLINE
5 30
330 1D
100 AcDbEntity
8 0
100 AcDbPolyline
90 4
70 1
10 0
20 0
10 2
20 0
10 2
20 2
10 0
20 2
1001 AcDbBlockRepETag
1070 1
1071 0
1005 30
0 ENDBLK
5 25
330 1D
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 BLOCK
5 26
330 1C
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 Fan
70 2
10 0
20 0
30 0
3 Fan
1
0 CIRCLE
5 40
330 1C
100 AcDbEntity
8 0
100 AcDbCircle
10 0
20 0
30 0
40 1
1001 AcDbBlockRepETag
1070 1
1071 0
1005 40
0 ENDBLK
5 27
330 1C
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 BLOCK
5 28
330 1B
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 Grid
70 2
10 0
20 0
30 0
3 Grid
1
0 CIRCLE
5 50
330 1B
100 AcDbEntity
8 0
100 AcDbCircle
10 0
20 0
30 0
40 1
1001 AcDbBlockRepETag
1070 1
1071 0
1005 50
0 ENDBLK
5 29
330 1B
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 ENDSEC
0 SECTION
2 ENTITIES
0 ENDSEC
0 SECTION
2 OBJECTS
0 DICTIONARY
5 C
330 0
100 AcDbDictionary
281 1
0 DICTIONARY
5 60
330 1D
100 AcDbDictionary
280 1
281 1
3 ACAD_ENHANCEDBLOCK
360 61
0 ACAD_EVALUATION_GRAPH
5 61
330 60
100 AcDbEvalGraph
96 4
97 4
91 0
93 32
95 1
360 62
91 1
93 32
95 4
360 63
0 BLOCKLINEARPARAMETER
5 62
330 61
100 AcDbEvalExpr
90 1
98 33
99 232
100 AcDbBlockElement
300 Linear
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 2
1021 0
1031 0
170 4
91 3
91 2
91 0
91 0
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockLinearParameter
305 Distance1
306
140 0
307
96 0
141 0
142 0
143 0
175 0
0 BLOCKARRAYACTION
5 63
330 61
100 AcDbEvalExpr
90 4
98 33
99 232
100 AcDbBlockElement
300 Array
98 33
99 232
1071 0
100 AcDbBlockAction
70 0
71 1
330 30
1010 4
1020 3
1030 0
100 AcDbBlockArrayAction
92 1
93 1
94 1
95 1
301 Base
302 End
303 UpdatedBase
304 UpdatedEnd
140 1
141 3
0 DICTIONARY
5 70
330 1C
100 AcDbDictionary
280 1
281 1
3 ACAD_ENHANCEDBLOCK
360 71
0 ACAD_EVALUATION_GRAPH
5 71
330 70
100 AcDbEvalGraph
96 4
97 4
91 0
93 32
95 1
360 72
91 1
93 32
95 4
360 73
0 BLOCKPOLARPARAMETER
5 72
330 71
100 AcDbEvalExpr
90 1
98 33
99 232
100 AcDbBlockElement
300 Polar
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 3
1021 4
1031 0
170 4
91 3
91 2
91 0
91 0
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockPolarParameter
305 Distance1
306
307 Angle1
308
140 0
309
96 0
141 0
142 0
143 0
175 0
410
97 0
145 0
146 0
147 0
176 0
0 BLOCKARRAYACTION
5 73
330 71
100 AcDbEvalExpr
90 4
98 33
99 232
100 AcDbBlockElement
300 Array
98 33
99 232
1071 0
100 AcDbBlockAction
70 0
71 1
330 40
1010 4
1020 5
1030 0
100 AcDbBlockArrayAction
92 1
93 1
94 1
95 1
301 Base
302 End
303 UpdatedBase
304 UpdatedEnd
140 1
141 2
0 DICTIONARY
5 80
330 1B
100 AcDbDictionary
280 1
281 1
3 ACAD_ENHANCEDBLOCK
360 81
0 ACAD_EVALUATION_GRAPH
5 81
330 80
100 AcDbEvalGraph
96 4
97 4
91 0
93 32
95 1
360 82
91 1
93 32
95 6
360 83
0 BLOCKXYPARAMETER
5 82
330 81
100 AcDbEvalExpr
90 1
98 33
99 232
100 AcDbBlockElement
300 XY
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 10
1021 10
1031 0
170 4
91 3
91 2
91 4
91 5
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockXYParameter
305 Y Distance1
306 X Distance1
307
308
141 0
140 0
309
97 1
146 0
147 0
148 0
176 0
410
96 1
142 0
143 0
144 0
175 0
0 BLOCKARRAYACTION
5 83
330 81
100 AcDbEvalExpr
90 6
98 33
99 232
100 AcDbBlockElement
300 Array
98 33
99 232
1071 0
100 AcDbBlockAction
70 0
71 1
330 50
1010 12
1020 12
1030 0
100 AcDbBlockArrayAction
92 1
93 1
94 1
95 1
301 Base
302 End
303 UpdatedBase
304 UpdatedEnd
140 4
141 5
0 ENDSEC
0 EOF
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,813 @@
0 SECTION
2 HEADER
9 $ACADVER
1 AC1032
9 $HANDSEED
5 200
0 ENDSEC
0 SECTION
2 TABLES
0 TABLE
2 BLOCK_RECORD
5 1
330 0
100 AcDbSymbolTable
70 6
0 BLOCK_RECORD
5 1F
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 *Model_Space
340 0
0 BLOCK_RECORD
5 1E
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 *Paper_Space
340 0
0 BLOCK_RECORD
5 1D
102 {ACAD_XDICTIONARY
360 60
102 }
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 Grow
340 0
70 0
280 1
281 1
0 BLOCK_RECORD
5 1C
102 {ACAD_XDICTIONARY
360 70
102 }
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 Pinned
340 0
70 0
280 1
281 1
0 BLOCK_RECORD
5 1B
102 {ACAD_XDICTIONARY
360 80
102 }
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 Sheet
340 0
70 0
280 1
281 1
0 BLOCK_RECORD
5 1A
102 {ACAD_XDICTIONARY
360 90
102 }
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 Tag
340 0
70 0
280 1
281 1
0 ENDTAB
0 ENDSEC
0 SECTION
2 BLOCKS
0 BLOCK
5 20
330 1F
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 *Model_Space
70 0
10 0
20 0
30 0
3 *Model_Space
1
0 ENDBLK
5 21
330 1F
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 BLOCK
5 24
330 1D
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 Grow
70 2
10 0
20 0
30 0
3 Grow
1
0 LWPOLYLINE
5 30
330 1D
100 AcDbEntity
8 0
100 AcDbPolyline
90 4
70 1
10 0
20 0
10 2
20 0
10 2
20 2
10 0
20 2
1001 AcDbBlockRepETag
1070 1
1071 1
1005 30
0 CIRCLE
5 31
330 1D
100 AcDbEntity
8 0
100 AcDbCircle
10 1
20 1
30 0
40 0.5
1001 AcDbBlockRepETag
1070 1
1071 2
1005 31
0 ENDBLK
5 25
330 1D
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 BLOCK
5 26
330 1C
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 Pinned
70 2
10 0
20 0
30 0
3 Pinned
1
0 LWPOLYLINE
5 40
330 1C
100 AcDbEntity
8 0
100 AcDbPolyline
90 4
70 1
10 0
20 0
10 2
20 0
10 2
20 2
10 0
20 2
1001 AcDbBlockRepETag
1070 1
1071 1
1005 40
0 ENDBLK
5 27
330 1C
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 BLOCK
5 28
330 1B
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 Sheet
70 2
10 0
20 0
30 0
3 Sheet
1
0 LWPOLYLINE
5 50
330 1B
100 AcDbEntity
8 0
100 AcDbPolyline
90 4
70 1
10 0
20 0
10 2
20 0
10 2
20 2
10 0
20 2
1001 AcDbBlockRepETag
1070 1
1071 1
1005 50
0 ENDBLK
5 29
330 1B
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 BLOCK
5 2A
330 1A
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 Tag
70 2
10 0
20 0
30 0
3 Tag
1
0 LINE
5 B0
330 1A
100 AcDbEntity
8 0
100 AcDbLine
10 1
20 0
30 0
11 4
21 0
31 0
1001 AcDbBlockRepETag
1070 1
1071 1
1005 B0
0 CIRCLE
5 B1
330 1A
100 AcDbEntity
8 0
100 AcDbCircle
10 4
20 0
30 0
40 0.25
1001 AcDbBlockRepETag
1070 1
1071 2
1005 B1
0 CIRCLE
5 B2
330 1A
100 AcDbEntity
8 0
100 AcDbCircle
10 2
20 2
30 0
40 0.5
1001 AcDbBlockRepETag
1070 1
1071 3
1005 B2
0 ENDBLK
5 2B
330 1A
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 ENDSEC
0 SECTION
2 ENTITIES
0 ENDSEC
0 SECTION
2 OBJECTS
0 DICTIONARY
5 C
330 0
100 AcDbDictionary
281 1
0 DICTIONARY
5 60
330 1D
100 AcDbDictionary
280 1
281 1
3 ACAD_ENHANCEDBLOCK
360 61
0 ACAD_EVALUATION_GRAPH
5 61
330 60
100 AcDbEvalGraph
96 3
97 3
91 0
93 32
95 1
360 62
91 1
93 32
95 2
360 63
91 2
93 32
95 3
360 64
0 BLOCKLINEARPARAMETER
5 62
330 61
100 AcDbEvalExpr
90 1
98 33
99 232
100 AcDbBlockElement
300 Linear
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 2
1021 0
1031 0
170 4
91 3
91 2
91 0
91 0
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockLinearParameter
305 Distance1
306
140 0
307
96 1
141 0
142 0
143 0
175 0
0 BLOCKPOINTPARAMETER
5 63
330 61
100 AcDbEvalExpr
90 2
98 33
99 232
100 AcDbBlockElement
300 Point
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock1PtParameter
1010 2
1020 2
1030 0
93 0
170 0
171 0
100 AcDbBlockPointParameter
303 Position1
304
1011 2
1021 2
1031 0
0 BLOCKSCALEACTION
5 64
330 61
100 AcDbEvalExpr
90 3
98 33
99 232
100 AcDbBlockElement
300 Scale
98 33
99 232
1071 0
100 AcDbBlockAction
70 0
71 3
330 30
330 31
330 63
1010 4
1020 3
1030 0
100 AcDbBlockActionWithBasePt
92 1
93 1
301 UpdatedBaseX
302 UpdatedBaseY
1011 0
1021 0
1031 0
280 1
1012 0
1022 0
1032 0
100 AcDbBlockScaleAction
94 1
95 1
96 1
303 Scale
304 XScale
305 YScale
0 DICTIONARY
5 70
330 1C
100 AcDbDictionary
280 1
281 1
3 ACAD_ENHANCEDBLOCK
360 71
0 ACAD_EVALUATION_GRAPH
5 71
330 70
100 AcDbEvalGraph
96 2
97 2
91 0
93 32
95 1
360 72
91 1
93 32
95 2
360 73
0 BLOCKLINEARPARAMETER
5 72
330 71
100 AcDbEvalExpr
90 1
98 33
99 232
100 AcDbBlockElement
300 Linear
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 2
1021 0
1031 0
170 4
91 3
91 2
91 0
91 0
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockLinearParameter
305 Distance1
306
140 0
307
96 0
141 0
142 0
143 0
175 0
0 BLOCKSCALEACTION
5 73
330 71
100 AcDbEvalExpr
90 2
98 33
99 232
100 AcDbBlockElement
300 Scale
98 33
99 232
1071 0
100 AcDbBlockAction
70 0
71 1
330 40
1010 4
1020 3
1030 0
100 AcDbBlockActionWithBasePt
92 1
93 1
301 UpdatedBaseX
302 UpdatedBaseY
1011 0
1021 0
1031 0
280 0
1012 2
1022 2
1032 0
100 AcDbBlockScaleAction
94 1
95 1
96 1
303 Scale
304 XScale
305 YScale
0 DICTIONARY
5 80
330 1B
100 AcDbDictionary
280 1
281 1
3 ACAD_ENHANCEDBLOCK
360 81
0 ACAD_EVALUATION_GRAPH
5 81
330 80
100 AcDbEvalGraph
96 2
97 2
91 0
93 32
95 1
360 82
91 1
93 32
95 2
360 83
0 BLOCKXYPARAMETER
5 82
330 81
100 AcDbEvalExpr
90 1
98 33
99 232
100 AcDbBlockElement
300 XY
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 2
1021 2
1031 0
170 4
91 3
91 2
91 4
91 5
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockXYParameter
305 Y Distance1
306 X Distance1
307
308
141 0
140 0
309
97 0
146 0
147 0
148 0
176 0
410
96 0
142 0
143 0
144 0
175 0
0 BLOCKSCALEACTION
5 83
330 81
100 AcDbEvalExpr
90 2
98 33
99 232
100 AcDbBlockElement
300 Scale
98 33
99 232
1071 0
100 AcDbBlockAction
70 0
71 1
330 50
1010 4
1020 3
1030 0
100 AcDbBlockActionWithBasePt
92 1
93 1
301 UpdatedBaseX
302 UpdatedBaseY
1011 0
1021 0
1031 0
280 1
1012 0
1022 0
1032 0
100 AcDbBlockScaleAction
94 1
95 1
96 1
303 Scale
304 XScale
305 YScale
0 DICTIONARY
5 90
330 1A
100 AcDbDictionary
280 1
281 1
3 ACAD_ENHANCEDBLOCK
360 91
0 ACAD_EVALUATION_GRAPH
5 91
330 90
100 AcDbEvalGraph
96 3
97 3
91 0
93 32
95 1
360 92
91 1
93 32
95 2
360 93
91 2
93 32
95 3
360 94
0 BLOCKPOLARPARAMETER
5 92
330 91
100 AcDbEvalExpr
90 1
98 33
99 232
100 AcDbBlockElement
300 Polar
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 4
1021 0
1031 0
170 4
91 3
91 2
91 0
91 0
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockPolarParameter
305 Distance1
306
307 Angle1
308
140 0
309
96 0
141 0
142 0
143 0
175 0
410
97 0
145 0
146 0
147 0
176 0
0 BLOCKPOINTPARAMETER
5 93
330 91
100 AcDbEvalExpr
90 2
98 33
99 232
100 AcDbBlockElement
300 Point
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock1PtParameter
1010 4
1020 1
1030 0
93 0
170 0
171 0
100 AcDbBlockPointParameter
303 Position1
304
1011 4
1021 1
1031 0
0 BLOCKPOLARSTRETCHACTION
5 94
330 91
100 AcDbEvalExpr
90 3
98 33
99 232
100 AcDbBlockElement
300 Polar Stretch
98 33
99 232
1071 0
100 AcDbBlockAction
70 0
71 3
330 B0
330 B1
330 93
1010 5
1020 -1
1030 0
100 AcDbBlockPolarStretchAction
92 1
301 EndXDelta
93 1
302 EndYDelta
94 1
303 Base
95 1
304 End
96 1
305 UpdatedBase
97 1
306 UpdatedEnd
73 2
1011 3.5
1021 -0.5
1011 4.5
1021 1.5
72 1
331 B2
74 1
332 B0
75 1
76 1
78 0
141 1
140 0
77 0
0 ENDSEC
0 EOF
+469
View File
@@ -0,0 +1,469 @@
0 SECTION
2 HEADER
9 $ACADVER
1 AC1032
9 $HANDSEED
5 200
0 ENDSEC
0 SECTION
2 TABLES
0 TABLE
2 BLOCK_RECORD
5 1
330 0
100 AcDbSymbolTable
70 3
0 BLOCK_RECORD
5 1F
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 *Model_Space
340 0
0 BLOCK_RECORD
5 1E
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 *Paper_Space
340 0
0 BLOCK_RECORD
5 1D
102 {ACAD_XDICTIONARY
360 60
102 }
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 Symbol
340 0
70 0
280 1
281 1
0 ENDTAB
0 ENDSEC
0 SECTION
2 BLOCKS
0 BLOCK
5 20
330 1F
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 *Model_Space
70 0
10 0
20 0
30 0
3 *Model_Space
1
0 ENDBLK
5 21
330 1F
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 BLOCK
5 24
330 1D
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 Symbol
70 2
10 0
20 0
30 0
3 Symbol
1
0 CIRCLE
5 30
330 1D
100 AcDbEntity
8 0
100 AcDbCircle
10 0
20 0
30 0
40 1
0 LINE
5 31
330 1D
100 AcDbEntity
8 0
100 AcDbLine
10 0
20 0
30 0
11 0
21 3
31 0
0 ATTDEF
5 32
330 1D
100 AcDbEntity
8 0
100 AcDbText
10 1
20 2
30 0
40 1
1 X
50 90
7 Standard
100 AcDbAttributeDefinition
3 Tag
2 TAG
70 0
0 ENDBLK
5 25
330 1D
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 ENDSEC
0 SECTION
2 ENTITIES
0 ENDSEC
0 SECTION
2 OBJECTS
0 DICTIONARY
5 C
330 0
100 AcDbDictionary
281 1
0 DICTIONARY
5 60
330 1D
100 AcDbDictionary
280 1
281 1
3 ACAD_ENHANCEDBLOCK
360 61
0 ACAD_EVALUATION_GRAPH
5 61
102 {ACAD_REACTORS
330 60
102 }
330 60
100 AcDbEvalGraph
96 8
97 8
91 0
93 32
95 15
360 62
92 -1
92 -1
92 -1
92 -1
91 1
93 32
95 16
360 63
92 -1
92 -1
92 -1
92 -1
91 2
93 32
95 19
360 64
92 -1
92 -1
92 -1
92 -1
91 3
93 32
95 20
360 65
92 -1
92 -1
92 -1
92 -1
91 4
93 32
95 21
360 66
92 -1
92 -1
92 -1
92 -1
91 5
93 32
95 25
360 67
92 -1
92 -1
92 -1
92 -1
91 6
93 32
95 26
360 68
92 -1
92 -1
92 -1
92 -1
91 7
93 32
95 30
360 69
0 BLOCKROTATIONPARAMETER
5 62
330 61
100 AcDbEvalExpr
90 15
98 33
99 232
100 AcDbBlockElement
300 Rotation
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 2
1021 0
1031 0
170 4
91 0
91 16
91 0
91 0
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockRotationParameter
305 Angle1
306
1011 2
1021 0
1031 0
140 0
307
96 3
141 0
142 6.283185307179586
143 0
175 0
0 BLOCKROTATIONGRIP
5 63
330 61
100 AcDbEvalExpr
90 16
98 33
99 232
100 AcDbBlockElement
300 Grip
98 33
99 232
1071 0
100 AcDbBlockGrip
91 0
92 0
1010 2
1020 0
1030 0
280 0
93 -1
100 AcDbBlockRotationGrip
0 BLOCKROTATEACTION
5 64
330 61
100 AcDbEvalExpr
90 19
98 33
99 232
100 AcDbBlockElement
300 Rotate
98 33
99 232
1071 0
100 AcDbBlockAction
70 2
91 0
91 0
71 4
330 31
330 32
330 65
330 68
1010 1
1020 1
1030 0
100 AcDbBlockActionWithBasePt
92 15
93 15
301 UpdatedBaseX
302 UpdatedBaseY
1011 0
1021 0
1031 0
280 1
1012 0
1022 0
1032 0
100 AcDbBlockRotationAction
94 15
303 AngleDelta
0 BLOCKFLIPPARAMETER
5 65
330 61
100 AcDbEvalExpr
90 20
98 33
99 232
100 AcDbBlockElement
300 Flip
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 -10
1021 0
1031 0
170 4
91 21
91 0
91 0
91 0
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockFlipParameter
305 Flip state1
306
307 Not flipped
308 Flipped
1012 -12
1022 0
1032 0
309 UpdatedFlip
96 21
0 BLOCKFLIPGRIP
5 66
330 61
100 AcDbEvalExpr
90 21
98 33
99 232
100 AcDbBlockElement
300 Grip
98 33
99 232
1071 0
100 AcDbBlockGrip
91 0
92 0
1010 -2
1020 0
1030 0
280 0
93 -1
100 AcDbBlockFlipGrip
0 BLOCKFLIPACTION
5 67
330 61
100 AcDbEvalExpr
90 25
98 33
99 232
100 AcDbBlockElement
300 Flip1
98 33
99 232
1071 0
100 AcDbBlockAction
70 2
91 0
91 0
71 3
330 31
330 32
330 68
1010 -6
1020 0
1030 0
100 AcDbBlockFlipAction
92 20
93 20
94 20
95 20
301 Flip
302 UpdatedFlip
303 UpdatedBase
304 UpdatedEnd
0 BLOCKPOINTPARAMETER
5 68
330 61
100 AcDbEvalExpr
90 26
98 33
99 232
100 AcDbBlockElement
300 Point
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock1PtParameter
1010 0
1020 3
1030 0
93 0
170 0
171 0
100 AcDbBlockPointParameter
303 Position1
304
1011 0
1021 4
1031 0
0 BLOCKMOVEACTION
5 69
330 61
100 AcDbEvalExpr
90 30
98 33
99 232
100 AcDbBlockElement
300 Move
98 33
99 232
1071 0
100 AcDbBlockAction
70 2
91 0
91 0
71 1
330 32
1010 0
1020 4
1030 0
100 AcDbBlockMoveAction
92 26
93 26
301 XDelta
302 YDelta
140 1
141 0
0 ENDSEC
0 EOF

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