Compare commits

..
Author SHA1 Message Date
FredApps 22b1809992 test: count attribute tag matching work instead of timing it 2026-12-01 13:33:56 +01:00
a79b9feca9 feat(doc,io,render): support MTEXT background mask (DXF 90/63/421/45) (#3240)
* feat(mtext): support MTEXT background mask (DXF 90/63/421/45) in doc, io, and render

* fix(mtext): write background mask before column tags and use Autodesk border offset factor

* fix(render): resolve ByLayer/ByBlock for MTEXT background mask and guard non-finite rotation

* fix(render/mtext): cover overflowing glyphs, MLeader text opt, and attrib ByBlock bg

* fix(io/dxf): omit inactive MTEXT background mask conditional tags

* Fix MTEXT background test for current Text fields

Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com>

---------

Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com>
Co-authored-by: vantruong-dang <vantruong-dang@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-01 12:50:47 +01:00
b778851b48 Viewports keep their own UCS and their other settings through save and copy (part of #1316) (#1484)
* Viewports keep their own UCS and their other settings through save and copy (part of #1316)

A layout viewport's own UCS and every setting CADCraft doesn't model
were dropped on read, so saving a sheet set lost them for good.

- Viewport::ucs (origin, X/Y axes, elevation, orthographic type, named
  and base UCS by name) and ucs_per_viewport (UCSVP), read from and
  written as VIEWPORT groups 110-112, 146, 79, 345/346 and 71.
- Viewport::extra: the viewport's other groups as read (snap, grid,
  lens and clipping, render mode, plot style sheet, shade plot, visual
  style, background, lighting). They belong to the entity, so COPY and
  MIRROR carry them; dxf_raw::finish writes them before the xdata and
  points their references at what they named (ForeignExtra::tail).
- Not carried raw: the view twist, direction and target (51, 16, 17),
  which say where the view centre is measured from; writing them back
  while the centre is in drawing coordinates would move the view.
- DWG: the bridge drops 345/346, the plot style sheet, shade plot and
  lighting groups, so CADCraft xdata keeps a copy (VPUCS, VPEXTRA) that
  the reader falls back on. The visual style, background and shade plot
  references are still lost through DWG (file-format-parity.md).
- A UCS with unreadable or zero-length axes is no UCS; a named UCS
  that's no longer in the table isn't pointed at.

Tests: another program's viewport read; DXF save and reread; two DWG
round trips; a copied viewport; a deleted named UCS; a viewport without
a UCS written as before; hostile groups (5000 extras, NaN axes, bad
handles); COPY and MIRROR through the engine.

* Viewports: VPEXTRA keeps only a viewport's own groups; a base UCS handle alone is kept

- CADCraft's VPEXTRA xdata copy of a viewport's unmodelled groups is
  merged only for groups that can stand inside the AcDbViewport subclass:
  a record start (0), handles (5, 105), a subclass (100), a group brace
  (102) or xdata (1000 on) from a crafted file are dropped, so a save
  can't write records or handles the user didn't draw.
- A VIEWPORT whose only UCS group is its base UCS handle (346) now reads a
  UCS, so the base UCS is resolved and written back.

* Viewports: drop structural groups from a record's own extras; index UCS names for the xdata fallback

- A VIEWPORT's own AcDbViewport groups are kept raw only when they can
  stand in the subclass, as CADCraft's VPEXTRA copy already was: a second
  handle (5, 105) or a group brace (102) written back would give the
  record two handles. The record's own pointer groups stay, to be
  remapped with it.
- The named and base UCS that CADCraft's xdata names are looked up in a
  case-insensitive index built once with the UCS table, not by scanning
  every UCS for each viewport.

* Parity checklist: regenerated after merging main

* Parity checklist: regenerated after merging main

* Parity checklist: regenerated after merging main

* xtask: take main's stats.rs (the merge kept a test import Linux clippy rejects)

* Viewport tests built on main set the UCS fields

* WIP row 74: Codex's test edits kept; production normalisation (identity UCS -> None, default-valued extras dropped in dxf_read viewport_ucs/viewport_extra) still to do

* Viewports: a default viewport reads back with no UCS or extra groups (#1484)

A DWG save writes an identity UCS and the default snap, grid, lens, clip,
render and shade groups for every viewport, so a viewport nobody gave a UCS
came back with one and a dozen extras. The DXF reader now reads an unnamed
identity UCS (UCSVP 0) as none, and keeps a group in extra only when it
differs from the defaults, listed in one table. Tests: a_default_viewport_reads_back_without_ucs_or_extras,
a_viewport_with_non_default_snap_keeps_it; layouts_and_paperspace passes.

* Viewports: clippy range patterns; raster_image test builds with the viewport's UCS fields

* Tests: move the viewport UCS suites into the it entry points (#1316)

viewport_ucs_roundtrip.rs and viewport_ucs_copy.rs were separate test
binaries; AGENTS section 30 wants the existing entry points. All 12 DXF/DWG
persistence tests and the COPY/MIRROR tests are kept.

* Tests: move the viewport UCS suites into the it entry points (#1316)

viewport_ucs_roundtrip.rs and viewport_ucs_copy.rs were separate test
binaries; AGENTS section 30 wants the existing entry points. All 12 DXF/DWG
persistence tests and the COPY/MIRROR tests are kept.

---------

Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: SBaksa <18648812+SBaksa@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-01 12:16:30 +01:00
e6bbf59c31 Expose xdata through entities, properties.set and AutoLISP's -3 group (#2469)
* Expose xdata through entities, properties.set and AutoLISP's -3 group

An entity's extended data was read, kept and written back (#528) but
invisible to the API: `entities` left it out, `properties.set` had no
field for it, `entget` never returned the -3 group and `entmod` dropped
it. Now `entities {xdata: true | "APP"}` and `properties` list it per
application with values typed by group code, `properties.set {xdata}`
replaces or removes one application's data after checking codes,
values, braces and sizes, and AutoLISP's entget/entmod/entmake carry
the -3 group, with `regapp` and the APPID table. The applications
CADCraft writes from its own model are reserved (one list, now in
cadcraft_doc, shared with the DXF reader).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Check xdata before any change in properties.set; cap entmake's xdata across applications

Review follow-ups on #2469:
- properties.set validated xdata after ensure_layer, so a request naming a new
  layer and carrying bad or oversized xdata left the layer behind on failure.
  The xdata checks now run first.
- entmake capped each application's groups but not their sum; an entity could
  exceed MAX_XDATA_GROUPS across applications. The total is checked as entmod
  already does, with a test.
- docs: the control-protocol xdata section is an h2 like its neighbours; the
  file-format-parity revision row no longer has a pipe inside a code span.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* properties.set checks every handle first; a dotted -3 group is a bad list

Review follow-ups on #2469:
- properties.set edited the objects before a handle that names nothing and
  then failed, keeping those edits (and a new layer). Every handle is checked
  before anything changes; a missing one is refused with its hex.
- xdata_from_list read `(-3 . 7)` as "no applications" and let entmake/entmod
  succeed with nothing set. A -3 whose cdr is not a list is refused (listp),
  so both return nil as for any bad list.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* An xdata application's groups must be a proper list

Review follow-up on #2469: `("ACME" . 7)` in a -3 group read as "no groups",
which `entmod` takes as "remove ACME's data", and a dotted tail after real
groups was dropped. The application's tail is checked as a list (listp) like
the -3 group itself, so entmake/entmod answer nil and change nothing; test
covers both shapes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Runs of one xdata application in any case are one application in the API

Review follow-up on #2469: a file can carry `ACME` and `acme` runs on one
entity. `entities` showed them as two JSON keys and `entget` as two lists, and
writing either back through properties.set or entmod replaced the application
twice, keeping only the last run's groups. Both projections now merge runs
case-insensitively (first spelling, all the groups), as set_xdata_app already
treats them; tests round-trip such an entity through both APIs.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Refuse raw ACAD xdata on a dimension, whose ACAD run is written from its overrides

Review follow-up on #2469 (austin62jake): properties.set accepted
`xdata: {"ACAD": …}` on a dimension and `entities` showed it, but the DXF
writer emits the dimension's ACAD run (DSTYLE) from its overrides and the
reader models it back, so the raw groups vanished on save. ACAD can't join
RESERVED_XDATA_APPS (files carry ACAD data on other entities that CADCraft
keeps raw), so the rule is per entity: `is_model_xdata_app(name, kind)` is
the reserved list on any entity plus ACAD on a dimension. properties.set
refuses it before anything changes, entmake/entmod answer nil. Tests cover
both paths, including that ACAD on a line survives a DXF round trip and the
dimension's own override does too. control-protocol.md says so.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(lisp): return and accept REAL for xdata group 1071

---------

Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: FredApps <fredapps@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-01 11:38:34 +01:00
20524853c1 Options: preview and selection effects in Visual Effect Settings (#964)
* Options: preview and selection effects in Visual Effect Settings

Selection Preview Effect (Dash / Thicken / Both, PREVIEWEFFECT) as AutoCAD
offers it, and Selected Objects Effect (Dashed / Selection color,
SELECTIONEFFECT), so neither has to be typed. They stay off the Selection tab
itself.

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

* Options test: each Visual Effect Settings choice sets its variable

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

* Tests: the visual effect test sets up the app's headless runtime, as main's UI tests now do

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

* Translations to craft-i18n (AGENTS.md rule 16)

The Greek and Ukrainian rows this PR added to the app catalogs are removed; the
English keys stay, and show until craft-i18n has them.

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

---------

Co-authored-by: Cody Vogt <18035288+codyvogt@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:55:01 +01:00
vantruong-dangandvantruong-dang 0590499adc fix(io): apply SPATIAL_FILTER boundary transform to preserve pasted XCLIPs (#2922)
* test(io): cover non-identity XCLIP filter transform

* fix(io): apply SPATIAL_FILTER boundary transform to clip vertices

* test(io): add DXF and DWG round-trip coverage for transformed XCLIP boundaries

* docs(io): document SPATIAL_FILTER matrix semantics and cover rotation/scale

* fix(io): invert boundary transform matrix per Autodesk DXF spec

* docs(io): annotate SPATIAL_FILTER group 40 translation indices in integration test

* fix(io): reject sheared boundary transforms to preserve foreign data

* fix(io): use scale-independent orthogonality check for boundary transforms

* fix(io): expand rotated 2-corner boundary_xf clips and add docstrings

* test(io): verify rotated 2-corner boundary expansion across 30/45/60/90 degrees

* fix(io): expand 2-corner clips on any rotated net transform and align rotated writer

* test(io): cover rotated+inverted 2-point XCLIP round-trip

* fix(io): use pure rotation boundary_xf for rotated 2-point clips to support non-uniform scale

* fix(io): canonicalize 2-point SPATIAL_FILTER corners in boundary space

* fix(io): read DWG through the shared DXF bridge in the XCLIP test

---------

Co-authored-by: vantruong-dang <vantruong-dang@users.noreply.github.com>
2026-12-01 10:52:55 +01:00
Moritz BoellingandClaude Opus 5.5 02461788e6 PDF plots write a filled primitive as the outline of its triangles, not one subpath per triangle (#3459) (#3614)
A solid hatch, wide polyline, wipeout mask or filled glyph reached the PDF
writer as a triangle list, and each triangle became its own closed subpath.
The writer now cancels edges that two triangles share in opposite
directions and chains what is left into closed loops, written as one
nonzero fill. The winding number at every point depends only on the net
directed edges, so the filled area is the same for overlapping, mixed-
orientation, zero-area and T-junction triangles; vertices are matched by
the exact bits of the f32 coordinates written. O(n log n) time, O(n) memory,
no recursion.

For a 400-vertex solid hatch with a square island the page content stream
goes from 30,086 to 9,922 bytes (457 to 3 subpaths) and the compressed file
from 5,874 to 4,223 bytes.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:51:34 +01:00
FredApps fe6530dec5 Merge pull request #1370 from codyvogt/fix/annotative-mleader-contexts
DXF/DWG: annotative multileaders keep their scales, and drawings open at their current annotation scale (stacked on #1362)
2026-12-01 10:49:57 +01:00
FredApps d7eb43d2dc Merge pull request #1362 from codyvogt/fix/annotative-text-contexts
DXF/DWG: annotative text, MText and dimensions keep their annotation scales on save (stacked on #1244)
2026-12-01 10:48:28 +01:00
FredApps 452a3b22eb Merge pull request #1244 from codyvogt/fix/block-record-annotative
DXF: annotative blocks keep their flag, uniform scaling, and their references' and attributes' annotation scale contexts on save
2026-12-01 10:45:14 +01:00
FredApps 5ffd5e858e Sync updated annotative text prerequisite into multileader contexts 2026-12-01 09:39:28 +01:00
FredApps dc5192180c Sync annotative block prerequisite and refresh the text fixture defaults 2026-12-01 09:39:26 +01:00
FredApps e928d57182 Sync current main into annotative block contexts 2026-12-01 09:39:20 +01:00
Tanish Manku 8bece25483 Merge pull request #3703 from storytold/stack/e4
Land #3695, #3658, #3039, #3404: Aligned text extents, fill-cap truncation, INSERT with EXPERT, Attribute Editor dialog
2026-11-30 21:28:02 -07:00
Tanish Manku 0d17d4cc50 Landing fix: #3404's TEXT fixture takes #3679's new fields 2026-11-30 20:46:29 -07:00
Tanish Manku 34d52cd336 Merge #3404: Block attributes: Attribute Editor and Properties attributes (repair of #1213) 2026-11-30 20:46:21 -07:00
Tanish Manku f2733ade72 Merge #3039: INSERT of a drawing file does not ask to redefine its block when EXPERT is 2 or more 2026-11-30 20:46:19 -07:00
Tanish Manku 3dc0e581c6 Merge #3658: render: mark the display list truncated when a fill stops at the fill cap (#3636) 2026-11-30 20:46:17 -07:00
Tanish Manku c49a815b1d Merge #3695: Aligned text extents hold narrow letters; unfitted text keeps a box of its own size (follow-up to #3506) 2026-11-30 20:46:15 -07:00
Tanish Manku c9471b09dc Merge pull request #3702 from storytold/land/3699
Land #3699: Update and Restart asks about unsaved drawings
2026-11-30 20:40:51 -07:00
moandClaude Fable 5.2 56388075ae Text that draws nothing has an empty box
A value of nothing but underline and overline toggles (%%u%%u) has no drawn
character, and the box floored the count at one: Aligned over a span of 20
that was a box of 20 by 120 for text that draws nothing. The box is empty
when no character is drawn, for an empty value too.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 03:29:28 +00:00
2ez4gcxandClaude Opus 5.5 f4edfee60c Merge origin/main into fix/fill-cap-truncated
main now carries #3594 and #3622 (landed through #3692), which rewrote
clip_prim around Limits and the pieces/fill closures. The only conflict is
that block in crates/render/src/viewports.rs: main's clip_prim is kept and
its Clip::Poly fill arm gets this branch's one line, so both truncation
signals stay:

- #3594's whole() in the fill closure marks the list when the clip stops
  at the room left or at its own 6,000,000-point stop;
- may_leave_out marks it when the clip region's own triangles stopped at
  the fill cap (#3636).

truncated is only ever OR-ed, so neither signal clears or doubles the
other.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:29:01 +07:00
moandClaude Fable 5.2 165287474e Merge main: the text box keeps its four corner points, mirrored as on main
Main (PR 3679) mirrors the box of Backwards and Upside-down text about the
point the text is placed by. This branch builds the box from a bottom and a
top instead of an offset and a height, so the mirror is applied to those
corner points.

Tests: the two helpers (ours with a vertical justification, main's with the
mirror flags) are one that takes both, and the test of the vertical
justifications also runs with each mirror.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 03:23:49 +00:00
code-compliant 4e9a5058cb Address attribute editor review 2026-12-01 11:15:31 +08:00
Tanish Manku d0872cc118 Merge #3699: Update and Restart asks about unsaved drawings 2026-11-30 20:03:50 -07:00
Tanish Manku 7f2e4544dc Merge pull request #3701 from storytold/docs/parity-batch-1201
Parity docs: rows updated for what merged from 2026-11-25 to 2026-12-01
2026-11-30 19:56:56 -07:00
Tanish Manku 5b145ab603 Merge pull request #3700 from storytold/stack/e3
Land #3628, #3583, #3625, #3617, #3248, #3221, #3287, #3259, #3232, #3291, #3679: Drawing Units dialog, SCALE and MOVE base points, TRIM/EXTEND Shift, mirrored hatch patterns, layout framing, deep zoom, RECTANG X/Y, Save As version, Turkish, TEXT backwards
2026-11-30 19:34:54 -07:00
Tanish Manku 4d0f4dc5b6 Parity docs: F2's impact names what is left; Tamil needs a Tamil font 2026-11-30 19:34:40 -07:00
moandClaude Fable 5.2 86063426de Text boxes count the characters a value draws, not the ones it is written with
The box took the length of the stored value, control codes included: the
%%u and %%o toggles draw nothing, %%d, %%c, %%p, %%% and %%nnn draw one
character, \U+XXXX draws one, and invisible formatting characters take no
room. So the width was over-estimated again for such text: Aligned
"%%uAB%%u" at height 1 over a span of 20 is drawn 12.5 high in a box of
6.25. The callers now pass the number of drawn characters.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 02:22:06 +00:00
Tanish Manku a62956e1e9 Parity docs: rows updated for what merged from 2026-11-25 to 2026-12-01 2026-11-30 19:11:13 -07:00
Tanish Manku 4f2800a0dc Landing fix: the two TEXT literals #3214 added take #3679's new fields 2026-11-30 18:52:32 -07:00
Tanish Manku 69e7b40762 Merge #3679: TEXT's own Backwards and Upside down (DXF 71 generation flags) 2026-11-30 18:44:56 -07:00
Tanish Manku 60de483a5e Turkish: translate the unsaved-changes warning that #3291 left in English 2026-11-30 18:44:11 -07:00
Tanish Manku dec1b14c22 Merge #3291: i18n(tr): complete Turkish UI catalog 2026-11-30 18:43:56 -07:00
Tanish Manku 9cf855c55e Merge #3232: Save As and Export: write DXF and DWG at the chosen version (#3213) 2026-11-30 18:43:54 -07:00
Tanish Manku 5d7f8b62d9 Merge #3259: RECTANG: Dynamic Input asks for the other corner as X and Y (#3258) 2026-11-30 18:43:52 -07:00
Tanish Manku e16c39825a Merge #3287: perf(gpu): stabilize deep-zoom vertex origin with power-of-two grid and hysteresis 2026-11-30 18:43:50 -07:00
Tanish Manku fe83a26af5 Merge #3221: fix(engine): frame layout extents on initial tab switch (#3219) 2026-11-30 18:43:48 -07:00
Tanish Manku d99b20a46a Merge #3248: DXF: mirror a mirrored HATCH's pattern lines with its boundary (#3120) 2026-11-30 18:43:46 -07:00
Tanish Manku 3b4ee98570 Merge #3617: trim/extend: Shift toggles mode with live preview (partial #3569) 2026-11-30 18:43:44 -07:00
Tanish Manku ace5d48da1 Merge #3625: MOVE and COPY: a perpendicular or tangent base point resolves from the second point (#3481) 2026-11-30 18:43:43 -07:00
Tanish Manku 719bdee804 Merge #3583: SCALE: a factor point on the base point re-prompts instead of ending the command (fixes #3475) 2026-11-30 18:43:41 -07:00
Tanish Manku 67fbc4f850 Merge #3628: Translate the Drawing Units dialog; Italian labels 2026-11-30 18:43:37 -07:00
cdwilson127andClaude Opus 5.5 fc1bf5e2ef Updates: Update and Restart asks about unsaved drawings instead of refusing (#3698)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:58:11 +13:00
Tanish Manku a1927ea897 Merge pull request #3692 from storytold/stack/e2
Land #3630, #3659, #3660, #3661, #3646, #3651, #3642, #3519, #3288, #3685, #3609, #3214, #3540, #3594, #3622: LISP and script fixes, graphics start-up fallback, render budgets, solver speed, viewport selection
2026-11-30 17:12:22 -07:00
CTGControlsandClaude Opus 5.5 7d9225c856 SCALE: the factor-point check uses require_length (#3475)
The point arm repeated require_length's check and message inline; it now
calls the helper, as the Reference length already does, so the two paths
keep one threshold and one error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:23:12 -06:00
moandClaude Fable 5.2 ae73bfa463 Bottom-justified Aligned text is inside its box
Bottom justification lifts a line by a third of the height it is drawn at.
The box used a third of its own height, which is the most the line can be
drawn at, so the box began above the bottom of the text: "I" over a span of
20 is drawn from 20 to 80 and its box began at 40. The box now runs from
where the shortest possible line would start (from the widest width the
stroke font gives the line) to where the tallest would end.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-30 22:20:44 +00:00
kc8a 65fbabbbee trim/extend: exercise the Shift cache key at Crossing with a steady prompt 2026-11-30 22:14:28 +00:00
moandClaude Fable 5.2 a5545fb5e2 Aligned text extents hold narrow letters; unfitted text keeps a box of its own size (follow-up to #3506)
Two findings from the landing review of #3506.

Text of next to no width is left as it is by the fonts. The box applied
that cutoff with a margin, so for a height of 1e-7 and a width factor of
1e-5 it still scaled the text over its span: a box about a million units
high. It now uses the fonts' cutoff as it is.

Aligned text is scaled by span / shaped width, and the box divided by the
widest width a line can have, so narrow letters were drawn taller than
their box: "I" over a span of 20 is drawn 60 high in a box of 22. The
height now comes from the least width the stroke font gives a line.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-30 21:44:53 +00:00
FredApps 03d69197fa Merge resolved annotation dependency into PR #1370 2026-11-30 22:04:33 +01:00
FredApps 877185824f Merge current main and preserve annotation and wipeout DXF setup 2026-11-30 22:04:30 +01:00
paco-velascoandClaude Fable 5.2 0cfd8aac85 Text generation flags: extents of mirrored Aligned and Fit text
A test that the extents of backwards and upside-down text over two
points are the plain text's extents reflected about the first point,
as the drawn text is.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-30 21:53:38 +01:00
Yuri GanugiandClaude Opus 5.5 5ec689264f chore(i18n): move the Italian rows out of this PR
Per review: the 40 Italian rows go to a translation-only PR.
it.tsv is back to its state on main; this PR keeps only the
dialog wiring and the English keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:53:20 +01:00
Tanish Manku 23f60b50aa Merge pull request #3689 from storytold/stack/p2
Land #3483, #3672, #3520, #3613, #3611, #3610, #3647, #3668, #3670: proxy graphics follow-ups, hatch derived bit, covered cell text, layer 0 attributes, WIPEOUTFRAME, layout flags
2026-11-30 13:51:50 -07:00
paco-velascoandClaude Fable 5.2 318cfc83fa Merge main into fix/text-generation-flags-read
Keeps both sides in text_box (main's fitted height and rotation, this
branch's mirroring) and sets the two flags on the Text literals main
has added since.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-30 21:31:20 +01:00
Tanish Manku 8a34fdf47e Merge #3622: selection highlight and plot style outlines no longer overflow the web build 2026-11-30 13:25:12 -07:00
Tanish Manku 18ccfa1100 Merge #3594: render: budget the primitives a display list holds 2026-11-30 13:25:10 -07:00
Tanish Manku fe8cff7071 Merge #3540: dxf: store DIMLFAC-scaled dimension measurements 2026-11-30 13:24:58 -07:00
Tanish Manku 0589527c4c Merge #3214: Selection through a viewport leaves out block parts on its frozen layers (#3126) 2026-11-30 13:24:55 -07:00
Tanish Manku 4d739604a0 Merge #3609: Update url to 2.5.9 and async-executor to 1.14.1 (part of #1935, F-17) 2026-11-30 13:24:53 -07:00
Tanish Manku dff5d4cca1 Merge #3685: Start with another renderer when the graphics can't start (automatic fallback) 2026-11-30 13:24:51 -07:00
Tanish Manku d9be0f6350 Merge #3288: fix(cmd): support SCALE Reference Points/Copy and grip height scaling 2026-11-30 13:24:49 -07:00
Tanish Manku 3f30859e0c Merge #3519: HATCH from a LISP (command) call takes the command-line answer order 2026-11-30 13:24:47 -07:00
Tanish Manku 66bca62c73 Merge #3642: fix(engine, mcp): run a script's LISP routine on before its next input 2026-11-30 13:24:38 -07:00
Tanish Manku f52bd37893 Merge #3651: fix(engine, mcp, ui): keep a request's output when the command history trims 2026-11-30 13:24:36 -07:00
Tanish Manku 80bccfca4f Merge #3646: fix(cmdline): insert spaces inside unclosed AutoLISP expressions (#3632) 2026-11-30 13:24:34 -07:00
Tanish Manku 95ce89b7dd Merge #3661: MTEXT: honor paragraph line spacing codes (\pxsm, \pxse, \pxsd) (#3638) 2026-11-30 13:24:32 -07:00
Tanish Manku f5ad6e18b9 Merge #3660: Solve dimension chains faster when moving a point 2026-11-30 13:24:30 -07:00
Tanish Manku 08fe43780c Merge #3659: Check constrained sketches faster after an edit 2026-11-30 13:24:28 -07:00
Tanish Manku 57e53f688c Merge #3630: fonts: read a family name past blank name records; make the user-font names test deterministic 2026-11-30 13:24:26 -07:00
code-compliant c8995ac18b Merge origin/main into repair/1213-block-attribute-editing 2026-12-01 04:22:46 +08:00
kc8a c9277f90e0 Merge branch 'main' into feat/trim-extend-shift
# Conflicts:
#	crates/engine/tests/it/trim_highlight.rs
2026-11-30 20:21:12 +00:00
Tanish Manku 022b9644be VPORT group 72 DWG test: skip where the DWG bridge isn't built (FreeBSD aarch64) 2026-11-30 13:12:18 -07:00
Tanish Manku 080ae3110d Merge pull request #3690 from storytold/stack/e1
Land #3504, #3506, #3526, #3513, #3586, #3612, #3615, #3624, #3571, #3584, #3587: TRIM/EXTRIM follow-ups, table paste follow-ups, text extents, palette and grip fixes
2026-11-30 13:11:59 -07:00
Cody Vogt b453478240 Merge branch 'fix/annotative-text-contexts' into fix/annotative-mleader-contexts 2026-11-30 14:05:26 -06:00
Cody VogtandClaude Opus 5.5 c12a1c12ca DXF writer: the DWG bridge's context choice in contexts_for (finish passed the complexity limit)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 14:05:25 -06:00
Cody Vogt 22a48f48de Merge branch 'fix/block-record-annotative' into fix/annotative-text-contexts 2026-11-30 14:05:25 -06:00
Tanish Manku b1345be253 Merge pull request #3352 from storytold/land/2355
Land #2355: REFEDIT edits an xref in place and writes it back to its file
2026-11-30 13:02:05 -07:00
Cody VogtandClaude Opus 5.5 d3a7097e99 Tests: the multileader's DWG round trip runs, through CADCraft's record
The multileader DWG test that waited for craft-libs#2005 (ignored) now runs:
its scales and paper text height come back through DWG from CADCraft's own
record, and the DWG holds no multileader contexts. The contexts' round trip
through DWG follows with the bridge.

FredApps on #1362 (rule 31).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:49:17 -06:00
Cody Vogt 684afce03c Merge branch 'fix/annotative-text-contexts' into fix/annotative-mleader-contexts
# Conflicts:
#	crates/io/src/dxf_raw.rs
2026-11-30 13:47:28 -06:00
Cody VogtandClaude Opus 5.5 91f1e0c0c0 DWG: annotative text, MText and dimensions keep their scales in CADCraft's record until the bridge converts contexts
A save through the DWG bridge writes no annotation scale contexts now: the
bridge doesn't convert them yet (storytold/craft-libs#2005), so CADCraft's own
record carries the scales, as for an older format. DXF from 2007 on writes the
contexts as before.

The DWG test that waited for craft-libs#2005 (ignored) now runs: the scales,
paper height and rotation come back through DWG from the record, and the DWG
holds no contexts. The contexts' own round trip through DWG follows with the
bridge.

FredApps on #1362 (rule 31).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:47:06 -06:00
Cody Vogt 9fdbfdb99f Merge branch 'fix/block-record-annotative' into fix/annotative-text-contexts 2026-11-30 13:43:57 -06:00
Cody VogtandClaude Opus 5.5 b076ec4c9f DWG: block reference contexts and the block's annotative flag stay DXF-only until the bridge converts them
The DWG bridge doesn't carry annotation scale contexts into a DWG yet
(storytold/craft-libs#2005): the DWG reader read them back as zeros, a
reference at scale 0 at its other scales. A save through the bridge now
leaves the kept block reference and attribute contexts out, as before they
were kept, and the block's AcadAnnotative flag too (without its references'
contexts AutoCAD would scale them by the annotation scale once more). DXF
keeps both.

The DWG round-trip test that waited for craft-libs#2005 (ignored,
a_reference_s_contexts_survive_dwg) is replaced by one that runs: a DWG save
leaves the contexts out and the reference reads back at its own scale. The
round trip of the contexts through DWG follows once the bridge converts
them.

FredApps on #1362 (rule 31).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:43:44 -06:00
FredApps 7068bf9464 Merge current main into deferred MOVE/COPY snapping
Preserve the canonical SCALE reference preview and drag behavior when resolving select_then.rs.
2026-11-30 20:41:08 +01:00
Tanish Manku 39ae41b5ea Merge fix: one destructuring for the viewport chunks 2026-11-30 12:31:45 -07:00
Tanish Manku 47372d358a Merge #3587: repeat pastetable on Enter with the last pasted text 2026-11-30 12:30:45 -07:00
Tanish Manku bdf4f65be9 Merge #3584: fix(render,table): wrap long TABLE cell text at column width (#3488) 2026-11-30 12:30:17 -07:00
Tanish Manku dcf69f77fe Merge #3571: Linux: the window keeps answering while a file dialog is open 2026-11-30 12:30:15 -07:00
Tanish Manku 989541c198 Merge #3624: Grips: a closed spline has one grip per control vertex and stays closed when it is dragged (#3566) 2026-11-30 12:30:13 -07:00
Tanish Manku 8623882d95 Merge #3615: Properties: a transparency percentage can be typed, and a slider shows its range (#3573) 2026-11-30 12:30:11 -07:00
Tanish Manku 556c192060 Merge #3612: Layers palette: the current layer list scrolls to layers past the bottom of the screen (#3400) 2026-11-30 12:30:09 -07:00
Tanish Manku cd01dab881 Merge #3586: fix(ui-egui): dispatch clipboard Copy and PasteTable events in arrival order (#3490) 2026-11-30 12:30:07 -07:00
Tanish Manku 97cc80800a Merge #3513: Use custom DIMPOST prefixes on radial dimensions 2026-11-30 12:30:04 -07:00
Tanish Manku bf715ddc44 Merge #3526: TRIM preview and EXTRIM: follow-ups from the landing review of #3382 and #2808 2026-11-30 12:30:02 -07:00
Tanish Manku 192b95e28b Merge #3506: The extents of Aligned and Fit text span their two points (follow-up to #3462) 2026-11-30 12:30:00 -07:00
Tanish Manku 670e88ea5e Merge #3504: The spatial index is rebuilt when ATTMODE changes (follow-up to #3462) 2026-11-30 12:29:58 -07:00
Tanish Manku 78b40d3593 Merge #3670: fix(io): keep the *Active VPORT records' group 72 through DXF and DWG 2026-11-30 12:29:52 -07:00
Tanish Manku 461be33ea8 Merge #3668: fix(io): save each layout's own LAYOUT flags (PSLTSCALE, LIMCHECK) instead of 1 2026-11-30 12:29:50 -07:00
Tanish Manku 489f143341 Merge #3647: Grow DXF entity lists fallibly and check room before placing them (part of #1922) 2026-11-30 12:29:48 -07:00
Tanish Manku 5c26eef628 Merge #3610: Keep OBJECTS records as slices of the DXF tag list while a file opens (part of #1922, F-06 e) 2026-11-30 12:29:46 -07:00
Tanish Manku a22473f3e4 Merge #3611: A saved drawing keeps WIPEOUTFRAME: the DXF writer emits the WIPEOUTVARIABLES object (#3440) 2026-11-30 12:29:44 -07:00
Tanish Manku d1fbec9473 Merge #3613: An attribute set on layer 0 stays on layer 0 on save and in the drawing (#3492) 2026-11-30 12:29:42 -07:00
Tanish Manku 9cedb46d53 Merge #3520: DXF: keep covered table cell text through 2007 and later saves 2026-11-30 12:29:40 -07:00
Tanish Manku ed759dda38 Merge #3672: DXF: do not write the derived boundary path bit without a pixel size (#3664) 2026-11-30 12:29:38 -07:00
Tanish Manku b8131c6b42 Merge #3483: fix: proxy graphics follow-ups from the #3454 landing (layer and linetype indices, snaps, edge-on arcs) 2026-11-30 12:29:36 -07:00
Tanish Manku 8c4875606f REFCLOSE: a reference to an xref of the host is refused even when the file has a block of that name; U inside a routine stops at a save that wrote the file 2026-11-30 12:19:08 -07:00
Tanish Manku a5289ffffa Merge main 2026-11-30 12:18:08 -07:00
kc8a 5d405e7d78 trim/extend: press/release Shift through the UI in the rollover test 2026-11-30 19:10:37 +00:00
kc8a 544dea24d1 trim/extend: Shift toggles mode with live preview (partial #3569)
Holding Shift during TRIM/EXTEND temporarily switches to the opposite command (standard CAD behavior). Session.shift_down is written by the UI and TrimM uses extend XOR shift_down for execution, prompt, Fence/Crossing preview and the single-entity rollover preview. The UI repaints and the preview cache key includes shift/ctrl, so a modifier-only change refreshes the preview.

BLOCK/INSERT geometry is still ignored as cutting/boundary edges in TRIM/EXTEND; that remains for a follow-up.
2026-11-30 18:32:57 +00:00
Cody Vogt 14a2c4780e Merge branch 'fix/annotative-text-contexts' into fix/annotative-mleader-contexts 2026-11-30 11:59:35 -06:00
Cody VogtandClaude Opus 5.5 05530e5e96 Tests: the annotative text context tests join the io test binary (AGENTS.md rule 30)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:59:20 -06:00
Cody Vogt 42f634336d Merge branch 'fix/block-record-annotative' into fix/annotative-text-contexts 2026-11-30 11:59:14 -06:00
Cody VogtandClaude Opus 5.5 f718f0f7f9 Tests: the annotative block context tests join the io test binary (AGENTS.md rule 30)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:58:58 -06:00
HagaiBA c1652286b5 fix(mtext): floor AtLeast paragraph line spacing at entity text height 2026-11-30 17:26:30 +02:00
Cody VogtandClaude Opus 5.5 896fe05886 DXF: a block reference moved in elevation takes its contexts along, at their own heights
block_contexts compared the reference with the one read in X and Y only, so a
reference moved only in Z kept its contexts at their old heights; and any
other change set every context's group 30 to the reference's Z, losing a
context's own height. Z is part of the change check now, and each context
keeps its offset from the reference as read, scaled with the reference's Z
scale as X and Y follow theirs.

FredApps on #1244.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:00:43 -06:00
HolyZephyros 4e0203b1f3 docs(i18n): record attribution and review status for Turkish additions 2026-11-30 16:06:19 +03:00
2ez4gcxandClaude Opus 5.5 634f7dd58e cadcraft: the device test checks that the read-back is answered
check() takes a read-back with no answer within 10 s as a pass, so the
device test that called it couldn't tell an answered read-back from a
timeout (it took 10.9 s on the Linux CI runner). Call clear_and_read and
require Ok(true) for both passes, naming the adapter and the time taken.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 19:39:28 +07:00
Ray 50d2fd0c77 Save As and Export: write DXF and DWG at the chosen version (#3213)
EXPORT ignored the version and always wrote the version the drawing was
read in, and the Save dialog passed the Default Save Format version only
for drawings with no file yet, so an opened 2013 DXF could not be written
as 2000.

EXPORT now takes SAVEAS's version and binary options for DXF and DWG
(other formats refuse them). The Save and Export dialogs share one helper
that passes the Default Save Format version for every .dxf or .dwg path,
an opened drawing's too. An export leaves the drawing's own version and
name alone, and QSAVE still keeps the file's version.

The message shown when the version is picked names Save As and Export
and goes through the translation system.
2026-11-30 05:22:50 -07:00
Ray 820b78d690 MOVE and COPY: a perpendicular or tangent base point resolves from the second point (#3481)
The base point prompt opts in to deferred PER and TAN snaps. The pick waits for
the second point, which resolves the base with snap::resolve_deferred, as LINE's
first point does, then moves or copies by second point minus that base. COPY
keeps the resolved base for later copies.
2026-11-30 05:19:07 -07:00
Ray f9c1aab173 RECTANG: Dynamic Input asks for the other corner as X and Y (#3258)
The other corner of a rectangle is its size, so the reference
application shows width and height boxes there whatever DYNPIFORMAT
says. CADCraft followed DYNPIFORMAT, so with the default polar format
40 Tab 30 placed the corner 40 units away at 30 degrees.

A prompt can now ask for X and Y (Prompt::xy), and RECTANG's other
corner does.
2026-11-30 05:16:51 -07:00
2ez4gcxandClaude Opus 5.5 6dde861d3c cadcraft: fall back to another renderer when the graphics can't start
When the first start of the window's graphics fails, run eframe again in the
same process with the next attempt instead of exiting:
- the start as it always was (DirectX 12 alone on Windows, eframe's backends
  elsewhere);
- OpenGL alone, where those backends have it beside another;
- the same backends on a software adapter (WARP, llvmpipe).
Each is tried with a stencil buffer, then without. No attempt creates a
backend the first one didn't, so Windows still never creates OpenGL (#31).

What failed picks the next attempt: an adapter, device or surface error moves
to another adapter; a failure the stencil buffer is part of tries the same
adapter without it. Before the app is created, a clear-and-read-back check
catches a driver that takes the stencil buffer and draws nothing (#1724's
Mesa log). A canvas whose GPU pipelines are refused draws on the CPU.

WGPU_BACKEND and CADCRAFT_STENCIL still win. Nothing is remembered between
starts. The log and the status bar say which renderer draws and why. When
every attempt fails, the first error is returned. A debug-only
CADCRAFT_GRAPHICS_FAULT switch fails one step of one attempt, for testing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 18:55:54 +07:00
garvitrakhecha a323e94b69 fix(cmdline): insert spaces inside unclosed AutoLISP expressions (#3632) 2026-11-30 15:50:07 +05:30
paco-velascoandClaude Fable 5.2 d80c4cb39f Text generation flags: the Text literals main has added since
Proxy graphics text, PDF import text and dynamic block grip text are built without Backwards or
Upside down; four tests build Text the same way.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-30 09:27:11 +01:00
SlopapaloozaandClaude Opus 5.5 34301df312 Review fixes: multiline attributes' 71; justified text's DXF start by its own flags
From CodeRabbit's reviews of #1136:
- TEXT's generation flags are AcDbText's group 71, but ATTDEF and ATTRIB
  read the first 71 among all their groups. A multiline attribute's
  AcDbAttribute / AcDbAttributeDefinition subclass has a 71 of its own (its
  multiline flag: 2 for an attribute, 4 for a definition), which AutoCAD and
  CADCraft write when the text has no generation flags, so multiline
  definitions read upside down and multiline attributes backwards (and were
  saved so). Only the groups before the attribute subclass give the flags
  now; the multiline fixture checks it, read and saved again.
- The start of a justified TEXT's baseline (DXF group 10) is worked out with
  the text's own Backwards and Upside down, as it's drawn and as its group
  71 says; it took the style's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:19:23 +01:00
SlopapaloozaandClaude Opus 5.5 c6016720ee TEXT's own Backwards and Upside down (DXF 71 generation flags)
TEXT, ATTDEF and ATTRIB have their own Backwards and Upside down, as AutoCAD's do (DXF group
71: 2 backwards, 4 upside down). New TEXT and attribute definitions take them from their style;
changing the style afterwards leaves existing text as it is. They were the style's only, so
text read from a file with its own flags was drawn as its style said.

- Model: `Text::backwards` and `Text::upside_down` (serde default false).
- DXF: read from 71 (the object's own groups, before an embedded MTEXT) and written when set.
- Render: drawn from the text's flags; the extents box mirrors with them, so zooming to
  extents frames mirrored text. Linetype text keeps its style's.
- Properties: a Misc group with Upside down and Backwards (`properties.describe`, and
  `properties.set` takes `backwards` and `upsideDown`), for several texts at once with *VARIES*.
- ATTDEF builds its text as TEXT does, so it also takes the style's width factor and obliquing.
- Round trip: #2237's matrices compare both flags, with DXF and DWG cases for them. Its
  mirrored-style cases mirror the text by the text's own flags, and each mirrored style
  also has text whose flags differ, so a style's flags can't leak into its text's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:19:23 +01:00
2ez4gcxandClaude Opus 5.5 fcca921719 test(io): run the DWG layout flags case only where the DWG bridge is built
Split layout_flags_are_saved_as_read into a DXF case for every target and
layout_flags_survive_a_dwg_save, which carries the same cfg as the other
DWG test in the file: the DWG bridge is not built on wasm32 or FreeBSD
aarch64 (#2526), so a DWG save fails there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:04:50 +07:00
HagaiBA 53a0b41c53 fix(mtext): preserve paragraph spacing resets across Formatted::to_contents 2026-11-30 09:54:57 +02:00
vantruong-dang ac405b4f5d test(ui-egui): drive the GPU origin check through the headless UI runtime 2026-11-30 14:30:14 +07:00
2ez4gcxandClaude Opus 5.5 4cbdfc1600 DXF: do not write the derived boundary path bit without a pixel size (#3664)
Since #3389 the HATCH writer keeps the Derived bit (4) of each boundary
path's group 92 from the file it read, but it never writes the hatch's
pixel size (group 47), and the reader does not keep one. #3664 reports
that AutoCAD refuses such a file, and that a stand-in pixel size draws
NET patterns solid.

Write only Polyline (2), External (1) from `outer`, and Textbox (8) and
Outermost (16) from the file, as for paths CADCraft creates. The bit
stays in HatchLoop::boundary_flags. Associativity (71), the source
handles (97, 330) and the pattern are unchanged; no group 47 is written.
The DWG save and AutoLISP entget use the same writer.

New test reads an invented associative NET hatch with derived paths and
a pixel size, saves it twice and checks the 92 bits, no 47, 71, 97 and
the 330 handles. Four #3389 tests now expect bit 4 cleared.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 14:27:23 +07:00
vantruong-dang eb53434e3b Merge remote-tracking branch 'origin/main' into perf/zoom-gpu-origin 2026-11-30 14:09:26 +07:00
Walter Haslbeck e7c907b690 Merge branch 'main', tag 'v0.21.0' of https://github.com/storytold/cadcraft into fix/proxy-landing-followups 2026-11-30 07:42:32 +01:00
2ez4gcxandClaude Opus 5.5 e58cd4ccc4 fix(io): keep the *Active VPORT records' group 72 through DXF and DWG
The reader skipped group 72 ("Circle sides" in the DXF Reference, VPORT)
of the first *ACTIVE record, and the writer wrote none. Opening a DXF or
DWG and saving it again therefore dropped the value.

Keep the first *ACTIVE record's 72 with the header values (internal key
CADCRAFT_VPORT_CIRCLE_SIDES, hidden from the variable list like other
CADCRAFT_ keys) and write it back on every *Active record. A value that
is not a 16-bit integer (the type of groups 60-79) is left out. A
drawing that stores none is written without 72, as before: no
documented default for this group was found, so none is invented.

DWG goes through the same reader (craft_dwg::decode then dxf_read) and
the same writer (dwg_bridge), so the value now survives a DWG save and
reopen too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:25:58 +07:00
vantruong-dang 86b275c6ef test(ui-egui): add wgpu origin stability and highlight alignment checks 2026-11-30 13:14:26 +07:00
moandClaude Fable 5.2 be85a3eb16 An unchanged WIPEOUTFRAME keeps the file's own object as read
The writer replaced a file's WIPEOUTVARIABLES object whenever the drawing
held 0 or 1, also when the setting was what the file said, and what other
applications hung on that object (an extension dictionary) was lost. The
writer now emits its object only when the file's own does not already say
what the drawing holds or what would be written for it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-30 05:26:39 +00:00
moandClaude Fable 5.2 24bbee7b0c Aligned and Fit text extents take the larger outcome near the fonts' cutoffs
The extents estimate a line's shaped width; the fonts measure it. Where the
fonts decide by a cutoff the two could differ, so the extents now assume
the real width is within a factor of 4 of the estimate and take the larger
box unless the estimate is clear of the cutoff:

- Fit text counts as stretched only when its fitted factor clears the
  fonts' cutoff by that factor; otherwise it is boxed unstretched.
- A line of next to no width is left as it is by the fonts, so its box no
  longer reaches for the second point.
- Aligned text shrunk into a short span is boxed at least as tall as its
  own height, which narrow characters reach.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-30 05:23:21 +00:00
vantruong-dang e10f499629 fix(engine): keep selected grip stationary in 3D during grip SCALE 2026-11-30 12:05:33 +07:00
vantruong-dang 19399e1ca8 fix(render,table): share resolved MTEXT sizing inputs between table renderer and paste 2026-11-30 11:55:54 +07:00
okereke-dev 7aca555e72 EXTRIM: measure a short stretch along itself, as TRIM does (CodeRabbit on #3526) 2026-11-29 23:54:41 -05:00
2ez4gcxandClaude Opus 5.5 241719d5ea fix(io): save each layout's own LAYOUT flags instead of 1
The LAYOUT object's own group 70 (after the AcDbLayout marker) holds the
layout's PSLTSCALE (bit 1) and LIMCHECK (bit 2), each the value while that
layout is current (DXF Reference, LAYOUT). The writer wrote 1 for the Model
layout and every paper-space layout and the reader ignored the group, so
every saved layout had paper-space linetype scaling on, whatever the
source said. DWG input goes through the same reader (the DWG bridge
writes the group), so DWG -> DXF conversion lost it too.

- doc: Layout::flags and Drawing::model_layout_flags keep the value read
  (None for a layout CADCraft made).
- read: group 70 is taken only after the AcDbLayout marker; before it the
  group is the plot layout flags.
- write: the value read, masked to the two bits the Reference defines;
  without one, the drawing's PSLTSCALE (what CADCraft draws every layout
  with) and LIMCHECK off. A new drawing still writes 1.
- engine: LAYOUT Copy copies the flags with the page setup and limits.

The renderer still uses the header PSLTSCALE for every layout; making it
per layout needs SETVAR to become per layout first, a separate change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:44:54 +07:00
moandClaude Fable 5.2 44d55b3250 Fit text extents follow the fitted width factor falling back
Fit text is stretched by scaling its width factor by span / shaped width
and shaping again. With a span that is a tiny part of the text's width the
scaled factor is too small for the fonts, which then draw at a factor of 1:
the text is far wider than its span, and the extents reported only the
span. The extents now take the unstretched width in that case, as they do
for an unusable stored factor.

Test (render, which sees both): the drawn text lies inside the drawing's
extents for a span too short to fit and for one that fits.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-30 04:34:38 +00:00
okereke-dev d3def9a5a3 EXTRIM: leave a stretch only where TRIM would pass over its cut, and refuse an edge left in another space (CodeRabbit on #3526)
too_short's margin is TRIM's ON_CUT plus the 3 tol the traced ends and pick can be off by, not
twice ON_CUT. A cutting edge picked before MSPACE or PSPACE moved to another space cuts nothing
there: the preview shows nothing and the trim is refused, so the preview never shows a cut the
trim can't make.
2026-11-29 23:30:36 -05:00
moandClaude Fable 5.2 b15f0b7158 A file that came with frame flag 2 keeps its own WIPEOUTVARIABLES object
The object a file brings is kept raw and written back, as on main, so a
drawing whose object holds 2 is saved as it was read. The writer still
produces only 0 or 1 itself: a setting changed in the session replaces the
file's object, and "shown but not plotted" set here is written as 1. The
dictionary key goes back out of the modelled entries, so the file's object
is kept again.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-30 04:21:24 +00:00
okereke-dev 0e41e906e1 TRIM/EXTEND: walk the space without collecting it when every object is an edge (review on #3526) 2026-11-29 23:09:57 -05:00
okereke-dev b357d69805 EXTRIM: count toward the preview cap only the parts it draws, rebuild the preview when the edited space changes (CodeRabbit on #3526) 2026-11-29 23:08:09 -05:00
vantruong-dang f3e071ccc2 fix(engine): frame only visible extents on initial paper layout switch 2026-11-30 11:05:45 +07:00
code-compliant d823c3e413 Reject unsupported user-defined hatch spacing
Require user-defined spacing to exceed the renderer limit in HATCH and SETVAR. Show the exact default spacing, and use a shared scale rule for rendering and DXF definitions.

Measure the rendered spacing before and after a DXF save at the first supported value.
2026-11-30 11:51:54 +08:00
code-compliant 5e8373933f Keep Ukrainian translations in the shared catalog 2026-11-30 11:46:45 +08:00
moandClaude Fable 5.2 ad16425480 Test: the top-down picker reaches a reference at its attribute value after ATTMODE changes
The picker skips a chunk whose cached envelope misses the query. With the
index rebuilt for the new ATTMODE, a box at the constant attribute value
finds the reference through the reused index, as the tree does.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-30 03:35:46 +00:00
mo 6ba8d0889a Merge remote-tracking branch 'origin/main' into spatial-index-attmode 2026-11-30 03:26:23 +00:00
moandClaude Fable 5.2 5820753676 Write only the documented 0 and 1 in the WIPEOUTVARIABLES frame flag
The DXF Reference gives the object's group 70 two values, 0 (no frame) and
1 (display frame). "Shown but not plotted" (WIPEOUTFRAME 2) displays the
frames, so it is now written as 1 and reopens as 1, as it did before this
branch; where a file keeps the third state is not documented.

The named object dictionary entry is listed with the entries the writer
models, so a file's own object is not kept beside the one written. Tests:
no setting writes a flag other than 0 or 1, and a changed setting replaces
the object a file came with.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-30 03:25:36 +00:00
HagaiBA bfd659e984 MTEXT: honor paragraph line spacing codes (\pxsm, \pxse, \pxsd) (#3638) 2026-11-29 23:50:45 +02:00
vangel76 bc9f54be52 Constraints: retain the dense sum’s positive zero identity 2026-11-29 22:03:52 +01:00
vangel76 42f7013c3b #3656: reuse sketch geometry when checking constraints after an edit 2026-11-29 22:03:10 +01:00
vangel76 ee7e64a382 Constraints: solve chains of dimensions with fewer products (#3657) 2026-11-29 22:03:03 +01:00
2ez4gcxandClaude Opus 5.5 9b9bf90230 render: mark the display list truncated when a fill stops at the fill cap (#3636)
triangulate_evenodd stops once its triangles pass 6,000,000 points (or
returns none past 200,000 edges) without telling the caller, so a fill
drawn in part left DisplayList::truncated false.

- fill: triangulate_evenodd_whole also says whether the triangles cover
  the whole region. The cap check moves to before the next slab that adds
  triangles, so the triangles are unchanged and a region whose last slab
  passes the cap counts as whole. triangulate_evenodd keeps its signature.
- Builder::region_tris marks the list truncated when a region is not
  whole; hatch fills and backgrounds, MLINE fills, Prim::Fill and WIPEOUT
  go through it.
- PolyClip keeps whether its region triangles are whole. A fill crossing
  the outline of a capped region is cut against the triangles there are,
  so it is drawn too little and never past the outline; may_leave_out
  says when that can happen and clip_prim marks the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 03:56:22 +07:00
2ez4gcxandClaude Opus 5.5 de1c000ebd test(mcp): move the history-trim test to the end of the file
The test is unchanged. At its first place it sat where #3642 adds a test
of its own, so the two branches conflicted in crates/mcp/src/tests.rs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 02:39:37 +07:00
2ez4gcxandClaude Opus 5.5 4e0f5fa57f fix(engine, mcp, ui): keep a request's output when the history trims (#3643)
Session::echo keeps the command history bounded: past 5,000 entries it
drops the oldest 1,000. Code that reported a request's output saved
log.len() as an index and returned the lines after it, so when the trim
happened during the request its output came back empty or partial while
the request still reported success.

Session now counts every line echo adds (never lowered by the trim or by
clearing the history). Session::log_mark returns that count, and
Session::log_since(mark) returns the lines echoed since the mark that the
history still holds. The collectors keep a mark instead of an index:
headless MCP cmdline.input, cmdline.script and cmdline.key, the window's
control channel (the same three), and the output of the lisp and appload
JSON commands. The history stays bounded as before.

Tests: lisp::tests::a_lisp_calls_output_survives_the_history_trim,
cadcraft-mcp tests::headless_output_survives_the_history_trim and
cadcraft-ui-egui control::tests::cmdline_output_survives_the_history_trim;
all fail without the change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 01:55:56 +07:00
garvitrakhecha 3e05a515a4 fix(cmdline): insert spaces inside unclosed AutoLISP expressions (#3632) 2026-11-29 22:27:26 +05:30
2ez4gcxandClaude Opus 5.5 8df3d9a241 io: return an out-of-memory error, not an abort, when DXF entities don't fit
Opening a large DXF aborted the process (handle_alloc_error) once an
entity list grew past its fallible up-front reservation, and the move of
the entities into the drawing allocated each of them again while the
list still held its copy.

- Entity lists grow fallibly (entity_room): doubling as a push would, but
  no further than their records can fill, so they end at about their
  final length; past the count (a polygon mesh's faces) they double. The
  up-front cap of #1833 is unchanged. A mesh's faces are reserved with
  their polyline and pushed straight into that room.
- The handle sets and the block list reserve before they insert.
- The first ENTITIES/BLOCKS list is moved, not copied; a repeated section
  (#865) is appended after a fallible reservation.
- Before each list moves into the drawing, room_to_place asks once,
  fallibly, for about the memory the drawing's copies take and hands it
  back for them.
- read_budgeted takes a test-only ceiling (None when reading) so tests can
  refuse a reservation as an allocator out of memory would.

A release cadcraft-cli opening a 10M-group binary DXF of LINEs in a job
with a memory limit now exits 1 with "DXF: out of memory reserving N
entities" at every limit from 1.2 to 2.45 GB (main aborted up to 3.0 GB)
and opens from 2.46 GB (main needed 3.2 GB; peak commit 3,215 -> 2,532 MB).

Part of #1922 (F-06).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:56:29 +07:00
2ez4gcxandClaude Opus 5.5 6318e09325 io: test that a long DXF entity list ends within its record count
Past the 65,536 entries an entity list reserves up front (#1833), the
DXF reader grows it by ordinary pushes. Each doubling is one allocation
that aborts the process when it can't be had, and the last one leaves up
to half the list spare. The new test reads 65,636 LINE records and
expects no more room than records; on main the list ends with room for
131,072.

Part of #1922 (F-06).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:56:16 +07:00
V1dalTheAbidal 6ad769c027 Selection through a viewport: test a constant attribute value (#3126)
A constant attribute's value counts in a reference's box since the block
caches hold `Contents`. Measured through a viewport it is left out when its
definition's layer is frozen there, as the renderer leaves it out. The test
fails when `contents` measures the value without the viewport's layers.
2026-11-29 18:19:47 +02:00
V1dalTheAbidal 1aac25a06f Selection through a viewport: text the drawing hides keeps no room (#3126)
`outline_in` added to the rectangle a dimension is hit along the room of
every text of its block on a layer frozen in the viewport. It did not look
at the drawing: text on a layer frozen for the whole drawing or turned off,
or invisible itself, had no room in that rectangle before a viewport was
counted, and got one when the viewport froze its layer as well, so a pick, a
crossing window, a fence or a crossing polygon took the dimension through
empty space. That text is now passed over.

A new test asserts the top side for each of those selections
with the layer frozen for the drawing and turned off, through a viewport
that freezes it too and through one that freezes nothing.
2026-11-29 18:16:08 +02:00
V1dalTheAbidal 574e966162 Merge remote-tracking branch 'origin/main' into pr/viewport-frozen-block-parts
Conflicts in crates/doc/src/extents.rs and crates/engine/src/select.rs.

extents.rs: main's `Contents` (a block's geometry, its constant attribute
values by tag and its definitions) is what the block caches hold, and it is
measured with the viewport's frozen layers: `contents` takes `frozen` and the
separate `in_drawing` cache, a constant value on a layer frozen in the
viewport is left out as the renderer leaves it out, and a clipped reference
takes the drawing's contents from `in_drawing` (`drawing_contents`).

select.rs: main's file with the viewport laid over it. A block reference is
hit on what is drawn (#3445), so through a viewport on what that viewport
draws (`insert_geometry` and `insert_fill_hits_box` take the frozen layers).
The frame of blank text (#2810) stays in the box a viewport gives. `pick_scanning`
tests its candidates through one `ViewportBounds`.

One test follows #3445: a clipped reference whose frame is hidden
(XCLIPFRAME 0) is no longer hit on its boundary, in any viewport, since the
boundary is not drawn; the window around it still takes it.
2026-11-29 17:57:59 +02:00
Cody Vogt ba0628ccdc Merge branch 'fix/annotative-text-contexts' into fix/annotative-mleader-contexts
# Conflicts:
#	crates/io/src/dxf_write/ctx.rs
#	crates/io/src/dxf_write/entity.rs
2026-11-29 08:27:40 -06:00
Cody Vogt 7d8d65aa77 Merge branch 'fix/block-record-annotative' into fix/annotative-text-contexts
# Conflicts:
#	crates/io/src/dxf_write/ctx.rs
2026-11-29 08:26:37 -06:00
Cody Vogt 785280cbbe Merge remote-tracking branch 'upstream/main' into fix/block-record-annotative
# Conflicts:
#	crates/io/src/dxf_raw.rs
2026-11-29 08:17:24 -06:00
2ez4gcxandClaude Opus 5.5 676e79a234 fix(engine, mcp): run a script's LISP routine on before its next input (#3635)
A LISP expression at Command: runs in 400,000-step slices, and only the
window's per-frame lisp_tick carries a routine on. Session::script gave
its next input right away and returned, so outside the window a routine
longer than one slice stopped after it for good: cadcraft-cli run and the
headless MCP server reported success with the routine cut short, and the
next LISP line got "a LISP routine is already running".

Session::lisp_run_until_input carries on such a routine until it ends or
waits for input (a get... prompt or a command pause). A script calls it
before each input it gives and once it ends, so the input goes to what
the routine waits for, or comes after it. The headless MCP backend calls
it after a command line and after Enter, since it has no frames either.
The window's own command line keeps its slices and Esc; a script in the
window, which already runs synchronously, now holds it until the routine
ends or waits.

Nobody can stop such a routine by hand, so it stops after
Limits::frameless_steps steps (BLOCKING_CAP, as a programmatic lisp call)
with the same "routine stopped after N steps" error; an endless *error*
handler is stopped one slice later.

Tests: lisp::tests::a_script_runs_a_long_routine_on_before_its_next_input,
lisp::tests::a_script_stops_an_endless_routine, cadcraft-cli
lisp_script::a_long_routine_in_a_script_draws_before_the_save and
cadcraft-mcp tests::headless_lisp_routines_run_to_their_end; all fail
without the change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 20:57:28 +07:00
Ray db961ff2b1 Grips: one grip per control vertex of a closed spline, and dragging it moves its copies (#3566)
A closed spline repeats control vertices: SPLINE CV's Close repeats the first at
the end, and control vertices that wrap round repeat the first degree. Grips
listed every copy and a drag moved one, which opened the curve. SPLINEDIT's
distinct/copies rule moves to Spline so grips use it too.

Control points count as copies only where they really repeat: a spline whose
knots wrap but whose tail doesn't repeat its first control points keeps every
control point its own, even when only its last matches its first.
2026-11-29 05:15:11 -07:00
2ez4gcxandClaude Opus 5.5 be693dbc92 fonts: give the face-names test its own temp folder, removed on drop
reading_a_user_fonts_names_keeps_no_font_bytes wrote its font to a
pid-named path in the temp folder without exclusive creation and removed
it by hand, so the file stayed behind if anything panicked before that
removal. The
font now goes in a folder the test creates itself (create_dir, trying the
next name if one exists), and a guard removes the folder when the test
ends, also on panic. The checks are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 17:44:20 +07:00
Yuri GanugiandClaude Opus 5.5 bdba75777d fix(ui): Drawing Units window id uses Id::unique, not the deprecated Id::new
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 11:01:25 +01:00
2ez4gcxandClaude Opus 5.5 0864c1fa48 fonts: read a family name past blank name records; make the names test deterministic
Face::family_name took only the first name record of each id and gave up
when it read as blank. Some installed fonts (43 VNI fonts on the test
machine) start name id 1 with an empty Unicode-platform record before the
Mac Roman and Windows names, so they had no family name. It now passes
over records that read as blank (empty, or in an encoding that is not
decoded) for the next one with the same id, bounded like Face::names.

reading_a_user_fonts_names_keeps_no_font_bytes took the first .ttf in
HashMap order from the installed fonts, so it failed whenever such a font
came first. It now writes its own font file (a name table built in the
test) and checks the same no-bytes property, plus the family read back.
A new test pins reading past blank records.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 14:29:46 +07:00
Yuri GanugiandClaude Opus 5.5 cce199c08b feat(i18n): translate the Drawing Units dialog; Italian labels
Route the UNITS dialog's labels, type lists, insertion units and buttons
through the catalog, and add the Italian translations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 07:06:01 +01:00
2ez4gcxandClaude Opus 5.5 351683c459 Mark fills refused past the point limit; style viewports within room
Two review findings on the plot style point limit:

- pattern_within kept going after a triangle set `full`; a later
  triangle over the pattern cell allowance then returned None, so the
  list was not marked truncated and later outlines were still styled.
  It now returns as soon as `full` is set; the cells running out first
  still keeps the fill solid, as before.
- Viewport contents were styled within the build's whole point limit,
  then clipped into the layout's list, which already holds the objects
  drawn before the viewport. Outlines that fit the contents' list but
  not the layout's stopped the append part-way and spent the build,
  dropping the last contents and the layout objects after them. They
  are now styled within the room the layout's list has left.

Part of #1603.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:17:07 +07:00
2ez4gcxandClaude Opus 5.5 5216e98977 Merge #3594's head d88fce7e0 into fix/web-highlight-pen-budget
Brings in "Start no clipped piece without room; skip viewport scans
once spent" (clip.rs, viewports.rs, tests.rs). No conflicts; the
viewport contents keep both the early return and the pen limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 11:43:58 +07:00
2ez4gcxandClaude Opus 5.5 d88fce7e03 Start no clipped piece without room; skip viewport scans once spent
CodeRabbit on #3594 and #3622:
- Pieces started a new piece when the cap had no piece left, so a long
  visible run was copied up to the point cap and then dropped. Starting
  a piece now stops the pieces there; a piece that fits exactly with
  nothing visible after it stays whole. The output is unchanged.
- A layout viewport after the build was spent still scanned model space,
  working out each object's bounds before entity() found nothing could
  be drawn. contents() now returns first when the build is spent and its
  list already says so. A build spent by a list filled exactly still
  scans, so the list is marked for what the viewport leaves out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 11:05:38 +07:00
2ez4gcxandClaude Opus 5.5 0f856d8af9 Size the selection highlight up front and cap plot style outlines (#1603)
On the web build (one allocation at most isize::MAX) two vectors could
still double past 2 GiB and panic with "capacity overflow":

- gpu::build_highlight_mesh grew its quads from empty. It now counts
  segments, point markers, fill corners, fill outline segments and
  image frame edges first and allocates once, as build_mesh does. Fill
  outlines are worked out once, while counting.
- pen::apply turned plot style line ends, joins and fill patterns into
  triangles after the build, outside MAX_DISPLAY_POINTS. It now stops
  at the list's point limit: from the first primitive whose geometry
  doesn't fit, the rest keep their plain line or solid fill and the
  list is marked truncated. Layouts and viewport contents use the
  build's own limit.

Measured on wasm32 (harness, Node): 40M highlighted points and a plot
of 1,060,000 round-ended lines panicked on the base; now 1.12 GB
allocated once, and 63,999,974 points marked truncated.

Part of #1603.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 09:11:49 +07:00
FredApps 8c0f7658a3 Release: CADCraft v0.21.0 (main 66931918cb)
Merge main into release. The tree equals main 66931918cb.
2026-11-28 21:39:43 +01:00
okereke-dev a0ab5c64c4 EXTRIM: delete only pieces with no length at all, leave the too-short stretch out of the preview, rebuild the preview when the frozen layers change (CodeRabbit on #3526) 2026-11-28 15:22:14 -05:00
moandClaude Fable 5.2 fc19d899eb Test: a layer-0 attribute of a nested reference follows the outer reference's layer
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 18:18:00 +00:00
2ez4gcxandClaude Opus 5.5 e0cde731c9 Clip within the room the list has left; keep clip_list's flags
CodeRabbit review on #3594:
- clip_list started from an empty list, so a list the budgets had
  cut came back with truncated false. It now starts with the input's
  truncated, undashed and expanded, as viewport contents merge them.
- clip_prim built the whole clipped result before push_raw checked the
  list's limits. A fill crossing a clip edge fans to more points, and a
  line crossing an outline of many edges splits into a piece per
  crossing, so the transient result could pass 2 GiB on wasm32 from a
  list within its budgets. clip::Cap and _within variants of the
  rectangle and outline clips stop at the room left (Limits::left) and
  say so; clip_prim appends what fit and marks the list truncated. A
  fill cut there keeps the triangles that fit, as line pieces already
  did. The uncapped functions stay as wrappers for their other callers.
  PolyClip::clip_triangles' 6,000,000-point stop now marks the list too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 00:43:01 +07:00
Ray 908e586eba Layers palette: Up and Down move through the current layer list's names (#3400)
egui's own arrow-key focus moved from the combo into the nearest row button
below and then down that column, so Enter toggled a lock instead of making a
layer current. In the open list, Up and Down now move from layer name to layer
name and scroll it into view; from the combo, Down goes to the current layer.
Enter or Space on a name makes it current. Each row's On/Off, Freeze/Thaw and
Lock/Unlock buttons are also named with their layer, so they no longer share
three names.
2026-11-28 10:26:22 -07:00
Ray fc1785b859 Properties: a transparency percentage can be typed, and a slider shows its range (#3573)
Clicking the Percent box in the Transparency menu closed the menu, because a
menu closes on any click inside it, so the value could only be dragged. The
Transparency menu now closes only on a click outside it (ByLayer and ByBlock
close it themselves), and the box is a slider with its value box, labelled
Percent.
2026-11-28 10:17:15 -07:00
moandClaude Fable 5.2 b9fb71535a The dynamic-grip preview keeps an attribute set on layer 0 on layer 0
The preview drew such an attribute on the reference's layer, unlike the
drawing itself.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 17:15:57 +00:00
Ray 55af51527e Layers palette: the current layer list scrolls to layers past the bottom of the screen (#3400)
The drop-down under the Layers palette's current layer, and Properties > Layer
with nothing selected, listed every layer in one column with no scroll area, so
with many layers the last ones were off screen and could not be picked. Both now
scroll like the Properties layer menu for a selection (#1467), at the same
height. The current layer combo also gets a combo box node named after the
layer it shows.
2026-11-28 10:09:27 -07:00
moandClaude Fable 5.2 26196a7418 Declare the WIPEOUTVARIABLES class in a DXF that holds the object
The object is of a class a reader does not have built in, so the CLASSES
section names it, as it does for RASTERVARIABLES. A test checks that a
drawing with the setting gets one object, one class and one dictionary
entry, that a drawing without it gets none, and that saving twice does
not add a second object.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 16:42:25 +00:00
moandClaude Opus 5.5 e4e48426f2 An attribute set on layer 0 stays on layer 0 on save, in the drawing and on BURST (#3492)
Layer 0 puts an attribute on its block reference's layer only when the
attribute takes it from its definition. The DXF writer (and so the DWG
bridge), the renderer, BURST and the attribute editor's current layer
applied that rule to an attribute whose own layer is 0 as well, so it was
saved, drawn and exploded on the reference's layer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 16:42:22 +00:00
moandClaude Sonnet 5.5 5b460a6061 Save WIPEOUTFRAME in the drawing's WIPEOUTVARIABLES object, in DXF and DWG (#3440)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 16:34:31 +00:00
2ez4gcxandClaude Opus 5.5 afbc8a26eb Merge origin/main into fix/web-display-primitive-budget
Resolve the conflicts in crates/render with #3564 (dash budget) and
#3560 (block-loop cache), keeping every side:
- Builder carries the point, primitive and dash counters and the loop
  cache; every part, XCLIP part and viewport-contents builder gets all
  of them, shared.
- build_space_within takes the point, primitive and dash limits; the
  tests of both PRs pass the other budget's default.
- The clipped appends carry undashed beside truncated, and spend the
  build when a piece doesn't fit.

Also test the shared primitive count with a limit no one parallel part
reaches (300 of 600, parts of 256). Since Builder::join limits the
joined list, the limit below one part passed without the shared count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 23:31:28 +07:00
2ez4gcxandClaude Opus 5.5 e5d3fe6a0b fix(io): keep OBJECTS records as slices of the DXF tag list while a file opens
Part of #1922 (F-06 e). The DXF reader's Objects kept every XRECORD,
TABLESTYLE, DIMASSOC, MLEADERSTYLE and GROUP record as a to_vec() copy of
its groups while read_budgeted still held the tag list they came from, so a
file made of such records held them twice while it opened. Objects now takes
a lifetime and keeps them as slices of that list; the records are read by
the same code from the same groups.

Peak commit opening 20M-tag crafted files (dev build): TABLESTYLE,
MLEADERSTYLE, DIMASSOC and CADCraft's own XRECORDs 1,660 -> 895 MB in ASCII
(87 -> 47 bytes per tag, the tag list alone) and 2,115 -> 1,991 MB in binary;
GROUPs 2,476 -> 1,367 MB (ASCII). Reading and saving give byte-identical
DXF and DWG output on 22 files.

The binary tag list's growth (craft-dxf, storytold/craft-libs) is left out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 22:50:16 +07:00
2ez4gcxandClaude Opus 5.5 bedf44ba88 Update url to 2.5.9 and async-executor to 1.14.1 in Cargo.lock
Clears the two cargo-deny advisory findings that #3607 ignores for now:
- url 2.5.8 -> 2.5.9 (RUSTSEC-2026-0592, stack overflow in
  Url::origin() on nested blob: URLs); form_urlencoded 1.2.2 -> 1.2.3
  comes with it because url 2.5.9 requires ^1.2.3.
- async-executor 1.14.0 (yanked, use-after-free in Executor::drop)
  -> 1.14.1 (smol-rs/async-executor#164).

Lockfile only; no Cargo.toml change. Part of #1935 (F-17).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:47:41 +07:00
2ez4gcxandClaude Opus 5.5 09f025ede3 render: say when clipped attributes or parallel parts are left out (#1603)
Review on #3594:
- The XCLIP attribute part's `truncated` flag now reaches the parent
  list, as the block-contents part's already did. A clipped reference
  whose attributes ran out of budget as the last object of a drawing
  drew 98 of 105 points and said nothing.
- The parts of a parallel build are joined within the list limits
  (Builder::join). Clipped copies are in no shared count, so two XCLIP'd
  blocks in different parts could join to 798 primitives against a
  limit of 748, unmarked. Parts are appended whole while they fit; at
  the first that doesn't, the build is spent and marked truncated. This
  is native-only: the web build has no parallel path.

Part of #1603.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 20:05:30 +07:00
2ez4gcxandClaude Opus 5.5 3771719811 render: budget the primitives a display list holds (#1603)
On wasm32 a DPrim is 40 bytes and one allocation can take at most
isize::MAX (2 GiB - 1): a list of more than 2^25 primitives panicked
with "capacity overflow" when its vector grew. The 64M-point budget
(#3306) charged a point primitive one point, so it allowed 64M of them;
a 4.5 MB DXF of dotted lines reached 33.56M.

- MAX_DISPLAY_PRIMS, charged once per primitive beside the points and
  shared like them: 2^24 on 32-bit targets, equal to MAX_DISPLAY_POINTS
  (and not counted) on 64-bit ones, where it can't bind.
- Clipped copies (viewport contents, XCLIP) are appended only while the
  list has room within both limits; the append stops at the first piece
  that doesn't fit and the build is spent, as when a budget runs out.
  Builder::charge checks the same room in its own list.
- Compile-time asserts: the primitive, point, pen, plotted-text and
  image vectors stay under isize::MAX bytes at these limits (checked
  for wasm32 by the wasm step).
- gpu::build_mesh counts its lines and quads first and allocates each
  array once: the quads grew by doubling and passed 1 GiB on large
  lists with lineweights shown.

Part of #1603.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 19:26:23 +07:00
code-compliant 9e9ce35ac9 Fix attribute editor prompts and multiline values
Use the command line when a prompt is active. Keep line breaks editable and use each visible tag as the value field label.

Verified with 23 attribute editor tests and four accessibility tests on Linux.
2026-11-27 20:07:08 +08:00
vantruong-dang 465234b4f9 fix(table): remove 50-line row-height cap in pastetable 2026-11-27 14:38:09 +07:00
vantruong-dang 9e9a1f5aaf test(ui): place duplicate Copy after PasteTable to prove deduplication 2026-11-27 14:11:45 +07:00
vantruong-dang 7534c964f9 fix(table): size pasted table rows and widths from resolved Data cell style 2026-11-27 14:06:55 +07:00
Christopher Gay 2c690e5da0 SCALE: a factor point on the base point re-prompts instead of ending the command (fixes #3475)
At the Specify scale factor prompt, a picked point at the base point gives a
factor of zero. The command then cleared the selection and ended without
scaling anything or saying why. It now answers "Requires a positive number."
and stays at the prompt, keeping the selection and base point, as typed
factors and the Reference option already do. Non-finite factors are rejected
the same way.
2026-11-26 23:09:03 -06:00
moandClaude Fable 5.2 172de6d33f Merge main into text-box-aligned-fit
Both sides added tests at the same place in crates/doc/src/tests.rs; all
are kept.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-26 16:34:30 -05:00
moandClaude Fable 5.2 8d9f464c8e Merge main into spatial-index-attmode
main now holds the dimension styles behind a shared pointer; the ATTMODE
comparison is kept next to the updated style comparison.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-26 16:34:27 -05:00
ATOM bfe2e35e0e dxf: apply negative DIMLFAC by dimension space 2026-11-26 09:27:17 -06:00
paco-velascoandClaude Fable 5.2 54cdaf45f4 Linux file dialogs: name the file types in the interface language
The filter labels were translated on the dialog's thread, where the
interface language (thread-local) is English. They are now read on the UI
thread and handed to the dialog's thread.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-26 15:46:14 +01:00
paco-velascoandClaude Fable 5.2 457f97f25b Linux: the window keeps answering while a file dialog is open
The Open, Save, APPLOAD and ALIASEDIT dialogs ran in the window's event
handler and waited there for the desktop portal's dialog. For as long as it
was open the window answered nothing, and after a few seconds the desktop
offered to force-quit the app. The dialog now waits on a thread of its own,
through Services::start_pick, as the macOS sheets do.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-26 15:18:05 +01:00
code-compliant 00aed39b3d Report pending edits for removed attribute rows 2026-11-26 15:53:42 +08:00
ATOM 1db31ea608 dxf: store DIMLFAC-scaled dimension measurements 2026-11-26 01:45:45 -06:00
vantruong-dang 20d4247ed5 fix(ui): preserve clipboard event ordering for PasteTable in shortcut dispatch 2026-11-26 14:35:13 +07:00
code-compliant 43269207e1 Merge origin/main into repair/1213-block-attribute-editing
Keep the Attribute Editor alongside the INSERT attribute entry and Array dialogs. Start the headless runtime in the Attribute Editor UI tests, as on main.
2026-11-26 14:31:31 +08:00
vantruong-dang 80001617ef fix(engine): repeat interactive pastetable with last TSV payload on Enter 2026-11-26 12:31:37 +07:00
vantruong-dang 3f20fb67c5 fix(table): wrap cell text within column width and size row heights to wrapped lines 2026-11-26 12:28:45 +07:00
vantruong-dang e3f1a0b1d2 test(engine): cover SCALE Reference previews and hot-grip point-pick branches 2026-11-26 11:46:29 +07:00
code-compliant 097506fb2e Keep user-defined hatch defaults separate from named scale
Use HPSPACE and HPDOUBLE for the current session. Keep HPSCALE as the named pattern scale.

Fixes #3525.
2026-11-26 10:10:51 +08:00
code-compliant be11e95239 Test that a user-defined hatch listed with 78 = 0 gets its families from the double flag
The reader builds a user-defined hatch's families from its double flag (77) when a file lists
no definition lines, as AutoCAD writes its own. The other tests save explicit families, so none
of them reached that fallback. This one rewrites a saved hatch to 78 = 0 with no lines and a 77
of 0 or 1, and reads it: one or two unit families, with the hatch's angle and spacing kept. It
fails with the fallback switched off.
2026-11-26 09:28:28 +08:00
Jon Breen b273a72307 DXF: keep covered table cell text through 2007 and later saves
A covered cell's text now goes in its own value block, like any other
cell's, instead of an empty block, so unmerging after a reopen brings
it back. An empty covered cell still writes an empty block. Follow-up
to #3392.
2026-11-25 13:32:02 -06:00
code-compliant 4d5661ebc2 A script a LISP routine starts feeds its own lines: its HATCH keeps the interface prompts 2026-11-26 03:04:29 +08:00
code-compliant f533ea8723 HATCH's published answers belong to a LISP routine's call, not a script's line
A script's own HATCH line started taking the published command-line
questions, so `HATCH A <angle>` in a script read A as a pattern name and
left the command asking for a scale. HATCH now asks them when an AutoLISP
`(command ...)` call starts it: the program input a routine feeds the
command line. A script's own line and a person keep the interface's
prompts, picking the boundary first, as before. A routine's call made
inside a script still gets the published order.

The two starts are told apart at the point HATCH chooses, with
lisp_program_input(), which answers for the routine's input alone:
command_origin() reports a script and a routine as program starts alike.

A script's HATCH keeps the interface's prompts, and a routine's call from
inside a script keeps the published order, each with its own test.
2026-11-26 02:42:54 +08:00
code-compliant 1b065b5a7e Hatch save: a scale too small to draw writes unit-scale lines, as the reader and renderer use, so resaving does not shrink them 2026-11-25 23:50:56 +08:00
code-compliant 9144d3148b A user-defined HATCH writes the pattern definition lines it keeps
A HATCH with the pattern name _USER was saved with group 78 = 0 and no
definition lines, though the DXF Reference has no user-defined exception
to 78's number of pattern definition lines. Another program read no
lines and its explode produced nothing, and a hatch whose lines are
based away from its origin reopened with them at (0,0).

The writer now lists a user-defined hatch's own families as it lists
any pattern's: each line's angle, base point, offset and dashes, scaled
and rotated as the hatch draws them, with the real count in group 78.
The pattern type (76 = 0) and the double hatch area flag (77) are
unchanged, and a DWG keeps the lines too, since the bridge converts the
same written HATCH. A file that lists no lines for a user-defined hatch
(78 = 0, as AutoCAD writes its own) is still read from its angle,
spacing and double flag.

The save test now expects the real count, and a doubled user-defined
hatch based at (1,1) keeps both families' angle, base point, offset and
count through a DXF save and read and a DWG save and read.
2026-11-25 22:41:34 +08:00
cloutier 05dbdfa9d3 Use custom DIMPOST prefixes on radial dimensions (#3511) 2026-11-25 09:40:06 -05:00
moandClaude Fable 5.2 921ea89a10 fix(doc): Aligned and Fit text extents follow how unusable sizes are drawn
A height of 0 is drawn as a height of 1, which left the Aligned box
empty (0 / 0). Fit text with an unusable width factor is drawn at its
own width, not stretched to the second point.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 09:13:37 -05:00
code-compliant b3682f9286 HATCH from a script or LISP routine takes its published answers (#3498)
A script, a LISP (command ...) routine or the command line's -HATCH
used to share one prompt machine: HATCH took every answer as a pattern
name. HATCH now asks the published questions when a program starts it:
the pattern name (or ?, Solid, or the user-defined form), then the
pattern's scale and angle, or the user-defined form's line angle,
spacing and double flag, and then the boundary objects. Enter takes
the default at each question, and a refused scale or spacing is asked
again.

-HATCH keeps its own prompts. It is a command id of its own rather than
an alias, so a dashed start is never the HATCH sequence; a person, the
interactive HATCH and the -HATCH Properties option are unchanged.

A user-defined hatch is stored as DXF's _USER pattern: pattern type 0,
the spacing as its scale, the lines' angle, and a second family at
right angles when doubled, which the file's group 77 records. DXF
reads the families back when a file has no pattern definition lines,
and writes the pattern type and double flag.

-HATCH is classified with the file-reading commands.
2026-11-25 21:52:29 +08:00
moandClaude Fable 5.2 5d7ec3ba60 fix(doc): Aligned text extents use the width factor the fonts shape with
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 08:30:49 -05:00
moandClaude Fable 5.2 ec55357459 fix(doc): the extents of Aligned and Fit text span their two points
Aligned and Fit text are drawn from their first point to their second,
whatever rotation is stored: Fit at its own height with its width
stretched, Aligned at the height that keeps its proportions. The
extents measured them like left-justified text at the stored rotation,
so ZOOM Extents and selection by box missed where they are drawn.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 07:56:36 -05:00
okereke-dev 9766e4dbe8 EXTRIM: name skipped.partly in the command's parameters 2026-11-25 07:09:58 -05:00
okereke-dev 79f0f000b0 EXTRIM: leave a stretch too short for TRIM to cut alone, keep short pieces that have length, count a partly cut object once (landing review of #2808)
A stretch whose end is within TRIM's on-cut tolerance of its pick made TRIM run on to the next
cut and take more than planned; it is now left and the object counted as uncut. Only pieces of
no length are deleted, as TRIM leaves short ones. An object cut in part is counted with those
not cut everywhere (skipped.partly), not also as trimmed.
2026-11-25 07:09:53 -05:00
okereke-dev 4746a3192d EXTRIM: leave layers frozen in the active viewport, cap the preview by drawn parts (landing review of #2808) 2026-11-25 07:06:57 -05:00
okereke-dev f37f36d39c TRIM/EXTEND: gather only the given cutting edges instead of scanning the space (landing review of #2808) 2026-11-25 07:04:05 -05:00
okereke-dev ad4a53a324 TRIM preview: cuts far from the origin stay apart (landing review of #3382)
The highlight merged cut points within 1e-9 of the distance from the origin, a whole unit near
x = 1e9, so a visible 0.5-unit trim there was merged away and the whole object highlighted. Cuts
now merge only when f64 can't tell them apart.
2026-11-25 07:03:14 -05:00
Walter Haslbeck 456cecd2f7 proxy layers test: a nameless LTYPE record counts on reading and isn't written 2026-11-25 08:40:07 +01:00
Walter Haslbeck 87fb3f2ddb fix: proxy graphics follow-ups from the #3454 landing
- names_by_index (was layers_by_index): markers only for the indices a
  record uses, looked up in a map, so a large index costs no more than a
  small one; the 65,535 cap goes.
- An index after which the graphics stay on the layer before is named by
  the file's LAYER table when it names that layer there.
- with_proxy_tables (was with_proxy_layers) remaps kept dimensions'
  pictures too; a reference to a *D block is never taken for the picture.
- Snaps walk a record's graphics like a block's contents: none on layers
  that are off or frozen.
- ellipse() rejects conjugate radii on one line (an exact quarter turn
  draws as a line); a sweep at or below EPS draws as its chord.
- Linetype indices follow the written LTYPE table (Drawing::proxy_linetypes);
  RENAME follows, PURGE keeps linetypes only proxy graphics use.
2026-11-25 07:51:13 +01:00
moandClaude Fable 5.2 2231e21d8d fix(engine): the spatial index is rebuilt when ATTMODE changes
Since #3462 a block reference's bounds include the constant attribute
values it shows, which ATTMODE decides. The index kept bounds measured
under the old ATTMODE, so after a change window selection and picking
could miss, or still find, a constant value. ATTMODE is now part of the
context the index is reused under.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 22:14:11 -05:00
V1dalTheAbidal 47fe64250c Selection through a viewport: a dimension's kept text room is reachable (#3126)
The rectangle a dimension is hit along keeps the room of block text the
viewport leaves out (`outline_in`), but a pick, selection cycling, a crossing
window, a fence and a crossing polygon first tested `bounds_in`, which leaves
that room out, so a side lying there was never reached. They now test
`touch_box_in`: `bounds_in` with that room. A window's containment test stays
on `bounds_in`.

A window polygon tested the corners of that rectangle as well, so it needed
the hidden text's room where a window of the same shape did not.
`hit_polylines_in` now keeps the room only for selections that touch.

The dimension-text test asserts the top side of the rectangle for each of
those selections and a window polygon against a window of the same shape.
2026-11-25 04:27:53 +02:00
Cody Vogt 5303fb4d3b Merge branch 'fix/annotative-text-contexts' into fix/annotative-mleader-contexts 2026-11-24 17:50:13 -06:00
Cody Vogt 52e71b8a9c Merge branch 'fix/block-record-annotative' into fix/annotative-text-contexts 2026-11-24 17:50:12 -06:00
Cody Vogt 21f16fe7f7 Merge remote-tracking branch 'upstream/main' into fix/block-record-annotative
# Conflicts:
#	crates/io/src/dxf_raw.rs
2026-11-24 17:50:01 -06:00
V1dalTheAbidal 71eea0add8 Selection through a viewport: a proxy in a block counts by what the viewport draws (#3126)
`unknown_bounds`, added on main by #2697, now takes the layers frozen in the
viewport and the drawing-bounds cache, and passes them on to `in_block_visible`
and `bounds_in` as the other block paths do. Without them the merge with main
did not compile. A proxy is never selected itself, so this only matters for a
proxy that is a part of a block: its graphics on a layer frozen in the viewport
take no room in the reference's box there. A new engine test covers that case.
2026-11-25 00:35:00 +02:00
V1dalTheAbidal 4ba0a5a166 Merge remote-tracking branch 'origin/main' into pr/viewport-frozen-block-parts 2026-11-25 00:17:57 +02:00
code-compliant 93816c5822 Merge remote-tracking branch 'origin/main' into repair/1213-block-attribute-editing-maint
# Conflicts:
#	crates/engine/src/lib.rs
2026-11-24 14:54:43 +08:00
code-compliant f61f15fc64 Fix stale attribute edit reports and viewport selection
- ATTEDIT/EATTEDIT: take the reference from the active viewport selection,
  so a layer frozen in an MSPACE viewport is respected.
- Echo the stale-rows Apply refusal to the command line as well as the dialog.
- Check pending text for read-only Properties attribute rows (constant or
  multiline), so a stale value is reported and dropped.
- Add regression tests for all three.
2026-11-24 14:34:20 +08:00
Cody Vogt c305d45688 Merge branch 'fix/annotative-text-contexts' into fix/annotative-mleader-contexts 2026-11-23 16:37:06 -06:00
Cody Vogt be8c2e690f Merge branch 'fix/block-record-annotative' into fix/annotative-text-contexts
# Conflicts:
#	crates/io/src/dxf_write/entity.rs
2026-11-23 16:37:05 -06:00
Cody Vogt fc6dbb5a1c Merge remote-tracking branch 'upstream/main' into fix/block-record-annotative 2026-11-23 16:36:52 -06:00
Tanish Manku cda891fb4e UNDO stops at a REFCLOSE Save that wrote an xref's file, instead of bringing back an edit it can't save 2026-11-23 13:30:21 -07:00
Tanish Manku 39fca9e2a7 Xref baseline: keep the file's modification time as the system gives it, so a time before 1970 counts 2026-11-23 13:30:21 -07:00
Tanish Manku 506ad531eb REFEDIT: refuse a reference with several columns or rows instead of opening its first instance 2026-11-23 13:30:21 -07:00
Tanish Manku 003ab113c2 REFCLOSE Save: refuse a host block the xref's drawing defines differently under its name 2026-11-23 13:20:39 -07:00
Tanish Manku 273437af7a REFCLOSE Save: a host linetype brings the text styles its dashes are drawn in 2026-11-23 13:17:36 -07:00
Tanish Manku d0d027ac8f REFCLOSE Save: a dangling reference the xref's file already had is written as it was 2026-11-23 13:15:38 -07:00
Tanish Manku 4c004d5dd5 REFCLOSE Save: count only the xref's dimensions that are written as losing their associations 2026-11-23 13:13:09 -07:00
Tanish Manku 3e98ef30e7 REFEDIT: an xref's version and form come from the read that gave its drawing and stamp 2026-11-23 13:10:19 -07:00
Tanish Manku 4840d576a5 REFEDIT: an outer reference REFEDIT can't open offers no nested level 2026-11-23 13:08:04 -07:00
Tanish Manku 07bdd66b1d REFEDIT docs: an xref's backup is kept only when ISAVEBAK is on 2026-11-23 12:55:51 -07:00
V1dalTheAbidal a9643c0a27 Selection through a viewport keeps two things it counted before (#3126)
Review of #3214: counting the layers frozen in the viewport took two
answers away that a selection through a viewport gave before.

A point on the layer Defpoints that is a part of a block (the definition
points of a dimension are held so) was hit and took room in a window
whatever the viewport froze. It counts again: ViewportBounds measures it,
and build_entities_in_viewport keeps it, also where the viewport freezes
Defpoints. A line on Defpoints follows the viewport, and what a viewport
draws on screen is built as before.

A crossing window inside the box of a dimension's text took nothing where
the viewport does not draw that text. With the text left out of the box,
a side of the rectangle the dimension is hit along ran through that
place and the window took the dimension. The rectangle now keeps the room
of the text the viewport leaves out; a window still needs only what the
viewport draws.
2026-11-23 17:49:14 +02:00
V1dalTheAbidal 4de385b87a Merge branch 'main' into pr/viewport-frozen-block-parts 2026-11-23 17:36:26 +02:00
code-compliant 8f2a89d048 Properties: a pending edit follows the whole attribute (#1213)
The pending snapshot and the dialog's stale-row check compared the fields a
row shows: tag, prompt, value, insertion point and flags. Two attributes can
match all of those and still be different attributes. With two editable `T=v`
definitions at the same insertion point, texts 1 and 2 high, typing into the
first Properties field and then running `battman {"name":"Twin","action":
"down","tag":"T"}` leaves every compared field equal while the reorder puts
the height-2 attribute in that place; Enter wrote the typed text there, and
the dialog applied its stale row the same way, both without a message.

The row now keeps the whole stored attribute: `AttributeRow::record`, the
engine's own `Attrib` (its text, its own layer, colour, linetype and
lineweight overrides, its modes and its multiline text). A pending edit and a
dialog row are bound to that record, so any stored property that differs
refuses the stale text and says so. The displayed fields stay for the list.

Equality is the drawing data's: two attributes identical in every stored
property are interchangeable, so a swap between them still applies. Text
holding a NaN never equals itself, so such a row refuses a pending edit; it
does not panic.

Tests: both paths write the height-2 attribute without the record comparison
and change nothing with it, checked by height.
2026-11-23 20:06:56 +08:00
code-compliant 3149c42abb Properties: stale attribute text never reaches another attribute (#1213)
The pending snapshot kept a tag and a value, and two attributes can share
both: with definitions `T=v` at [0,1] and [0,2], typing into the first row and
then running `battman {"name":"Twin","action":"down","tag":"T"}` left the
snapshot matching, because the swapped attributes still reported `T` and `v`,
so Enter wrote the typed text into the other one. The Edit Attributes dialog's
stale-row check compared the same two fields and had the same weakness.

The snapshot now keeps the whole row, whose insertion point is the new
`AttributeRow::at`, and the dialog compares every property it shows, so both
paths refuse a reorder that only moves attributes.

A frame that finds another attribute in the field's place also takes no input:
text and Enter queued for that frame were meant for the attribute the field
had, so they neither commit nor become a pending buffer for the one there now.
The field draws the drawing's value, inert for that frame, and editing resumes
on the next.

Tests: equal tag and value attributes swapped under pending text write the
wrong attribute without the stronger comparison, in the Properties palette and
in the dialog; input queued for the frame that finds the row stale reached the
new row without the inert frame.
2026-11-23 17:34:00 +08:00
code-compliant fe10d3241a Properties: pending attribute text stays with its attribute (#1213)
A Properties attribute field is a place in the reference: `attedit` takes `at`
by index. The pending text was kept by drawing, reference and index alone, so a
reorder (`battman` order), a value edited from another path, or an undo that
put another attribute in that place handed the typed text to whichever
attribute was there. With attributes `[NO=7, NOTE=n]`: type into NOTE, run
`battman {"name":"Tag","action":"order","order":["NOTE","NO"]}` while it waits,
press Enter, and NO became `EG` while NOTE stayed `n`.

The pending text now carries the tag and value it was typed into. When the
place holds another attribute, the text is dropped, no `attedit` is sent, and
the command line says the value was not applied, as the dialog refuses a stale
row. An ordinary edit is unchanged, still one undo step.

Tests: a reorder, an edit from elsewhere and an undo under pending text each
write the wrong attribute without the snapshot check and change nothing with
it.
2026-11-23 15:50:57 +08:00
code-compliant 967c2d3111 attedit_dialog: a Properties attribute edit is one undo step (#2792)
The editor tests cover opening the dialog, drawing switches, repeated tags and
stale rows, but not a value typed into the Properties field reaching the
drawing and coming back with one Undo. This adds that case: type into NOTE,
press Enter, see the new value, undo, see the old one.

Test shape follows PR #2912's Properties edit and Undo test.
2026-11-23 12:38:22 +08:00
code-compliant 883eb6b65c Properties: an attribute tag keeps its own text, not the interface's
The Attributes group labelled its rows with prop_row, which looks the label up
in the interface catalogs: a tag such as `To` read as `A` in Spanish, and a tag
matching any other interface string changed the same way. A data_row helper
takes the label as it is, for drawing text, and keeps prop_row translated.

Test: attribute_tags_in_properties_are_not_translated fails without the helper.

The helper and the test shape follow PR #2912, which fixes the same label in
its Attributes group; this change does not bring that PR's xdata group.
2026-11-23 12:38:22 +08:00
code-compliant f7029901c1 Merge remote-tracking branch 'origin/main' into repair/1213-block-attribute-editing 2026-11-23 10:28:51 +08:00
Tanish Manku 9e7663b25c REFEDIT.LEVELS is classified for the automation roots: it touches no file
The PR's new command was on no list, which main's every_command_is_classified
test refuses. Its "path" is a path of nested references, not a file.
2026-11-20 19:25:05 -07:00
Tanish Manku 10727f5025 REFEDIT: a nested reference is offered only when it opens with its parents
Discovery checked each reference's own transform, while opening it checks the
transform with everything above it: two small uniform scales together could be
offered and then refused.
2026-11-20 18:55:52 -07:00
Tanish Manku 1515833f2c REFCLOSE Save: an xref's backup follows ISAVEBAK, as SAVE's does
With ISAVEBAK off, SAVE keeps no .bak; the write-back of an xref kept one anyway.
2026-11-20 18:53:05 -07:00
Tanish Manku 28d8ba72c5 REFCLOSE Save: name the dimension associations an xref's write-back leaves out
Loading an xref drops its dimensions' associations, so writing it back leaves
them out of the file. When the part written back had associative dimensions,
the save says so and lists "dimension associations" in notSaved, pointing at
the backup that keeps them. A dimension drawn during the edit attaches to the
host's copies, whose handles mean nothing in the xref's file: it is written
without those associations, and counted too.
2026-11-20 18:51:28 -07:00
Tanish Manku 5af8fc020a REFCLOSE Save: an xref is not written naming a block it doesn't define
A host dimension style copied into the xref's drawing brings the blocks its
arrowheads are drawn with. A block the written objects still name that the
drawing lacks, such as another xref of the host added with REFSET, refuses the
save: the file, its backup and the edit stay as they were.
2026-11-20 18:47:03 -07:00
Tanish Manku a3e04070be REFCLOSE Save: test that an xref's write-back reports what SAVE would
The merge replaced the PR's own loss report with main's lost_writing and
lost_message (the conflict was in cmd/file.rs). This covers a case the PR's copy
missed: a proxy an R2000 DXF xref can't keep is named, with the reason and the
backup that still has it.
2026-11-20 18:44:39 -07:00
Tanish Manku 210a99ecc8 REFEDIT xref tests: the tests that read and write DWG allow the in-process converter themselves
main now refuses to convert a DWG in process unless the caller allows it, so these
two tests failed after the merge.
2026-11-20 18:43:25 -07:00
Tanish Manku bc703cb134 REFEDIT and REFCLOSE: an xref is read and written only inside the automation roots
refedit and refclose touch files, so they move to the FILES list. REFEDIT checks
that the xref's file may be read and written before an edit begins; REFCLOSE Save
checks the file it writes and its .bak before anything is read or written, so
roots put in force since the edit began hold too. A refused save leaves the xref,
its backup and the host as they were, and the edit stays open.
2026-11-20 18:42:31 -07:00
Cody Vogt f4a18d46d0 Merge branch 'fix/annotative-text-contexts' into fix/annotative-mleader-contexts 2026-11-20 19:41:23 -06:00
Cody Vogt 9809059ffa Merge branch 'fix/block-record-annotative' into fix/annotative-text-contexts 2026-11-20 19:41:23 -06:00
Cody Vogt 50b37bda98 Merge remote-tracking branch 'upstream/main' into fix/block-record-annotative
# Conflicts:
#	crates/doc/src/foreign.rs
2026-11-20 19:41:23 -06:00
Tanish Manku 84eb20b5c0 Merge #2355: blocks: REFEDIT edits xrefs in place and writes their drawing back; nested references, faded drawing and Edit Reference bar
# Conflicts:
#	crates/engine/src/cmd/file.rs
#	crates/render/src/draw.rs
#	crates/render/src/lib.rs
#	crates/render/src/pipeline.rs
#	crates/render/src/viewports.rs
2026-11-20 18:32:01 -07:00
Cody Vogt 86202b9cc4 Merge branch 'fix/annotative-text-contexts' into fix/annotative-mleader-contexts 2026-11-20 18:52:38 -06:00
Cody VogtandClaude Opus 5.5 56dc8fb410 DXF writer: annotation scale planning in two helpers (main's tags_kept_for passed the complexity limit)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:52:37 -06:00
Cody Vogt dc56b87e73 Merge branch 'fix/annotative-text-contexts' into fix/annotative-mleader-contexts
# Conflicts:
#	crates/io/src/dxf_anno.rs
2026-11-20 18:43:58 -06:00
Cody VogtandClaude Opus 5.5 0f40e91e82 io: dxf_anno reads main's borrowed DXF sections (SectionRef)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:43:00 -06:00
Cody Vogt 6e211deb37 Merge branch 'fix/annotative-text-contexts' into fix/annotative-mleader-contexts
# Conflicts:
#	crates/io/src/dxf_anno.rs
2026-11-20 18:35:57 -06:00
Cody Vogt 8892b53b3b Merge branch 'fix/block-record-annotative' into fix/annotative-text-contexts
# Conflicts:
#	crates/io/src/dxf_write/common.rs
#	crates/io/src/dxf_write/ctx.rs
#	crates/io/src/dxf_write/sections.rs
2026-11-20 18:35:39 -06:00
Cody Vogt 887e9361dc Merge remote-tracking branch 'upstream/main' into fix/block-record-annotative
# Conflicts:
#	crates/io/src/dxf_raw.rs
#	crates/io/src/dxf_read/tables.rs
2026-11-20 18:34:55 -06:00
Cody Vogt dd048358b6 Merge remote-tracking branch 'upstream/main' into feat/block-attribute-editing
# Conflicts:
#	crates/engine/tests/it/attedit_prompts.rs
#	crates/ui-egui/src/dialogs.rs
#	crates/ui-egui/src/i18n/uk.tsv
#	crates/ui-egui/src/menus.rs
2026-11-20 18:06:09 -06:00
Francesco BV 27e408d91b REFEDIT/REFCLOSE on xrefs: per-drawing baseline, safer save checks
From the second automated review of #2355:

- The "loaded" stamp was one per file for the whole process, taken from
  the path after the bytes were read. Each xref block now keeps its own
  baseline (Block::xref_stamp, session state), taken from the opened
  file before and after the read (None when it changed meanwhile), and
  another drawing loading the file no longer moves it. REFEDIT uses the
  stamp of the one read its handles and version come from, and refuses
  unless that is the drawing's baseline; an unknown stamp counts as
  changed. The process-wide LOADED cache is gone.
- REFCLOSE Save checks the stamp before reading, of the read itself,
  and once more just before the file is replaced (narrowing, not
  closing, the window for another program's save).
- It refuses while the xref's file is open in another drawing tab (it
  was checked only when the edit began).
- It refuses a file the xref could no longer load (more than
  MAX_XREF_OBJECTS, counted as import counts: load::object_count).
- bring_symbols counts distinct symbols only, and refuses the save past
  the budget instead of writing with symbols missing; it copies host
  multileader styles (with their text style) and table styles (with
  their cell styles' text styles) too.
- refedit.levels no longer offers a nested reference REFEDIT would
  refuse (scaled differently in X and Y, flat), nor what is below it.
- Faded copies keep the object's own transparency; the renderer fades
  them by the current XFADECTL, so changing it during the edit shows.
2026-11-20 10:11:24 +01:00
Francesco BV 195c052931 REFEDIT xref tests: folders cleaned up on every exit; a host-only layer
Each test's folder is now an owned guard removed on drop, so a skipped
symlink test or a failed assertion no longer leaves its files behind.

The save test drew its new line after a `layer` call that does nothing
in JSON (`.ok()` hid it), so the line stayed on layer 0 and the check
that host layers come along could not fail. It makes "Added" current
first (layer.new) and asserts the line and the file's layer table.

Review of #2355 (CodeRabbit, tests/it/refedit_xref.rs:30 and :117).
2026-11-20 09:56:07 +01:00
Francesco BV 7d1d0ba55b render: the REFEDIT fade looks the working set up once per display list
entity_parts asked RefEdit::is_working, a scan of the working set, for
every object drawn, and read XFADECTL from the header each time: 50,000
working objects meant about a billion handle comparisons per rebuild.
The working set is now a hash set built with XFADECTL once per display
list (render::Fade) and shared by the serial, parallel and viewport
builders.

Review of #2355 (CodeRabbit, render/src/draw.rs:50).
2026-11-20 09:55:38 +01:00
Francesco BV 8920c0fb6f i18n: Chinese label for Reference Nesting Levels
main now requires every command label in zh.tsv (#1129); refedit.levels
came in with this branch.
2026-11-20 09:14:55 +01:00
Francesco BV 68fbe896a7 render: XFADECTL fade in its own function
After the merge with main, entity_parts went past clippy's cognitive
complexity limit (32/30) with the REFEDIT fade in it.
2026-11-20 08:36:48 +01:00
Francesco BV f9756d5083 rustfmt the REFCLOSE write-back and its tests 2026-11-20 08:32:24 +01:00
Francesco BV 7a199cc2e1 REFCLOSE: say what the xref's file couldn't keep
SAVE and SAVEAS list what the writer drops; the write-back wrote the
source drawing straight through and said nothing, so a DWG xref holding
types the DWG writer can't keep (or a 2013+ DXF one holding solids with
SAT-text geometry) lost them silently.

REFCLOSE now counts them as SAVE does, for the version the file is
written in (file::loss_writing: not_saved_as for DWG, sat_text_dropped
for 2013+ DXF), echoes the same warning prefixed with the file and
naming the backup that still has them, and lists them in the result's
notSaved. Nothing lost, no warning.

Review of #2355, point 3.
2026-11-20 08:29:25 +01:00
Francesco BV 88ef222cdf REFEDIT xref tests: follow main's io and Insert after the merge
cadcraft_io::read and write take a path now, and Insert has a clip.
2026-11-20 08:29:18 +01:00
Francesco BV 64e0b5c2a4 REFCLOSE: write an xref back in the version it was read in
The write-back used IoHooks::write, which picks the version from the
drawing: an R2000 DWG xref came back as a 2004 DWG (a DWG is written at
2004 or later by default) and an R12 DXF one as R2000. An xref is often
someone else's file, and a version change can lock its author out.

REFEDIT now records the file's version (a DWG's from its first bytes, a
DXF's $ACADVER) and whether it is a binary DXF, and REFCLOSE writes it
back through the write_as hook at that version and form. A version
CADCraft doesn't write (R12) is refused before the edit begins, so no
work is lost; so is a build without the write_as hook. REFEDIT's result
names the version.

Review of #2355, point 2.
2026-11-20 08:22:23 +01:00
Francesco BV b27cc3ce22 REFCLOSE: write an xref back the way SAVE writes a drawing
The write-back made its own temporary file (`<file>.cadcraft-tmp`, opened
with a plain truncating write) and copied the backup with fs::copy, so a
symbolic link planted at either path took the write: the drawing went
into the link's target and the xref's path became that link (CWE-59).

It now goes through what SAVE uses: the backup is file::backup (written
atomically, a link at the .bak replaced, never written through) and the
new file atomic_write::write_atomic_with (an exclusively created
temporary file renamed over the file). The file written is the one the
xref's path led to when the edit began; REFCLOSE refuses when the path
leads elsewhere by then (a link put there during the edit).

The backup is named by file::backup_path, as SAVE names it: site.dwg's
is site.bak, site.dxf's site.dxf.bak, so two xrefs of one name in one
folder no longer share (and overwrite) one site.bak.

Review of #2355, points 1 and 4.
2026-11-20 08:20:51 +01:00
Francesco BV b355f1e14a Merge origin/main into pr/xref-edit-in-place
Conflicts: the doc re-export (Raster next to XrefSource), the system
variable table (XCLIPFRAME next to XFADECTL), the canvas paint calls
(painter is a reference now), the Italian and Ukrainian labels (both
sides kept), and docs/gaps.md and docs/target-app-parity.md, taken from
main: pull requests don't edit those docs any more (AGENTS.md), so the
rows this change affects are named in the PR instead.
2026-11-20 08:16:53 +01:00
HolyZephyros 573823767c i18n(tr): complete Turkish UI catalog 2026-11-19 16:16:01 +03:00
vantruong-dang 485892d8d1 perf(gpu): stabilize deep-zoom vertex origin with power-of-two grid and hysteresis 2026-11-19 16:20:25 +07:00
Cody VogtandClaude Opus 5.5 bc0363df59 fmt: dxf_anno's craft_dxf import in order
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 08:39:56 -06:00
Cody VogtandClaude Opus 5.5 24312f63cf fmt: dxf_anno's craft_dxf import in order
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 08:39:49 -06:00
Cody VogtandClaude Opus 5.5 86898c0e1a io: dxf_anno uses craft_dxf, as main's DXF crate now is
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:07:07 -06:00
Cody VogtandClaude Opus 5.5 d12e08b1c9 io: dxf_anno uses craft_dxf, as main's DXF crate now is
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:07:05 -06:00
Cody VogtandClaude Opus 5.5 7904be03d3 Merge fix/annotative-text-contexts (#1362, with current main) into fix/annotative-mleader-contexts
crates/dwg is gone from main; this PR's bridge part (multileader contexts) is
ported to storytold/craft-libs#2005, and its DWG round-trip test is ignored
until the pinned craft-dwg has it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:02:26 -06:00
Cody VogtandClaude Opus 5.5 ed24154ffb Merge fix/block-record-annotative (#1244, with current main) into fix/annotative-text-contexts
crates/dwg is gone from main; this PR's bridge part (text and dimension
contexts) is ported to storytold/craft-libs#2005, and its DWG round-trip test
is ignored until the pinned craft-dwg has it (now through craft_dwg).
io/lib.rs keeps main's dxf_clip and this PR's dxf_anno.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:01:40 -06:00
Cody VogtandClaude Opus 5.5 4a9dd1a71b Merge storytold/cadcraft main into fix/block-record-annotative
- crates/dwg is gone from main (the bridge is craft-dwg in storytold/craft-libs
  now); this PR's bridge part is ported there as storytold/craft-libs#2005.
  Its DWG round-trip test is ignored until the pinned craft-dwg has it.
- dxf_raw.rs finish(): main's hard-owner liveness (`own`, `owner_of`,
  `settle`) walks the kept objects and the refreshed contexts' added records;
  the contexts get their owner chains from `own`.
- retained_objects: main's pass structure, with this PR's modelled_xdict_key.
- foreign.rs: main's `version` and this PR's `placements` both stay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:57:42 -06:00
vantruong-dang 5f3fbd636d fix(engine): frame layout extents on initial tab switch (#3219) 2026-11-16 21:55:16 +07:00
V1dalTheAbidal fa44f8541a A dimension is not picked on block text the viewport does not draw (#3126)
A dimension is hit anywhere inside the box of its text. That box was read
from the dimension's block without the viewport, so through an MSPACE
viewport a pick in the box of text on a layer frozen in that viewport
still took the dimension, although the viewport does not draw the text.
AutoCAD 2022 picks nothing there.

- doc: ViewportBounds::leaves_out tells whether a viewport leaves a part
  of a block out for its layer, by the comparison its boxes already use.
- engine: the text test of a pick and of selection cycling's list skips
  the text the viewport leaves out.

Not changed: the rectangle around a dimension is still hit along its
sides (#2991). With the text not drawn its top side runs through the box
of the text, so a pick within pick distance of that side and a crossing
window over it still take the dimension, where AutoCAD takes nothing.

Nothing changes where no layer is frozen in the active viewport: text on
a layer frozen for the whole drawing or turned off is tested as before.
2026-11-16 14:27:32 +02:00
V1dalTheAbidal f3a9ecdce9 Selection through a viewport leaves out block parts on its frozen layers (#3126)
Through an MSPACE viewport a block reference on a layer the viewport draws
was hit on a part whose layer is frozen in that viewport, and that part
took room in the box a window tests. The viewport does not draw the part.

- doc: ViewportBounds measures an entity as one layout viewport draws it,
  without the block contents on the viewport's frozen layers.
- render: build_entities_in_viewport builds loose entities as a viewport
  that freezes the given layers draws them.
- engine: a pick, selection cycling's list, a window, a crossing window, a
  fence and the polygons test a reference against that box and that
  geometry. The spatial index is unchanged: the viewport's box is never
  larger than the indexed one.
- ui: the highlight of a reference inside the active viewport is built
  the same way.

A clipped reference (XCLIP) stays selected by its boundary whatever the
viewport draws inside it, as AutoCAD 2022 selects it: it keeps the box
the drawing gives it.

Nothing changes where no layer is frozen in the active viewport.
2026-11-16 11:14:42 +02:00
jayzed80 a957675512 DXF: mirror a mirrored HATCH's pattern lines with its boundary (#3120)
A HATCH with extrusion (0,0,-1) had its boundary and hatch angle mirrored
into the world, but the pattern definition lines read from the file kept
their OCS direction, base point and offset. Lines at an angle other than the
hatch's were drawn on the wrong slant (ANSI31 at 45 instead of 135) and
multi-line patterns lost their alignment. Mirror each line the same way.
2026-11-15 10:12:49 +00:00
FredApps 54d1be50ba Release: CADCraft v0.21.0 (main 8e69890223) 2026-11-14 21:44:55 +01:00
FredApps 1ba86d461b Release: CADCraft v0.21.0 2026-11-14 21:44:50 +01:00
Dylan M. Taylor 7526dc62c1 Merge tested main for Flatpak update patch release 2026-11-11 15:25:57 -05:00
Dylan M. Taylor 161af2a8da Release 0.20.1: repair Flatpak update checks and self-updates (#3078)
* Release 0.20.1: fix Flatpak update permissions

* test: avoid unchecked option parsing in Flatpak regression
2026-11-11 14:27:14 -05:00
FredApps 28241abb8f Merge main into release for CADCraft v0.20.0 2026-11-11 16:38:54 +01:00
cdwilson127 21c984ed5c INSERT of a drawing file whose block exists no longer asks to redefine it when EXPERT is 2 or more (fixes #2995)
EXPERT 2 or more answers the "already exists. Redefine it?" question
Yes without asking, so a routine that inserts the same file repeatedly
finishes each INSERT. EXPERT below 2 still asks.
2026-11-11 12:22:46 +13:00
FredAppsand.CooCoo 51f5bbcc21 Fonts: the MTEXT strip test expects a short \U+ escape to keep its digits (#2954) (#3024)
strips_formatting expected `\U+12` to strip to nothing. plain_mtext
dropped every unknown code up to the next `;` when that assertion was
written. #1036 limits this to the codes in takes_arg, and `\U` is not
one of them, so plain_mtext returns `+12`. The layout and paragraph
paths give the same text, and
unicode_escapes_are_decoded_in_every_parser already expects it.

The test has failed on main since both changes merged, and the failure
stops the gate at its test step. The test module now also checks the
short escape in both layout paths.

(cherry picked from commit 6f0f1fefa8)

Co-authored-by: .CooCoo <RobertLeeLW@gmail.com>
2026-11-10 19:49:24 +01:00
Dylan M. Taylor 227e3c385b Release 0.19.0 2026-11-09 06:29:44 -05:00
Cody VogtandClaude Sonnet 5.5 89ec9b2d45 Merge main into feat/block-attribute-editing
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 00:26:44 -06:00
Cody VogtandClaude Sonnet 5.5 05eb57bd63 Merge the stack below into an3
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 23:28:33 -06:00
Cody VogtandClaude Sonnet 5.5 7d1a7e4fc8 Annotative text contexts test: Dimension gains insertion_point on main
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 23:28:33 -06:00
Cody VogtandClaude Sonnet 5.5 3f82e57ff0 Merge main (via the stack below) into fix/annotative-mleader-contexts
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 23:01:57 -06:00
Cody VogtandClaude Sonnet 5.5 af425df2c8 Merge main (via the stack below) into fix/annotative-text-contexts
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 23:01:56 -06:00
Cody VogtandClaude Sonnet 5.5 5635f12cbe Merge main into fix/block-record-annotative
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 23:01:18 -06:00
Cody VogtandClaude Sonnet 5.5 a174177b4b Enhanced Attribute Editor: pending edits stay with their drawing and attribute layout
The Properties attribute field's edit buffer is now keyed by the drawing's uid as well as the
handle and place, so text typed in one drawing is not committed in another drawing's reference
that has the same handle.

Apply in the dialog checks that the reference still has the attributes (tag and value, in the
same places) the dialog listed. If another command or an undo changed them, nothing is written:
the rows are reloaded and the dialog says so, instead of the typed value landing on whichever
attribute now has that place.

Regression tests: a_stale_dialog_does_not_overwrite_another_attribute,
a_pending_properties_value_does_not_follow_a_drawing_switch.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 10:03:55 -06:00
Cody VogtandClaude Sonnet 5.5 aaadba7b11 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-02 09:42:02 -06:00
Cody VogtandClaude Opus 5.5 37cd9089d3 Enhanced Attribute Editor: edits go by attribute place, so a repeated tag changes one row
attedit takes `at: {index: value}` beside `values`: one attribute by its place in
the reference (indexes checked against its attributes). The Edit Attributes
dialog and the Properties palette send their edits that way, so on a reference
with two attributes sharing a tag (a DXF may carry them) editing one row no
longer overwrites the other. `values` still changes every attribute with the tag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 09:42:02 -06:00
Cody VogtandClaude Opus 5.5 312a339cb1 Enhanced Attribute Editor: egui ids without the APIs this egui deprecates
Id::unique for the window, Ui::scope_id for the palette's value fields, as the
rest of the UI does since main's egui update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 09:42:02 -06:00
Cody VogtandClaude Opus 5.5 5134098c57 Enhanced Attribute Editor: open it on a reference with one attribute current
attedit::open(app, handle, current) opens the dialog on a block reference
of the active drawing with the given attribute (an index in
cadcraft_engine::attributes order) current: its tag is bold, and its value
box takes the focus and scrolls into view in the first frame. Without one,
or for one that can't be changed, the first editable attribute is current.
It returns false, and opens nothing, for anything but a block reference
with an attribute that can be changed. ATTEDIT/EATTEDIT from a menu go
through it, and Apply keeps the current attribute.

This is what a double-click on an attribute needs (#1790).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 09:42:02 -06:00
Cody VogtandClaude Opus 5.5 9f518ba001 Enhanced Attribute Editor: tied to the drawing it was opened for
The dialog kept only the reference's handle, and handles repeat across
drawings: with another drawing's tab chosen, it stayed open and Apply
or OK changed that drawing's reference with the same handle. It now
records the drawing (DocState::uid), closes when another is active, and
Apply does nothing there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 09:42:02 -06:00
Cody VogtandClaude Opus 5.5 f0ab3e94e5 Block attributes: Enhanced Attribute Editor, an Attributes group in Properties, REFEDIT on dynamic blocks
- Edit Attributes (ATTEDIT/EATTEDIT typed or from a menu) with one block reference selected
  opens the Enhanced Attribute Editor: tag, prompt and value of each attribute; Apply and OK run
  `attedit {handle, values}` with the values changed, one undo step each. With nothing selected
  ATTEDIT asks at the command line as before, and now takes a selected reference at once.
- The Properties palette lists a block reference's attributes in an Attributes group; values
  can be edited there (multiline values with line breaks and constant attributes read-only).
- `attedit` JSON: refuses objects that aren't block references, references on locked layers and
  values over 64 KiB; leaves constant attributes alone and reports them as `constantTags`.
- `cadcraft_engine::attributes` gives the rows the palette and dialog show (prompt from the
  attribute definition when the attribute has none).
- REFEDIT on a dynamic block reference names the dynamic block and points to BEDIT or Edit
  Attributes, instead of "*U1 is generated geometry".
- Shortcut menu: Edit Attributes only when some attribute can be changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 09:42:02 -06:00
Cody VogtandClaude Sonnet 5.5 9ce077cf51 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:22 -06:00
Cody VogtandClaude Sonnet 5.5 555703f029 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:18 -06:00
Cody VogtandClaude Opus 5.5 b2335c7f27 DWG: a multileader context's body closes (301 }) before the next record
As acadrust writes it; its reader stops at the next record either way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:47:36 -06:00
Cody VogtandClaude Opus 5.5 3c4c5d4330 DXF: AutoCAD's CANNOSCALE names the scale the contexts are written at
A CANNOSCALE naming none of the drawing's scales wrote that name to the
variable dictionary while the default contexts were written at 1:1; the
variable now names the resolved scale too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:47:36 -06:00
Cody VogtandClaude Opus 5.5 1418607e06 DXF test: an annotative multileader has no *D block
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:47:36 -06:00
Cody VogtandClaude Opus 5.5 e89ff0832d DXF: the current annotation scale is AutoCAD's CANNOSCALE variable
AutoCAD keeps the current annotation scale in the named object dictionary's
AcDbVariableDictionary, as a DICTIONARYVAR CANNOSCALE naming the scale.
CADCraft read only its own record, so AutoCAD's drawings opened at 1:1
whatever their scale (annotative objects then showed at their first scale),
and the variable was written back as read, so AutoCAD reopened a drawing at
its old scale after CADCraft changed it.

The variable is read when the scale is in the list (after CADCraft's record:
AutoCAD keeps that record as it was, so the variable is the newer one), and
the kept variable is written with the drawing's current scale. Annotative
objects are written at that scale.

Checked in CADCraft and AutoCAD: an AutoCAD drawing at 1:2 opens at 1:2;
switched to 1:10 and saved as DXF and DWG, AutoCAD opens both at 1:10.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:47:36 -06:00
Cody VogtandClaude Opus 5.5 0f094da0ae DXF/DWG: annotative multileaders keep their annotation scales on save
An annotative multileader's scale context (ACDB_MLEADEROBJECTCONTEXTDATA_CLASS)
holds the multileader's whole CONTEXT_DATA body at that scale: overall scale
(40), text height, arrowhead size, landing gap, content position and the
leaders. CADCraft dropped AutoCAD's on read and wrote none, so annotative
multileaders came back plain at the default scale's size, and AutoCAD showed
CADCraft's at one size at every scale.

Multileaders now go through the annotation scale contexts like text, MText
and dimensions: written at the default scale with AcadAnnotative xdata and a
context per scale (the entity writer's CONTEXT_DATA at that scale, with its
overall scale and landing gap set), read back at paper size. The DWG bridge
gives acadrust the CONTEXT_DATA{ group it reads the context after, and takes
acadrust's braces and marker out again.

Checked in AutoCAD: its own annotative multileader reads back at 1:2 and
1:10 at paper size, and the saved file reopens with text 0.18 / 0.9 as
before; one made in CADCraft opens with text 2.5 / 25 at 1:1 / 1:10, the text
moved with the scale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:47:36 -06:00
Cody VogtandClaude Opus 5.5 3099c82881 DXF: only annotative dimensions get a *D block per scale
Annotative text and MText went through the dimension block planning too and
left one empty anonymous *D block per scale in every saved file. The hostile
contexts test now saves, opens the file again and checks the scales and that
every context names a written SCALE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:47:35 -06:00
Cody VogtandClaude Opus 5.5 0b04db61e3 DXF test: a justified text's start point is recomputed on save (since #1062)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:47:34 -06:00
Cody VogtandClaude Opus 5.5 97b9e2a765 DXF/DWG: annotative text, MText and dimensions keep their annotation scales on save
AutoCAD keeps an annotative object's size at each annotation scale it
supports in scale contexts (extension dictionary AcDbContextDataManager,
ACDB_ANNOTATIONSCALES, one *OBJECTCONTEXTDATA_CLASS per scale), with the
object's own groups at its default scale. CADCraft dropped AutoCAD's contexts
on read, so those objects opened as plain text at the default scale's size
and lost their scales on save; its own annotative objects went out with only
CADCraft's private record, so AutoCAD showed them at one size at every scale.

Text, MText and dimensions in model space and layouts are now written at
their default scale (the current one when supported) with AcadAnnotative
xdata and a context per scale: text insertion and alignment points, MText
width and columns, a dimension's text position and a *D block with its
geometry at that scale (sharing the DIMASSOC's extension dictionary when
there is one). Scales missing from the list are added. Reading takes the
scales from the contexts and the sizes back to paper size. Files before the
2007 format keep CADCraft's record as before. The DWG bridge gives acadrust
text contexts its way (marker, radians) and dimension contexts' blocks as
BLOCK_RECORD handles, and turns them back.

Checked in AutoCAD: it opens the output, keeps both contexts of each
object, and draws the dimension at 0.18 / 9.0 text height at 1:1 / 1:50.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:47:34 -06:00
Cody VogtandClaude Sonnet 5.5 0a6d97969b DXF: the kept-context code in read and finish moves into helpers
main now denies cognitive_complexity over 30 and too_many_arguments over 7.
This PR's additions took read to 32 and finish to 31, and retained_objects
to 8 arguments: the block-reference and attribute bookkeeping now lives in
insert_handles, of_insert, keep_attrib_dictionaries, keep_placements,
written_attribs and refreshed_contexts, and retained_objects takes the root
and its entries as one pair.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-31 16:47:24 -06:00
Cody VogtandClaude Opus 5.5 75d135c9e2 DXF: an attribute as read is found by its tag and place, and keeps its rotation
A kept attribute placement was looked up by its index among the reference's
attributes now, which differs once they are reordered or replaced (ATTSYNC).
It is now found by tag and place among that tag, like the attribute's contexts.
The rotation change is measured from the attribute as read too, not from its
default context, so an unchanged save no longer turns every context when the
ATTRIB (at the current scale) and the default context differ.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:32:38 -06:00
Cody VogtandClaude Opus 5.5 345b5bc7d6 DXF: new reference contexts take handles above every handle in use
Upstream now believes handles above 2^48 (AutoCAD writes them), so new
annotation contexts can no longer take stand-in handles from 2^48 up: they
start above the written handles, $HANDSEED, the kept objects and their targets.

Test: a drawing whose reference sits at 2^48 + 1 gains a scale and every
written handle stays unique (red with the old 2^48 base).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:32:38 -06:00
Cody VogtandClaude Opus 5.5 37bf128ffd DXF: kept reference contexts follow the reference as read; one default rule
A kept context is brought up to date by what its block reference did since
the file was read. That baseline was the default context, which needn't be
where the reference was (an unchanged save then moved every context); the
reference and its attributes as read are now kept (`Foreign::placements`)
and used, the default context only for data without them.

A context's own offset from the reference now scales and mirrors with it
(back into the reference's frame then, scaled, turned to its frame now), not
only turns.

The default context is the one whose first 290 group is 1 everywhere (an
attribute context has a later 290 of its own).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:32:38 -06:00
Cody VogtandClaude Opus 5.5 97e225f324 DXF: new reference contexts come from one whose scale is still written
When the default context's scale had been deleted from the drawing's list,
a reference CADCraft keeps annotative got no new contexts for its added
scales; the template is now its default context, else its first, among
those whose SCALE is written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:32:38 -06:00
Cody VogtandClaude Opus 5.5 8a0ca4da37 DXF: kept reference contexts follow the drawing's and the reference's scales
A kept block reference or attribute context whose SCALE is no longer in the
drawing's list is not written (its dictionary entry goes with it), so no
context points at a null scale. A reference CADCraft's model keeps annotative
has a context for exactly the scales it supports: contexts of scales it
dropped go, and one per new scale is made from the default context, scaled
by the ratio of the scales about the reference's insertion point. One
context stays the default.

Attributes are identified by reference, tag and their place among the
reference's attributes with that tag, so two attributes with one tag keep
their own extension dictionaries and contexts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:32:38 -06:00
Cody VogtandClaude Opus 5.5 6aa64a13c9 DWG: block reference annotation contexts keep their rotation, insertion and scales
AutoCAD's DXF has a block reference context's rotation (50, degrees),
insertion point and scales straight after its scale (340). acadrust 0.6.4
reads them after an AcDbBlkRefObjectContextData marker, with the rotation in
radians, and without the marker read zeros: a drawing saved as DWG had every
annotative reference at scale 0 at its other annotation scales, where
AutoCAD then drew nothing. The DWG bridge now gives acadrust the contexts its
way (marker, radians) and turns its DXF back into AutoCAD's (no marker,
degrees).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:32:38 -06:00
Cody VogtandClaude Opus 5.5 f344a13e63 DXF: a block reference's attributes keep their annotation scale contexts
The attributes of an annotative reference hold their own contexts (insertion
and alignment points and rotation at each annotation scale, under the ATTRIB's
extension dictionary), dropped like the reference's were. CADCraft writes
attributes with new handles, so their extension dictionaries are now kept by
attribute, as its reference's handle and tag, and put back on the attribute
written with that reference and tag. On writing each context keeps its own
place in the block at its scale, moves by what the attribute did in the block
since (its default context then, the attribute now), and is placed by the
reference's context for that scale as it is now: a reference left alone keeps
them as read; one moved, turned or scaled carries them exactly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:32:38 -06:00
Cody VogtandClaude Opus 5.5 425054a962 Block literals in tests take scale_uniformly; a test helper's lifetime is elided
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:32:38 -06:00
Cody VogtandClaude Opus 5.5 2a268501b4 DXF: a block reference keeps its annotation scale contexts, following the reference
A reference to an annotative block holds its scale at each annotation scale in
its extension dictionary (AcDbContextDataManager, ACDB_ANNOTATIONSCALES).
CADCraft dropped it with the other annotation contexts it means to write from
its model, but it models none for references: with the block's annotative
flag kept, AutoCAD then scaled the reference once more by the current
annotation scale (5 became 25). A reference's contexts are now kept, and
refreshed on writing: each moves, turns and scales by what the reference did
since the file was read (its default context was the reference then), so a
reference left alone keeps them as read. The scales they name are found by
name (SCALE group 300), as the scale list is written again from the model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:32:37 -06:00
Cody VogtandClaude Opus 5.5 2827d420b1 DXF: a block record keeps its annotative flag and uniform scaling
A BLOCK_RECORD's AcadAnnotative xdata (references to the block are
annotative) was dropped on reading, AcadAnnotative being among the
applications CADCraft writes itself, and never written: a saved drawing's
annotative blocks came back plain, and AutoCAD then scaled their references
by units instead of the annotation scale (a metre block showed Unit factor
1000 and Scale 0.005). Group 281 (scale uniformly) was dropped too. Both are
now read into the block (`Block::annotative`, `Block::scale_uniformly`) and
written back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 11:32:37 -06:00
Francesco BVandClaude Opus 5.5 ad6314967f blocks: REFEDIT edits xrefs in place and writes their drawing back
REFEDIT on an xref (or a block that came with one) edits it in place, and
REFCLOSE Save writes the change into the source drawing (the old file
kept as .bak, symbol prefixes removed, host symbols copied, handles kept)
and reloads the xref. Refused for read-only files, files locked by
another program or open in another tab, and files changed since they
were loaded or during the edit. Nested references are picked through
their parents (path, nested, refedit.levels, "Select nesting level
[OK/Next]"). Everything outside the working set is drawn faded
(XFADECTL), and an Edit Reference bar offers Add to/Remove from Working
Set and Save/Discard Changes. Gap F2.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-27 19:58:37 +01:00
276 changed files with 23015 additions and 2980 deletions
+1 -1
View File
@@ -86,7 +86,7 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/ko.tsv` | @huk082 (AI-assisted) | Original Korean translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; no font assets added |
| `crates/ui-egui/src/i18n/ar.tsv` | @hasan-sdaif | Original Arabic translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted) | Original Turkish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app reviewed by a native speaker |
| `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted); 870 later rows: @HolyZephyros (AI-assisted) | Original Turkish translations of CADCraft English strings (original catalog by @ogzhnklvz; 870 later rows written from CADCraft's English strings in #3291) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app for the original catalog was reviewed by a native speaker; the 870 rows added in #3291 have not yet been reviewed by a native speaker |
| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted); 46 later rows: @V1dalTheAbidal with Claude Code (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the 46 later rows were read by their contributor, a native Greek speaker; independent native proofreading of the whole file pending |
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the craft-i18n#401 phase 1 changes reviewed by a native Vietnamese speaker; older rows not yet proofread in full |
| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) |
Generated
+6 -6
View File
@@ -378,9 +378,9 @@ dependencies = [
[[package]]
name = "async-executor"
version = "1.14.0"
version = "1.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
dependencies = [
"async-task",
"concurrent-queue",
@@ -2733,9 +2733,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
dependencies = [
"percent-encoding",
]
@@ -6609,9 +6609,9 @@ dependencies = [
[[package]]
name = "url"
version = "2.5.8"
version = "2.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
dependencies = [
"form_urlencoded",
"idna",
+4 -4
View File
@@ -94,9 +94,9 @@
untested, 2018 tested only on synthetic files) open through the open-source acadrust library
and save as 2000 through 2018. New drawings default to
2018 (AC1032) in both formats. In the app's Save dialog, File ▸ Default Save Format
(also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version for untitled
drawings; drawings with a file keep their own version, subject to supported-version mapping
and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later
(also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version Save As and
Export write, for opened drawings too; Save (QSAVE) of an opened file keeps its own version,
subject to supported-version mapping and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later
saves. Export to SVG and PNG today.
- **Fast and native.** Pure Rust and egui, no Electron, no web view. One binary on macOS
(universal), Windows, Linux and FreeBSD, plus a WebAssembly build for the browser.
@@ -120,7 +120,7 @@ numbers):
| Layers & properties | Layers palette and Layer Properties Manager (on/off, freeze, lock, plot, colour, linetype), layer tools (isolate, freeze, off, lock, match, previous), Properties palette with per-object editing, linetypes, lineweights, colour index and true colour |
| Annotation | All DIM* commands with full DIMSTYLE variables, overrides and every arrowhead, associative dimensions that follow geometry, MLEADER, TABLE, TrueType fonts (`.ttf`, `.otf`, `.ttc` collections), MTEXT formatting codes (fonts, heights, colours, stacked fractions), our own single-stroke drafting font |
| Hatch & blocks | Pick-point hatch boundaries with islands, pattern, solid and gradient fills from our own pattern library, BLOCK/INSERT, attributes and nested blocks |
| Files | DXF read (R12–2018, binary from R13) and write (2000–2018, ASCII and binary), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library; R13 and R14 untested, 2018 tested only on synthetic files) and write (2000–2018). New drawings save as 2018 (AC1032); opened drawings keep their supported version, except DWG defaults to at least 2004. In the app's Save dialog, File ▸ Default Save Format (also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version for untitled drawings; drawings with a file keep their own version, subject to supported-version mapping and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later saves. DXF uses R2000 structure with the chosen `$ACADVER`. PDF plotting, SVG and PNG export. Entities CADCraft doesn't model yet are not kept on save: see [file-format parity](docs/file-format-parity.md) for version selection and fidelity |
| Files | DXF read (R12–2018, binary from R13) and write (2000–2018, ASCII and binary), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library; R13 and R14 untested, 2018 tested only on synthetic files) and write (2000–2018). New drawings save as 2018 (AC1032); opened drawings keep their supported version, except DWG defaults to at least 2004. In the app's Save dialog, File ▸ Default Save Format (also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version Save As and Export write, for opened drawings too; Save (QSAVE) of an opened file keeps its own version, subject to supported-version mapping and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later saves. DXF uses R2000 structure with the chosen `$ACADVER`. PDF plotting, SVG and PNG export. Entities CADCraft doesn't model yet are not kept on save: see [file-format parity](docs/file-format-parity.md) for version selection and fidelity |
| Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF |
| Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit |
| Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror |
+17 -12
View File
@@ -2,7 +2,7 @@
**Stage: pre-alpha** · next: alpha, when the six rows of the [alpha gate](docs/roadmap.md#alpha-gate) pass (five fail today; the gate was revised on 2026-11-19 and its hours are not re-estimated yet)
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-25 · **Change:** minor (Upcoming updated for what merged from 2026-11-21 to 2026-11-25; previously minor: Upcoming updated for what merged on 2026-11-19 and 2026-11-20; previously major: alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-12-01 · **Change:** minor (Upcoming updated for what merged from 2026-11-25 to 2026-12-01; previously minor: Upcoming updated for what merged from 2026-11-21 to 2026-11-25; previously minor: Upcoming updated for what merged on 2026-11-19 and 2026-11-20; previously major: alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
CADCraft targets full parity with AutoCAD (2D drafting first, then annotation, layouts and
plotting, DWG, parametrics and 3D), plus what AutoCAD doesn't have: agent control over MCP, a
@@ -84,8 +84,8 @@ Hours are Opus 5.5 agent wall-clock hours, calibrated on this repo's own build:
## Languages
AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus eighteen catalogs
(Ukrainian, Brazilian Portuguese, German, Spanish, Czech, Russian, French, Simplified Chinese, Italian, Korean, Swedish, Arabic, Greek, Hungarian, Turkish, Bosnian, Georgian and Vietnamese). Detail: [localization-parity.md](docs/localization-parity.md).
AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus twenty catalogs
(Ukrainian, Brazilian Portuguese, German, Spanish, Czech, Russian, French, Simplified Chinese, Italian, Korean, Swedish, Arabic, Greek, Hungarian, Turkish, Bosnian, Georgian, Vietnamese, Polish and Tamil; Tamil needs an installed Tamil font or a build with the craft-fonts face, and without one the interface stays in English). Detail: [localization-parity.md](docs/localization-parity.md).
| Language | Status | UI translated |
|---|---|---:|
@@ -103,7 +103,7 @@ AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus ei
| Korean | partial | 1,235 catalog rows |
| Vietnamese | partial | 1,460 catalog rows (2026-11-07); native review pending |
Other languages shipped: Ukrainian (1,357 rows, the reference catalog, #36), Czech (1,215), Russian (1,005), Italian (1,352), Swedish (1,382), Hungarian (1,326) and Turkish (1,330), counted 2026-10-24; engine messages stay English. Every catalog but Ukrainian's has strings added since it landed that still fall back to English: 6 (Italian, Swedish) to 296 (French) per `cargo xtask i18n` ([localization-parity.md](docs/localization-parity.md)).
Other languages shipped: Ukrainian (1,357 rows, the reference catalog, #36), Czech (1,215), Russian (1,005), Italian (1,352), Swedish (1,382), Hungarian (1,326) and Turkish (1,330), counted 2026-10-24; engine messages stay English. Since those counts Polish (#218) and Tamil (#3105) landed and the Russian (#3378), Czech (#1579) and Vietnamese (#3500) catalogs were brought up to date; the counts here are not redone. Every catalog but Ukrainian's has strings added since it landed that still fall back to English: 6 (Italian, Swedish) to 296 (French) per `cargo xtask i18n` ([localization-parity.md](docs/localization-parity.md)).
## Upcoming
@@ -112,16 +112,18 @@ already written and waiting in a pull request lands before new work starts, whoe
and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
**1. Urgent: security fixes, leaks, crashes and lost work.**
- The open findings of the security audit (#1919–#1935): check each against the input limits that
- The open findings of the security audit (#1922, #1925, #1931, #1932 and #1935 of #1919–#1935; the others are closed): check each against the input limits that
landed on 2026-11-11, close what is fixed and fix the rest. A crafted handle that makes new entities
overwrite existing ones (#1921) is fixed by #1276.
- A saved file that crashes AutoCAD 2021 (#3303); dimension text lost on save (#3299) was fixed on 2026-11-20.
- Crashes and hangs with a reproduction: the web build on a large DXF (#1603), a DWG with 3D content
(#2174), startup on older graphics hardware (#1724, #1631, #3222).
- Crashes and hangs with a reproduction: the web build on a large DXF (#1603; bounded by #3594 and
#3622, still open), a DWG with 3D content (#2174), startup on older graphics hardware (#1724, #1631,
#3222).
**2. Parity with AutoCAD: the alpha gate rows, then the beta checklist (apart from its items named under tier 3).**
- It starts on common hardware: an automatic fallback renderer (`CADCRAFT_STENCIL=0` is the manual
switch since #3336).
- It starts on common hardware: the automatic fallback renderer landed (#3685; `CADCRAFT_STENCIL=0`
is the manual switch since #3336); waiting for the reporters to confirm, and older Intel Macs (#1631,
#2146) are not covered.
- It opens the DWG and DXF files people already have: large files (#3102, #2633, #1088), layouts and
paper units (#1672, #2836), and a corpus of real files run in CI.
- Saving loses nothing and other CAD programs open the result (#2904, #1687, #3234, #2632).
@@ -131,16 +133,18 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
- The prompt options that still say "not available yet" (gaps F1).
- Layouts print at scale on a system printer (#3216); the menu bar and panels can be restored since
#3308.
- 602 pull requests are open (2026-11-25; 661 on 2026-11-20). About 230 were mergeable, passed CI and were small; they are
- 586 pull requests are open (2026-12-01; 602 on 2026-11-25). About 230 were mergeable, passed CI and were small; they are
reviewed and landed in this order, the longest-waiting authors first within a row.
**3. Lower priority: affects fewer people and nothing breaks without it.**
- Dynamic-block authoring, editing an xref in place, exact ellipse and spline geometry, correct
polyline offsets.
- Dynamic-block authoring, the leftovers of editing an xref in place (landed in #3352), exact ellipse
and spline geometry, correct polyline offsets.
- Prompt options that need 3D (DVIEW's camera options, -RENAME Material); 3D itself comes after 1.0,
but a file with 3D content must open safely (tier 1).
- Menu breadth against AutoCAD for Mac as a headline number.
Done from 2026-11-25 to 2026-12-01: REFEDIT, REFSET and REFCLOSE on xrefs, writing the xref's drawing back in the version it was read in (#2355 in #3352; not on the web); an automatic fallback renderer when the graphics can't start (#3685 in #3692; not yet confirmed by the reporters, and older Intel Macs are not covered); TRIM highlights only the part a click removes and EXTEND what it adds, and EXTRIM (#3382, #2808 in #3471; follow-ups #3526 in #3690); SCALE Reference Points and Copy, and grip Scale of text heights (#3288 in #3472); QLEADER at the command line (#2740; its Settings dialog is not available yet); OFFSETGAPTYPE (#1506); FILLET and CHAMFER with two polylines and with middle, closed and arc segments (#1223); prompts and results of COPY, JOIN, PEDIT, RECTANG, STRETCH, PLINE, SPLINE, SPLINEDIT, ARRAY, ARRAYPATH, DIVIDE, INSERT and MINSERT brought closer to AutoCAD's (#2726, #2725, #2906, #2790, #2204, #2209, #2205, #2699, #2703, #2705, #2772, #2778, #2761, #2762, #2774, #2782, #2780, #2784, #2766, #2789); spreadsheet text pasted as a TABLE (#3290 in #3470), with wrapped cell text and Enter to repeat (#3584, #3587 in #3690); GROUPDISPLAYMODE, group copies and draw order across every layout (#2152); New Layout from Area (#2080); drawing locks and WHOHAS, which say when a drawing is open elsewhere (#1018, part of #540); REVCLOUD arcs that other readers recognise as a cloud (#1692); hatches by internal point that keep their arcs (#1474); `\X` dimension text below the line (#1084); JIS and Japanese paper sizes (#1810); a translucent fill in the AREA preview (#1303); selection through a viewport that leaves out block parts on its frozen layers (#3214 in #3692); saves that keep covered cell text, WIPEOUTFRAME, LAYOUT flags, VPORT group 72, attributes on layer 0 and DIMLFAC measurements (#3520, #3611, #3668, #3670, #3613 in #3689; #3540 in #3692), and RENAME that keeps foreign data (#1020); the web build's display list, selection highlight and plot style outlines bounded (#3594, #3622 in #3692; #1603 stays open); hostile-input fixes toward the security audit (#3482, #3491, #3536 for #1923; #3610, #3647 for #1922; #3588 for #1925; #3609 for #1935; #3484, #3539, #3562, #3590 for quadratic-time opens); LISP and script fixes (#3519, #3572, #3576, #3642, #3646, #3651); the move to the shared UI framework, with floating palettes as OS windows and Ctrl+= and Ctrl+- for the interface scale (#3449); the Tamil catalog (#3105 in #3470) and the Russian, Czech and Vietnamese catalogs brought up to date (#3378, #1579, #3500).
Done from 2026-11-21 to 2026-11-25: PDFIMPORT, a PDF page as editable lines, polylines, solid hatches and text (#3375 in #3419); dynamic block references that rotate, flip, array, scale, stretch polar, align and look up, with their grips (#963, #993, #1030, #1098, #1699, #1723, #1752 in #3424; authoring is still open); the proxy graphics of other applications' objects drawn (#2697, #3435, #3437) and dimensions kept as read drawn from their `*D` block (#3439); saves that keep layout plot settings (#3233, #3386, #3390), DXF 2007+ table cell text (#3392), hatch boundary flags (#3389), fit text (#3391) and registered applications (#2918); the Array window for ARRAYRECT and ARRAYPOLAR (#3394); ATTDIA and the Edit Attributes dialog on INSERT (#3411) and constant attribute values drawn (#3462); Edit > Paste from the system clipboard (#3366, #3460, #3461; #3320 open); opening from Finder and quit prompts on macOS (#1347 in #3344, not yet run on a Mac); an already-open drawing selects its tab when opened from the interface (#899 in #3422; the control channel, MCP, scripts and LISP still open a second copy); Tab through every object snap candidate (#1673); the Write Block dialog for WBLOCK (#1778); Generate Boundary (#2804); mitred wide polylines (#3453; the extents leave out the mitre tip, #3443); DIMASSOC 1 (#2977); crossing selection of block references by what they draw (#3445); an option to turn off the update check (#3097).
Done on 2026-11-19 and 2026-11-20: the hostile-input fixes #1276, #2820, #2821 and #2765 (#3304, #3305), clicks while the mouse moves and right-click or Space as Enter (#3307), the interface reset (#3308), paper units (#3309), the UCS command (#3310), -ATTEDIT, -RENAME and -LAYER options (#3311), TRIM/EXTEND depth (#3312), dimension values kept on save (#3335), the stencil switch (#3336), a typed OPEN path (#3343) and double-click text editing (#3345).
@@ -172,6 +176,7 @@ REFEDIT (#818), XCLIP (#2354), dynamic block references (#838–#883), and the D
| Date | Change | Summary |
|---|---|---|
| 2026-12-01 | minor | Upcoming updated for the merges of 2026-11-25 to 2026-12-01 (REFEDIT on xrefs, the automatic fallback renderer, TRIM/EXTEND highlight and EXTRIM, SCALE Reference, QLEADER, OFFSETGAPTYPE, FILLET/CHAMFER with polylines, spreadsheet paste as a TABLE, groups and draw order, New Layout from Area, drawing locks and WHOHAS, what saves keep, web display-list bounds, security-audit fixes, the shared UI framework); languages list now twenty catalogs (Polish, Tamil); pull-request count 602 → 586; percentages and hours not re-scored |
| 2026-11-25 | minor | Upcoming updated for the merges of 2026-11-21 to 2026-11-25 (PDF import, dynamic block reference actions, proxy graphics, what saves keep, Array window, ATTDIA, system clipboard paste, macOS opening from Finder, WBLOCK dialog, Generate Boundary); #3299 fixed; pull-request count 661 → 602; percentages and hours not re-scored |
| 2026-11-20 | minor | Upcoming updated for the merges of 2026-11-19 and 2026-11-20 (security stacks, input, interface reset, paper units, UCS, prompt options, TRIM/EXTEND, text editing in place); pull-request count 714 → 661; percentages and hours not re-scored |
| 2026-11-19 | major | Alpha gate revised from user reports (six rows, Windows first; block authoring, xref editing in place and exact curve geometry moved to beta); Upcoming re-ranked into three tiers: urgent (security, leaks, crashes, lost work), parity, lower priority; percentages and hours not re-scored |
+2
View File
@@ -66,6 +66,8 @@ fn synthetic(n: usize, side: f64) -> Result<cadcraft_engine::doc::Drawing, cadcr
style: "Standard".into(),
halign: d::HAlign::Left,
valign: d::VAlign::Baseline,
backwards: false,
upside_down: false,
}),
};
dr.add(&Space::Model, Common::default(), kind)?;
+43
View File
@@ -0,0 +1,43 @@
//! A LISP routine in a `run` script runs to its end before the script goes on and the drawing is
//! saved, however many slices it takes (#3635).
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A fresh scratch directory that is removed on drop, also when an assertion fails.
struct Scratch(std::path::PathBuf);
impl Scratch {
fn new(tag: &str) -> Self {
let dir = std::env::temp_dir().join(format!("cc-cli-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir(&dir).expect("create scratch dir");
Scratch(dir)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// The loop takes many slices: the circle drawn after it is in the saved drawing, and the next
/// line runs once the routine has ended.
#[test]
fn a_long_routine_in_a_script_draws_before_the_save() {
let scratch = Scratch::new("lisp-script");
let saved = scratch.0.join("out.dxf");
let saved = saved.to_str().unwrap();
let script = r#"(progn (repeat 1000000 (setq x 1)) (command "circle" "0,0" "5") (princ "done"))\n(princ (+ x 1))"#;
let out = cli(&["run", "--metric", "--script", script, "--save", saved]);
let err = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "{:?}: {err}", out.status);
assert!(err.lines().any(|l| l == "done") && err.lines().any(|l| l == "2"), "{err}");
let info = cli(&["info", saved]);
let v: serde_json::Value = serde_json::from_slice(&info.stdout).unwrap();
assert_eq!(v["counts"]["Circle"], 1, "{v}");
}
+1
View File
@@ -2,6 +2,7 @@ mod cli;
mod dash_limit_note;
mod drafting_spacing;
mod help;
mod lisp_script;
// DWG output needs craft-dwg's bridge.
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod ltype_dwg_note;
+4 -3
View File
@@ -30,6 +30,10 @@ chrono = { workspace = true }
# Reads eframe's app.ron to tell whether a window state was saved (main.rs `saved_window`).
# Already in Cargo.lock through eframe; same version so nothing is built twice.
ron = "0.12"
# Waits for wgpu's answers while the graphics start (src/renderer.rs) and, on macOS, for the
# answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already in
# Cargo.lock through eframe.
pollster = "1"
[build-dependencies]
winresource = "0.1"
@@ -56,9 +60,6 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["std",
# The same winit eframe uses (the storytold fork, patched in the workspace).
# `rwh_06`: the window handle a file dialog shown as a sheet attaches to (src/sheet.rs).
winit = { version = "0.30", default-features = false, features = ["rwh_06"] }
# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already
# in Cargo.lock through eframe.
pollster = "1"
# Finder double-click, Open With, Dock drops and `open -a CADCraft plan.dxf` arrive as a
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle (#158). Keep the Objective-C
# handler behind a safe API, without relaxing the workspace's unsafe-code lint.
+8 -3
View File
@@ -23,7 +23,10 @@ pub(crate) const VARS: &[(&str, &str)] = &[
(CONFIG_DIR, "the settings folder (logs, autosave, workspace, plotters); empty means no settings folder"),
(LOCALE, "the interface language, instead of the system's"),
(VSYNC, "1 presents with vsync, 0 without it (default: without on Linux and BSD)"),
(STENCIL, "0 opens the window without a stencil buffer, for drivers that show a black window; clipped layout viewports then draw unclipped"),
(
STENCIL,
"0 opens the window without a stencil buffer, 1 keeps it on every attempt; unset, a start that can't draw with it drops it (clipped layout viewports then draw unclipped)",
),
(WAYLAND, "1 keeps the native Wayland backend instead of XWayland; 0 or unset is off"),
(NO_NATIVE_MENU, "macOS: 1 keeps the menus inside the window; 0 or unset is off"),
(SYSTEM_CURSOR, "1 uses the system cursor instead of the drawn crosshair; 0 or unset is off"),
@@ -46,8 +49,10 @@ pub(crate) struct Env {
pub(crate) locale: Option<String>,
/// Present with vsync (default: off on Linux and BSD, on elsewhere).
pub(crate) vsync: Switch,
/// Off: the window has no stencil buffer (default: on). Some old drivers (Mesa on Intel HD
/// 4000, old Intel drivers on Windows) accept a stencil pass and then present a black window.
/// Off: the window has no stencil buffer; on: it keeps one on every attempt at starting the
/// graphics. Default: it starts with one, and a start that can't draw with it drops it (see
/// `renderer`). Some old drivers (Mesa on Intel HD 4000, old Intel drivers on Windows) accept a
/// stencil pass and then present a black window.
pub(crate) stencil: Switch,
/// Keep the native Wayland backend instead of XWayland.
#[cfg_attr(not(all(unix, not(target_os = "macos"))), allow(dead_code))]
+63 -36
View File
@@ -33,6 +33,7 @@ mod nightly_session;
mod portable;
mod process_identity;
mod profile_root;
mod renderer;
#[cfg(target_os = "macos")]
mod sheet;
mod single_instance;
@@ -239,9 +240,38 @@ fn filters(pick: &Pick) -> Vec<(&'static str, Vec<&'static str>)> {
}
}
/// `Services::start_pick` for Linux and the BSDs: the blocking dialog runs on a thread of its
/// own, so the window keeps answering the desktop while the dialog is open; `ui` is woken when
/// it answers. If the thread cannot start, `done` is dropped unanswered and the app says the
/// dialog could not be shown.
#[cfg(all(unix, not(target_os = "macos")))]
fn start_pick(ui: egui::Context) -> cadcraft_ui_egui::StartPick {
Box::new(move |pick, done| {
let ui = ui.clone();
// Here, not on the thread: the interface language is this thread's
// (`i18n::with_language`), and the filter labels are translated.
let filters = filters(&pick);
let spawned = std::thread::Builder::new().name("file-dialog".into()).spawn(move || {
let dialog = file_dialog_with(&pick, &filters);
let picked = if matches!(pick, Pick::Save(_)) { dialog.save_file() } else { dialog.pick_file() };
done(picked.map(|p| p.to_string_lossy().to_string()));
ui.request_repaint();
});
if let Err(e) = spawned {
log::warn!("file dialog: {e}");
}
})
}
/// The blocking dialog for `pick` (Windows, Linux, FreeBSD).
fn file_dialog(pick: &Pick) -> rfd::FileDialog {
let dialog = filters(pick).iter().fold(rfd::FileDialog::new(), |d, (label, exts)| d.add_filter(*label, exts));
file_dialog_with(pick, &filters(pick))
}
/// [`file_dialog`] offering `filters`, the file types of `pick` ([`filters`]) as the caller's
/// thread names them.
fn file_dialog_with(pick: &Pick, filters: &[(&'static str, Vec<&'static str>)]) -> rfd::FileDialog {
let dialog = filters.iter().fold(rfd::FileDialog::new(), |d, (label, exts)| d.add_filter(*label, exts));
match pick {
Pick::Save(name) => dialog.set_file_name(name),
Pick::Lisp(dir) | Pick::Pgp(dir) if !dir.is_empty() => dialog.set_directory(dir),
@@ -306,7 +336,7 @@ const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
/// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state
/// saved by the last session is restored instead of opening centred. `stencil`: the stencil bits of
/// its render pass ([`stencil_bits`]).
/// its render pass (each attempt at starting the graphics sets its own, see [`renderer::apply`]).
fn window_options(restoring: bool, stencil: u8, frame: Option<&cadcraft_ui_egui::framework::Decision>) -> eframe::NativeOptions {
let viewport = egui::ViewportBuilder::default()
.with_title(os_window::name_for(os_window::identity()))
@@ -335,17 +365,6 @@ fn window_options(restoring: bool, stencil: u8, frame: Option<&cadcraft_ui_egui:
/// The key eframe saves the main window state under in its storage.
const WINDOW_KEY: &str = "window";
/// Stencil bits of the window's render pass (see `NativeOptions::stencil_buffer`).
const STENCIL_BITS: u8 = 8;
/// The stencil bits of the window's render pass: none when `CADCRAFT_STENCIL` is off. Some old
/// drivers (Mesa on Intel HD 4000, old Intel drivers on Windows) accept a stencil pass without an
/// error and then present a black window, so only an explicit opt-out drops it. Without a stencil
/// buffer, clipped layout viewports draw unclipped.
fn stencil_bits(stencil: Switch) -> u8 {
if stencil == Switch::Off { 0 } else { STENCIL_BITS }
}
#[cfg(target_os = "macos")]
const APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/cadcraft-macos-512.png");
#[cfg(not(target_os = "macos"))]
@@ -545,12 +564,6 @@ fn main() -> eframe::Result {
cadcraft_engine::fonts::ttf::set_fallback_fonts(list);
}
let surface = cadcraft_ui_egui::gpu::surface_config(vars.vsync, cfg!(all(unix, not(target_os = "macos"))));
// The window's render pass and the canvas's pipelines must agree on it; a mismatch is a wgpu
// validation error.
let stencil = stencil_bits(vars.stencil);
if stencil == 0 {
log::warn!("CADCRAFT_STENCIL is off: the window has no stencil buffer; clipped layout viewports draw unclipped");
}
// XWayland when it's there (see below), unless CADCRAFT_WAYLAND=1 keeps the native Wayland backend.
let forced_x11 = cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On;
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11);
@@ -563,7 +576,7 @@ fn main() -> eframe::Result {
// 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: persistence_path.clone(),
..window_options(restores_window(persistence_path.as_deref()), stencil, frame.as_ref())
..window_options(restores_window(persistence_path.as_deref()), renderer::STENCIL_BITS, frame.as_ref())
};
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
@@ -600,10 +613,13 @@ fn main() -> eframe::Result {
let apple_events = &apple_events;
// 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(
// Each attempt at starting the graphics sets its backends, adapter and stencil buffer, and a
// failed one is followed by the next (see renderer.rs).
let result = renderer::run_native(
os_window::name_for(os_window::identity()),
options,
Box::new(move |cc| {
vars.stencil,
Box::new(move |cc, started| {
cadcraft_ui_egui::framework::install(&cc.egui_ctx, forced_x11, frame.clone())?;
let mut app = CadApp::new(Session::empty(), services());
// The exit hook runs in `on_exit`: macOS ends the process inside AppKit's terminate after
@@ -618,6 +634,13 @@ fn main() -> eframe::Result {
if let Some(window) = cc.winit_window().cloned() {
app.services.start_pick = Some(sheet::start_pick(window, cc.egui_ctx.clone()));
}
// On Linux and the BSDs the dialog is the desktop portal's, another process: waiting
// for it in the event handler leaves the window unanswered for as long as it is open,
// and the desktop then offers to force-quit the app.
#[cfg(all(unix, not(target_os = "macos")))]
{
app.services.start_pick = Some(start_pick(cc.egui_ctx.clone()));
}
let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref());
if let Some(ui) = restored {
app.ui = ui;
@@ -671,9 +694,8 @@ fn main() -> eframe::Result {
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
}
if let Some(rs) = &cc.wgpu_render_state {
app.set_wgpu(rs, eframe::egui_wgpu::depth_format_from_bits(0, stencil));
}
// On the GPU with the window's stencil buffer, or on the CPU when the GPU refuses the canvas.
started.install(&mut app, cc.wgpu_render_state.as_ref());
if let Some(port) = control_port {
let rx = control_server::start(port, cc.egui_ctx.clone());
app = app.with_control(rx);
@@ -731,10 +753,8 @@ fn main() -> eframe::Result {
#[cfg(test)]
mod tests {
use super::{
STENCIL_BITS, filters_for_save, follow_desktop, nightly_version_line, saved_window, stencil_bits, version_string, window_options,
without_tiny_window,
};
use super::{filters_for_save, follow_desktop, nightly_version_line, saved_window, version_string, window_options, without_tiny_window};
use crate::renderer::STENCIL_BITS;
#[test]
fn save_dialog_offers_dwg_with_the_drawing_format_first() {
@@ -769,18 +789,25 @@ mod tests {
}
/// `CADCRAFT_STENCIL=0` (also `no`, `false`, any case) opens the window without a stencil
/// buffer; unset, blank, `1` or anything else keeps it.
/// buffer, and `1` keeps it on every attempt; unset, blank or anything else starts with one and
/// lets a failed start drop it.
#[test]
fn the_stencil_buffer_is_dropped_only_when_asked() {
let bits = |value: Option<&str>| {
fn the_stencil_buffer_follows_cadcraft_stencil() {
let stencils = |value: Option<&str>| {
let vars = crate::env::Env::from_vars(|k| (k == "CADCRAFT_STENCIL").then_some(value).flatten().map(Into::into));
stencil_bits(vars.stencil)
let attempts = crate::renderer::attempts(eframe::wgpu::Backends::DX12, false, vars.stencil);
attempts.iter().map(|a| a.stencil).collect::<std::collections::BTreeSet<_>>().into_iter().collect::<Vec<_>>()
};
for off in ["0", "no", "NO", "false", "False", " 0 "] {
assert_eq!(bits(Some(off)), 0, "{off:?}");
assert_eq!(stencils(Some(off)), [false], "{off:?}");
}
for on in [None, Some(""), Some("1"), Some("yes"), Some("8"), Some("maybe")] {
assert_eq!(bits(on), STENCIL_BITS, "{on:?}");
for on in ["1", "yes", "On"] {
assert_eq!(stencils(Some(on)), [true], "{on:?}");
}
for unset in [None, Some(""), Some("8"), Some("maybe")] {
assert_eq!(stencils(unset), [false, true], "{unset:?}");
let vars = crate::env::Env::from_vars(|k| (k == "CADCRAFT_STENCIL").then_some(unset).flatten().map(Into::into));
assert!(crate::renderer::attempts(eframe::wgpu::Backends::DX12, false, vars.stencil)[0].stencil, "{unset:?}: the first has one");
}
}
+660
View File
@@ -0,0 +1,660 @@
//! Which renderer draws the window, and what the app does when one can't start.
//!
//! The window draws with wgpu (eframe is built with its `wgpu` renderer only). Where a start fails
//! decides what is tried next:
//!
//! - The adapter, the device or the window's surface can't be made (no adapter for the backends, a
//! device the driver refuses or loses): eframe returns `Error::Wgpu` before the app exists. The
//! stencil buffer plays no part, so another adapter is tried.
//! - The window's surface can't be configured, or egui's pipelines are refused: also before the app
//! exists. The stencil buffer is part of both, so the same adapter is tried without it first.
//! - The driver takes the stencil buffer and then draws nothing, with no error: Mesa's OpenGL on Ivy
//! Bridge refuses `glTexStorage2D(GL_STENCIL_INDEX8)`, the frame buffer is incomplete and every
//! frame comes out black (#1724). egui makes the window's stencil buffer a texture it can also
//! sample, which wgpu's OpenGL backend stores with that call. Before the app is created, [`check`]
//! clears a small target, without and then with a stencil buffer made the same way, and reads it
//! back.
//! - The canvas's own pipelines are refused: the canvas draws on the CPU ([`Started::install`]).
//!
//! Not caught: a driver that crashes the process or hangs, a black window whose offscreen check
//! passes (a fault in presenting to the window), a failure after the app was created (an error
//! then ends the start as before), and a panic inside eframe or egui-wgpu.
//!
//! The attempts, in order ([`attempts`]): the start as it always was (DirectX 12 alone on Windows,
//! see `graphics.rs`; eframe's backends elsewhere); OpenGL alone, where those backends have it
//! beside another; then those backends with a software adapter only (WARP, llvmpipe). Each is tried
//! with a stencil buffer, then without. No attempt creates a backend the first one did not, so no
//! driver code runs that the start did not run before: on Windows, where OpenGL is left out because
//! an AMD driver crashes inside it (#31), the fallback is WARP. A start that works today makes only
//! the first attempt, and the check.
//!
//! `WGPU_BACKEND` limits every attempt to its backends, and `CADCRAFT_STENCIL` fixes the stencil
//! buffer. Nothing is remembered between starts: a failed attempt costs a fraction of a second, and
//! a remembered choice would keep a lesser renderer after a failure that happened once.
use std::sync::Arc;
use std::time::Duration;
use cadcraft_ui_egui::CadApp;
use cadcraft_ui_egui::switch::Switch;
use eframe::egui_wgpu::{self, NativeAdapterSelectorMethod, WgpuError, WgpuSetup};
use eframe::wgpu::{self, Backends, DeviceType};
/// Stencil bits of the window's render pass when an attempt has a stencil buffer (see
/// `NativeOptions::stencil_buffer`).
pub(crate) const STENCIL_BITS: u8 = 8;
/// How long [`check`] waits for its read-back. A slower answer counts as a pass: a busy GPU is no
/// reason to fall back.
const CHECK_TIMEOUT: Duration = Duration::from_secs(10);
/// The width of [`check`]'s target: one row of RGBA8 pixels is then exactly the row alignment a
/// copy to a buffer needs.
const CHECK_WIDTH: u32 = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT / 4;
/// The colour [`check`] clears to, as it reads back: a new texture starts as zeros.
const CHECK_COLOR: [u8; 4] = [255, 0, 255, 255];
type DynError = Box<dyn std::error::Error + Send + Sync>;
/// Builds the app once an attempt's window draws.
pub(crate) type Creator<'a> = Box<dyn FnOnce(&eframe::CreationContext<'_>, &Started) -> Result<Box<dyn eframe::App + 'a>, DynError> + 'a>;
/// The backends by name, for the log and the status bar.
const NAMES: [(Backends, &str); 4] =
[(Backends::DX12, "DirectX 12"), (Backends::METAL, "Metal"), (Backends::VULKAN, "Vulkan"), (Backends::GL, "OpenGL")];
/// One way to start the window's graphics.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Attempt {
/// The backends wgpu chooses an adapter from.
pub(crate) backends: Backends,
/// Only a software adapter (WARP, llvmpipe); otherwise wgpu's choice, which prefers a GPU.
pub(crate) software: bool,
/// The window has a stencil buffer, which clips the contents of clipped layout viewports.
pub(crate) stencil: bool,
}
impl Attempt {
/// The same adapter: an attempt that differs only in its stencil buffer.
fn same_adapter(self, other: Attempt) -> bool {
(self.backends, self.software) == (other.backends, other.software)
}
}
impl std::fmt::Display for Attempt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let backends: Vec<&str> = NAMES.iter().filter(|n| self.backends.contains(n.0)).map(|n| n.1).collect();
f.write_str(&if backends.is_empty() { format!("{:?}", self.backends) } else { backends.join(" or ") })?;
if self.software {
f.write_str(" on a software adapter")?;
}
f.write_str(if self.stencil { "" } else { " without a stencil buffer" })
}
}
/// The attempts in order (see the module docs). `first`: the backends the start is configured with;
/// `requested`: they are `WGPU_BACKEND`'s, which every attempt keeps; `stencil`: `CADCRAFT_STENCIL`.
pub(crate) fn attempts(first: Backends, requested: bool, stencil: Switch) -> Vec<Attempt> {
let mut adapters = vec![(first, false)];
if !requested && first.contains(Backends::GL) && first != Backends::GL {
adapters.push((Backends::GL, false));
}
adapters.push((first, true));
let stencils: &[bool] = match stencil {
Switch::On => &[true],
Switch::Off => &[false],
Switch::Default => &[true, false],
};
adapters.into_iter().flat_map(|(backends, software)| stencils.iter().map(move |&stencil| Attempt { backends, software, stencil })).collect()
}
/// What a failed attempt says about the attempts after it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Failure {
/// The adapter, the device or the surface couldn't be made, or nothing was drawn: the same
/// adapter without a stencil buffer fails the same way.
Adapter,
/// Something the stencil buffer is part of failed: the same adapter without one may work.
Stencil,
}
/// The attempt to try after the one at `at` failed with `failure`: the next one after a stencil
/// failure, else the next on another adapter.
pub(crate) fn next(attempts: &[Attempt], at: usize, failure: Failure) -> Option<usize> {
let failed = *attempts.get(at)?;
attempts.iter().enumerate().skip(at + 1).find(|(_, a)| failure == Failure::Stencil || !a.same_adapter(failed)).map(|(i, _)| i)
}
/// What `error` from `eframe::run_native` says about the attempt: `None` when it isn't the graphics
/// (the app's own start, the windowing system).
pub(crate) fn classify(error: &eframe::Error) -> Option<Failure> {
match error {
eframe::Error::Wgpu(WgpuError::ConfigureSurface(_) | WgpuError::CreateRenderer(_)) => Some(Failure::Stencil),
eframe::Error::Wgpu(_) => Some(Failure::Adapter),
eframe::Error::AppCreation(error) => error.downcast_ref::<CheckFailed>().map(|c| c.failure),
_ => None,
}
}
/// The attempt to try after the one at `at` ended with `error`: none once the app was `created`,
/// since a failure after that is no start failure (and the app can't be built twice), and none for
/// an error that isn't the graphics'.
pub(crate) fn retry(attempts: &[Attempt], at: usize, created: bool, error: &eframe::Error) -> Option<usize> {
if created {
return None;
}
next(attempts, at, classify(error)?)
}
/// [`check`] found that the window can't draw. Returned from the app creator, it ends the attempt
/// before the app exists.
#[derive(Debug)]
pub(crate) struct CheckFailed {
failure: Failure,
message: String,
}
impl std::fmt::Display for CheckFailed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for CheckFailed {}
/// Clear a small target and read it back: as it is, then with a stencil buffer of `stencil`, made
/// as egui makes the window's (see the module docs). A target that doesn't come back cleared is a
/// [`Failure::Adapter`] without the stencil buffer and a [`Failure::Stencil`] with it.
pub(crate) fn check(device: &wgpu::Device, queue: &wgpu::Queue, stencil: Option<wgpu::TextureFormat>) -> Result<(), CheckFailed> {
passes(stencil, |format| clear_and_read(device, queue, format))
}
/// [`check`]'s passes, each made by `pass` with or without the stencil buffer: what failed names
/// the [`Failure`], and a device that didn't answer the first pass isn't waited for a second time.
fn passes(
stencil: Option<wgpu::TextureFormat>,
mut pass: impl FnMut(Option<wgpu::TextureFormat>) -> Result<bool, String>,
) -> Result<(), CheckFailed> {
let failed = |failure: Failure| move |message: String| CheckFailed { failure, message };
let answered = pass(None).map_err(failed(Failure::Adapter))?;
match stencil {
Some(format) if answered => pass(Some(format)).map(|_| ()).map_err(failed(Failure::Stencil)),
_ => Ok(()),
}
}
/// One pass of [`check`]: `Err` names what came back instead of [`CHECK_COLOR`]; `Ok(false)`: no
/// answer came, which counts as a pass.
fn clear_and_read(device: &wgpu::Device, queue: &wgpu::Queue, stencil: Option<wgpu::TextureFormat>) -> Result<bool, String> {
let size = wgpu::Extent3d { width: CHECK_WIDTH, height: 1, depth_or_array_layers: 1 };
let row = CHECK_WIDTH * 4;
let submitted = pollster::block_on(egui_wgpu::winit::catch_errors(device, || {
let texture = |format, usage| {
device.create_texture(&wgpu::TextureDescriptor {
label: Some("startup check"),
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
})
};
let color = texture(wgpu::TextureFormat::Rgba8Unorm, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC);
// The usage egui gives the window's depth and stencil texture.
let depth = stencil.map(|format| texture(format, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING));
let color_view = color.create_view(&wgpu::TextureViewDescriptor::default());
let depth_view = depth.as_ref().map(|t| t.create_view(&wgpu::TextureViewDescriptor::default()));
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("startup check"),
size: u64::from(row),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
let [r, g, b, a] = CHECK_COLOR.map(|c| f64::from(c) / 255.0);
drop(encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("startup check"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &color_view,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r, g, b, a }), store: wgpu::StoreOp::Store },
depth_slice: None,
})],
depth_stencil_attachment: depth_view.as_ref().zip(stencil).map(|(view, format)| wgpu::RenderPassDepthStencilAttachment {
view,
depth_ops: format.has_depth_aspect().then_some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }),
stencil_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0), store: wgpu::StoreOp::Discard }),
}),
..Default::default()
}));
encoder.copy_texture_to_buffer(
color.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &buffer,
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: None },
},
size,
);
queue.submit([encoder.finish()]);
buffer
}));
let buffer = submitted.map_err(|e| format!("the device refused the check: {e}"))?;
let (send, mapped) = std::sync::mpsc::channel();
buffer.slice(..).map_async(wgpu::MapMode::Read, move |result| {
let _ = send.send(result);
});
match device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(CHECK_TIMEOUT) }) {
Ok(_) => {}
Err(wgpu::PollError::Timeout) => {
log::warn!("graphics: the start-up check had no answer after {CHECK_TIMEOUT:?}; taken as passed");
return Ok(false);
}
Err(e) => return Err(format!("waiting for the check failed: {e}")),
}
match mapped.try_recv() {
Ok(Ok(())) => {}
Ok(Err(e)) => return Err(format!("the check could not be read back: {e}")),
Err(_) => {
log::warn!("graphics: the start-up check was not read back; taken as passed");
return Ok(false);
}
}
let pixels = buffer.slice(..).get_mapped_range().map_err(|e| format!("the check could not be read back: {e}"))?;
read_back(&pixels).map(|()| true)
}
/// Whether the row [`check`] read back is [`CHECK_COLOR`] throughout, within what a driver's
/// rounding could change.
fn read_back(pixels: &[u8]) -> Result<(), String> {
let row = CHECK_WIDTH as usize * CHECK_COLOR.len();
let cleared = |p: &[u8; CHECK_COLOR.len()]| p.iter().zip(CHECK_COLOR).all(|(&p, c)| p.abs_diff(c) <= 8);
match pixels.as_chunks::<{ CHECK_COLOR.len() }>().0.iter().find(|&p| !cleared(p)) {
Some(p) => Err(format!("a cleared target read back {p:?}, not {CHECK_COLOR:?}")),
None if pixels.len() == row => Ok(()),
None => Err(format!("the check read back {} bytes, not {row}", pixels.len())),
}
}
/// `options` for `attempt`: its backends, its adapter and its stencil buffer.
pub(crate) fn apply(options: &mut eframe::NativeOptions, attempt: Attempt) {
options.stencil_buffer = if attempt.stencil { STENCIL_BITS } else { 0 };
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
create.instance_descriptor.backends = attempt.backends;
create.native_adapter_selector = attempt.software.then(|| Arc::new(software_adapter) as NativeAdapterSelectorMethod);
}
}
/// A software adapter of `adapters` that can show `surface`.
fn software_adapter(adapters: &[wgpu::Adapter], surface: Option<&wgpu::Surface<'_>>) -> Result<wgpu::Adapter, String> {
adapters
.iter()
.find(|a| a.get_info().device_type == DeviceType::Cpu && surface.is_none_or(|s| a.is_surface_supported(s)))
.cloned()
.ok_or_else(|| "no software adapter can show the window".to_owned())
}
/// Run eframe with each attempt in turn until one starts the window, then build the app with
/// `create`. `options` are as configured (their backends are `WGPU_BACKEND`'s or the platform's),
/// `stencil` is `CADCRAFT_STENCIL`. A failed attempt is dropped with its window before any app
/// exists; an error once the app was created ends the start, as before. When every attempt failed,
/// the first one's error is returned: it is the one the start as it always was would have given.
pub(crate) fn run_native(name: &str, options: eframe::NativeOptions, stencil: Switch, create: Creator<'_>) -> eframe::Result {
let requested = Backends::from_env().is_some();
let configured = match &options.wgpu_options.wgpu_setup {
WgpuSetup::CreateNew(create) => create.instance_descriptor.backends,
WgpuSetup::Existing(_) => Backends::all(),
};
// Only what this build has, so no attempt asks for a backend that can't be there.
let first = if requested { configured } else { configured & wgpu::Instance::enabled_backend_features() };
let attempts = attempts(first, requested, stencil);
// Later attempts reuse eframe's event loop, so the hooks a clone drops aren't needed again.
let template = options.clone();
let mut options = Some(options);
let mut create = Some(create);
let mut first_failure = None;
let mut why = None;
let mut at = 0;
while let Some(&attempt) = attempts.get(at) {
let mut attempt_options = options.take().unwrap_or_else(|| template.clone());
apply(&mut attempt_options, attempt);
fault::refuse_adapter(&mut attempt_options, at);
log::info!("graphics: starting with {attempt} (attempt {} of {})", at + 1, attempts.len());
let started = Started { attempt, index: at, why: why.clone() };
let slot = &mut create;
let result = eframe::run_native(
name,
attempt_options,
Box::new(|cc| {
if let Some(rs) = &cc.wgpu_render_state {
fault::check(started.index, started.stencil_format())?;
let checking = std::time::Instant::now();
check(&rs.device, &rs.queue, started.stencil_format())?;
log::info!("graphics: the start-up check passed in {:.1?}", checking.elapsed());
}
let create = slot.take().ok_or("the app was already created")?;
create(cc, &started)
}),
);
let Err(error) = result else { return Ok(()) };
let Some(after) = retry(&attempts, at, create.is_none(), &error) else {
if create.is_none() || classify(&error).is_none() {
return Err(error);
}
log::error!("graphics: {attempt} failed: {error}; no other renderer is left to try");
return Err(first_failure.unwrap_or(error));
};
log::warn!("graphics: {attempt} failed: {error}; trying the next renderer");
// The first failure says why the first choice isn't drawing; the log has the others.
why.get_or_insert_with(|| format!("{attempt} failed: {}", error.to_string().lines().next().unwrap_or_default()));
first_failure.get_or_insert(error);
at = after;
}
Err(first_failure.unwrap_or_else(|| eframe::Error::AppCreation("no renderer to start the window with".into())))
}
/// The attempt that started the window, handed to the app creator.
pub(crate) struct Started {
attempt: Attempt,
/// Its position in [`attempts`].
index: usize,
/// Why the first attempt isn't the one drawing.
why: Option<String>,
}
impl Started {
/// The format of the window's stencil buffer, which the canvas's pipelines must match.
fn stencil_format(&self) -> Option<wgpu::TextureFormat> {
egui_wgpu::depth_format_from_bits(0, if self.attempt.stencil { STENCIL_BITS } else { 0 })
}
/// Draw the canvas on the GPU with the window's render state `rs`, or on the CPU when its
/// pipelines are refused. Logs which renderer draws, and says in the status bar why when it is
/// not the first choice (unless the start already put something there).
pub(crate) fn install(&self, app: &mut CadApp, rs: Option<&egui_wgpu::RenderState>) {
let Some(rs) = rs else { return };
let stencil = self.stencil_format();
let installed = pollster::block_on(egui_wgpu::winit::catch_errors(&rs.device, || app.set_wgpu(rs, stencil)));
let canvas_failed = match installed {
Err(e) => Some(e.to_string()),
Ok(()) => fault::canvas(self.index),
};
if canvas_failed.is_some() {
app.canvas.gpu = None;
app.canvas.gpu_device = None;
}
let info = rs.adapter.get_info();
log::info!(
"graphics: {} draws the window on {} ({:?}, {:?}, driver {}); the canvas draws on the {}",
self.attempt,
info.name.trim(),
info.backend,
info.device_type,
[info.driver.trim(), info.driver_info.trim()].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" "),
if canvas_failed.is_some() { "CPU" } else { "GPU" }
);
if !self.attempt.stencil {
log::warn!("graphics: no stencil buffer: clipped layout viewports draw unclipped");
}
let note = match (&self.why, &canvas_failed) {
(_, Some(error)) => {
Some(cadcraft_ui_egui::tf!("Graphics: the drawing area draws on the CPU, because the GPU refused it: {error}", error = error))
}
(Some(why), None) => Some(cadcraft_ui_egui::tf!("Graphics: drawing with {renderer}, because {why}", renderer = self.attempt, why = why)),
(None, None) => None,
};
if let Some(note) = note {
log::warn!("{note}");
if app.status.is_none() {
app.set_status(note);
}
}
}
}
/// A test switch read only by debug builds: `CADCRAFT_GRAPHICS_FAULT=<attempt>:<step>[,...]` fails
/// the attempt at that position in [`attempts`] (from 0) at `adapter` (its adapter is refused),
/// `draw` or `stencil` ([`check`]'s pass without or with the stencil buffer), or `canvas` (the
/// canvas's pipelines), so each fallback can be run on a machine whose graphics work.
mod fault {
use super::{Arc, CheckFailed, Failure, NativeAdapterSelectorMethod, WgpuSetup, wgpu};
#[cfg(debug_assertions)]
fn asked(index: usize, step: &str) -> bool {
listed(std::env::var("CADCRAFT_GRAPHICS_FAULT").ok().as_deref(), index, step)
}
#[cfg(not(debug_assertions))]
fn asked(_index: usize, _step: &str) -> bool {
false
}
/// Whether `value` lists `<index>:<step>`.
#[cfg(any(debug_assertions, test))]
pub(super) fn listed(value: Option<&str>, index: usize, step: &str) -> bool {
value.is_some_and(|v| v.split(',').any(|f| f.trim().split_once(':') == Some((index.to_string().as_str(), step))))
}
pub(super) fn refuse_adapter(options: &mut eframe::NativeOptions, index: usize) {
if asked(index, "adapter")
&& let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup
{
let refuse = |_: &[wgpu::Adapter], _: Option<&wgpu::Surface<'_>>| Err("refused by CADCRAFT_GRAPHICS_FAULT".to_owned());
create.native_adapter_selector = Some(Arc::new(refuse) as NativeAdapterSelectorMethod);
}
}
pub(super) fn check(index: usize, stencil: Option<wgpu::TextureFormat>) -> Result<(), CheckFailed> {
let fail = |failure, step| CheckFailed { failure, message: format!("the {step} check failed (CADCRAFT_GRAPHICS_FAULT)") };
if asked(index, "draw") {
return Err(fail(Failure::Adapter, "draw"));
}
if stencil.is_some() && asked(index, "stencil") {
return Err(fail(Failure::Stencil, "stencil"));
}
Ok(())
}
pub(super) fn canvas(index: usize) -> Option<String> {
asked(index, "canvas").then(|| "refused by CADCRAFT_GRAPHICS_FAULT".to_owned())
}
}
#[cfg(test)]
mod tests {
use super::*;
const ANY: Backends = Backends::VULKAN.union(Backends::GL);
/// A short name of `attempt`, to read the order in the asserts.
fn key(attempt: &Attempt) -> String {
let short = [(Backends::DX12, "dx12"), (Backends::METAL, "metal"), (Backends::VULKAN, "vulkan"), (Backends::GL, "gl")];
let mut key = short.iter().filter(|(b, _)| attempt.backends.contains(*b)).map(|(_, n)| *n).collect::<Vec<_>>().join("+");
if attempt.software {
key.push_str(" software");
}
if !attempt.stencil {
key.push_str(" no-stencil");
}
key
}
fn keys(list: &[Attempt]) -> Vec<String> {
list.iter().map(key).collect()
}
/// The first attempt is the start as it always was; OpenGL alone comes only where it was one of
/// several, then the same backends on a software adapter, each with and then without a stencil
/// buffer. `WGPU_BACKEND` keeps its backends on every attempt, and `CADCRAFT_STENCIL` its choice.
#[test]
fn the_attempts_begin_with_the_start_as_it_was_and_keep_explicit_choices() {
let linux = attempts(ANY, false, Switch::Default);
assert_eq!(keys(&linux), ["vulkan+gl", "vulkan+gl no-stencil", "gl", "gl no-stencil", "vulkan+gl software", "vulkan+gl software no-stencil"]);
// Windows: DirectX 12 alone (graphics.rs), so the fallback never creates OpenGL there.
let windows = attempts(Backends::DX12, false, Switch::Default);
assert_eq!(keys(&windows), ["dx12", "dx12 no-stencil", "dx12 software", "dx12 software no-stencil"]);
// WGPU_BACKEND=vulkan,gl: no attempt leaves its backends.
assert!(attempts(ANY, true, Switch::Default).iter().all(|a| a.backends == ANY));
assert_eq!(attempts(Backends::GL, false, Switch::Default).len(), 4, "OpenGL alone is already the first");
// CADCRAFT_STENCIL: off is never on, on is never dropped.
assert!(attempts(ANY, false, Switch::Off).iter().all(|a| !a.stencil));
assert!(attempts(ANY, false, Switch::On).iter().all(|a| a.stencil));
assert_eq!(attempts(ANY, false, Switch::On).len() * 2, linux.len());
}
/// A stencil failure tries the same adapter without the stencil buffer; any other failure skips
/// that twin and tries the next adapter; past the last there is nothing.
#[test]
fn a_failure_picks_the_next_attempt_by_what_failed() {
let list = attempts(ANY, false, Switch::Default);
let at = |k: &str| list.iter().position(|a| key(a) == k).unwrap();
let next_key = |from: &str, failure| next(&list, at(from), failure).map(|i| key(&list[i]));
assert_eq!(next_key("vulkan+gl", Failure::Stencil).as_deref(), Some("vulkan+gl no-stencil"));
assert_eq!(next_key("vulkan+gl", Failure::Adapter).as_deref(), Some("gl"));
assert_eq!(next_key("vulkan+gl no-stencil", Failure::Adapter).as_deref(), Some("gl"));
assert_eq!(next_key("gl no-stencil", Failure::Stencil).as_deref(), Some("vulkan+gl software"));
assert_eq!(next_key("vulkan+gl software", Failure::Adapter), None);
assert_eq!(next_key("vulkan+gl software no-stencil", Failure::Stencil), None);
assert_eq!(next(&list, list.len(), Failure::Stencil), None);
// CADCRAFT_STENCIL=1: a stencil failure has no twin to fall back to, so the next adapter.
let on = attempts(Backends::DX12, false, Switch::On);
assert_eq!(next(&on, 0, Failure::Stencil), Some(1));
assert!(on[1].software);
}
/// Errors before the app exists are graphics failures; which kind decides the next attempt. The
/// app's own errors and the windowing system's are not, so they end the start as before.
#[test]
fn start_errors_are_sorted_by_what_failed() {
let no_adapter = eframe::Error::Wgpu(WgpuError::CustomNativeAdapterSelectionError("none".into()));
assert_eq!(classify(&no_adapter), Some(Failure::Adapter));
assert_eq!(classify(&eframe::Error::Wgpu(WgpuError::NoSurfaceFormatsAvailable)), Some(Failure::Adapter));
let refused = || wgpu::Error::Validation { source: Box::new(std::fmt::Error), description: "refused".into() };
assert_eq!(classify(&eframe::Error::Wgpu(WgpuError::ConfigureSurface(refused()))), Some(Failure::Stencil));
assert_eq!(classify(&eframe::Error::Wgpu(WgpuError::CreateRenderer(refused()))), Some(Failure::Stencil));
for failure in [Failure::Adapter, Failure::Stencil] {
let failed = eframe::Error::AppCreation(Box::new(CheckFailed { failure, message: "black".into() }));
assert_eq!(classify(&failed), Some(failure));
}
assert_eq!(classify(&eframe::Error::AppCreation("the app's own start".into())), None);
}
/// Only a graphics failure before the app exists is retried: once the app was created an error
/// ends the start (the app can't be built twice), as does an error that isn't the graphics'.
#[test]
fn only_a_start_failure_before_the_app_exists_is_retried() {
let list = attempts(Backends::DX12, false, Switch::Default);
let gpu = eframe::Error::Wgpu(WgpuError::NoSurfaceFormatsAvailable);
assert_eq!(retry(&list, 0, false, &gpu), Some(2));
assert_eq!(retry(&list, 0, true, &gpu), None);
let black = eframe::Error::AppCreation(Box::new(CheckFailed { failure: Failure::Stencil, message: "black".into() }));
assert_eq!(retry(&list, 0, false, &black), Some(1));
assert_eq!(retry(&list, 0, false, &eframe::Error::AppCreation("the app's own start".into())), None);
}
/// Each attempt takes its backends, its adapter and its stencil buffer.
#[test]
fn an_attempt_sets_its_backends_adapter_and_stencil_buffer() {
let mut options = eframe::NativeOptions::default();
for attempt in attempts(Backends::VULKAN | Backends::GL, false, Switch::Default) {
apply(&mut options, attempt);
let WgpuSetup::CreateNew(create) = &options.wgpu_options.wgpu_setup else { panic!("eframe creates its own wgpu setup") };
assert_eq!(create.instance_descriptor.backends, attempt.backends);
assert_eq!(create.native_adapter_selector.is_some(), attempt.software, "{attempt}");
assert_eq!(options.stencil_buffer > 0, attempt.stencil, "{attempt}");
}
}
/// The read-back is answered and passes on a working device, with and without a stencil
/// buffer. The device is made as the app makes it: on Windows DirectX 12 alone with FXC
/// (graphics.rs; an AMD driver crashes when OpenGL is created there, #31), and egui's limits for
/// the adapter.
#[test]
fn the_check_passes_on_a_device_that_draws() {
let mut options = eframe::NativeOptions::default();
crate::graphics::configure(&mut options, if cfg!(windows) { None } else { Some(Backends::all()) }, None);
let WgpuSetup::CreateNew(mut create) = options.wgpu_options.wgpu_setup else { panic!("eframe creates its own wgpu setup") };
create.instance_descriptor.backends.remove(Backends::BROWSER_WEBGPU);
let setup = WgpuSetup::CreateNew(create);
let instance = pollster::block_on(setup.new_instance());
let config = egui_wgpu::WgpuConfiguration { wgpu_setup: setup, ..Default::default() };
let Ok(rs) = pollster::block_on(egui_wgpu::RenderState::create(&config, &instance, None, Default::default())) else {
eprintln!("no graphics adapter here: the device check is left to machines with one");
return;
};
let info = rs.adapter.get_info();
for stencil in [None, Some(wgpu::TextureFormat::Stencil8)] {
// `check` takes no answer as a pass; a working device must answer, or every start on it
// would wait for the timeout.
let started = std::time::Instant::now();
let read = clear_and_read(&rs.device, &rs.queue, stencil);
let elapsed = started.elapsed();
assert_eq!(read, Ok(true), "{stencil:?} on {} ({:?}, {:?}) after {elapsed:?}", info.name, info.backend, info.device_type);
}
}
/// The read-back passes only when every pixel came back cleared: a target the clear never
/// reached still holds the zeros a texture starts as.
#[test]
fn the_check_fails_a_target_the_clear_did_not_reach() {
let row = |pixel: [u8; 4]| pixel.repeat(CHECK_WIDTH as usize);
assert!(read_back(&row(CHECK_COLOR)).is_ok());
assert!(read_back(&row([250, 6, 251, 255])).is_ok(), "a driver's rounding");
assert!(read_back(&row([0, 0, 0, 0])).is_err(), "never cleared");
assert!(read_back(&row([255, 0, 255, 0])).is_err(), "another alpha");
let mut one_off = row(CHECK_COLOR);
one_off[CHECK_COLOR.len() * 7 + 1] = 200;
assert!(read_back(&one_off).is_err(), "one pixel the clear missed");
assert!(read_back(&row(CHECK_COLOR)[..8]).is_err(), "a short read");
assert!(read_back(&[]).is_err());
}
/// A target that didn't come back cleared blames the adapter without the stencil buffer and the
/// stencil buffer with it; no answer is a pass, and isn't waited for twice.
#[test]
fn a_failed_pass_names_what_failed() {
let stencil = Some(wgpu::TextureFormat::Stencil8);
let failure = |black_with: Option<bool>| {
passes(stencil, |format| if black_with.is_none_or(|with| with == format.is_some()) { Err("black".into()) } else { Ok(true) })
.map_err(|e| e.failure)
};
assert_eq!(failure(Some(false)), Err(Failure::Adapter), "black without the stencil buffer");
assert_eq!(failure(None), Err(Failure::Adapter), "black either way");
assert_eq!(failure(Some(true)), Err(Failure::Stencil), "black only with it");
let mut asked = Vec::new();
let unanswered = passes(stencil, |format| {
asked.push(format);
Ok(false)
});
assert!(unanswered.is_ok());
assert_eq!(asked, [None], "no second wait after no answer");
let mut asked = Vec::new();
let answered = passes(stencil, |format| {
asked.push(format);
Ok(true)
});
assert!(answered.is_ok());
assert_eq!(asked, [None, stencil], "both passes when the first answered");
}
/// The test switch names attempts by position and step, and nothing else trips it.
#[test]
fn the_fault_switch_names_one_step_of_one_attempt() {
assert!(fault::listed(Some("0:stencil"), 0, "stencil"));
assert!(fault::listed(Some(" 2:adapter , 0:draw"), 0, "draw"));
assert!(!fault::listed(Some("0:stencil"), 1, "stencil"));
assert!(!fault::listed(Some("10:draw"), 1, "draw"));
assert!(!fault::listed(Some("0:stencils"), 0, "stencil"));
assert!(!fault::listed(None, 0, "draw"));
}
/// The log and the status bar tell the attempts apart.
#[test]
fn an_attempt_names_what_it_tries() {
let list = attempts(ANY, false, Switch::Default);
let names: std::collections::BTreeSet<String> = list.iter().map(ToString::to_string).collect();
assert_eq!(names.len(), list.len());
}
}
+23 -20
View File
@@ -206,8 +206,7 @@ pub fn next_id(d: &Drawing) -> u32 {
/// Interpret a constraint against the model's current parameters, appending its auxiliary
/// unknowns (contact parameters) to the model, settled with the geometry held still.
pub(crate) fn interpret(c: &Constraint, model: &mut Model, target: f64) -> Result<Built, String> {
let x = model.x0.clone();
let mut b = Built::new(c, model, &x, target)?;
let mut b = Built::new(c, model, &model.x0, target)?;
if b.aux_init.is_empty() {
return Ok(b);
}
@@ -527,22 +526,26 @@ pub fn solve(d: &mut Drawing, opts: &SolveOptions) -> Result<SolveReport, SolveE
/// Largest residual of each constraint at the current geometry (`None` when it cannot be
/// interpreted).
pub fn residuals(d: &Drawing) -> Vec<(u32, Option<f64>)> {
let mut e = env(d);
residuals_with_model(d, residual_model(d)).collect()
}
fn residual_model(d: &Drawing) -> Model {
let handles: Vec<Handle> = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
let mut model = Model::build(d, &handles);
d.constraints
.iter()
.take(MAX_CONSTRAINTS)
.map(|c| {
let target = if c.kind.is_dimensional() { constraint_value(&mut e, c).ok() } else { Some(0.0) };
let r = target.and_then(|t| interpret(c, &mut model, t).ok()).map(|b| {
let mut out = Vec::new();
b.eval(&model, &model.x0, &mut out);
lm::max_abs(&out)
});
(c.id, r)
})
.collect()
Model::build(d, &handles)
}
fn residuals_with_model(d: &Drawing, mut model: Model) -> impl Iterator<Item = (u32, Option<f64>)> + '_ {
let mut e = env(d);
let mut out = Vec::new();
d.constraints.iter().take(MAX_CONSTRAINTS).map(move |c| {
let target = if c.kind.is_dimensional() { constraint_value(&mut e, c).ok() } else { Some(0.0) };
let r = target.and_then(|t| interpret(c, &mut model, t).ok()).map(|b| {
out.clear();
b.eval(&model, &model.x0, &mut out);
lm::max_abs(&out)
});
(c.id, r)
})
}
/// Put back what each Fix locks where `before` had it, and report whether anything moved.
@@ -683,9 +686,9 @@ pub fn moved_anchors(d: &Drawing, before: &Drawing) -> Vec<(u32, Vec2)> {
/// True when every interpretable constraint holds at the current geometry.
pub fn all_satisfied(d: &Drawing) -> bool {
let handles: Vec<Handle> = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
let tol = scale_tol(&Model::build(d, &handles).x0) * 10.0;
residuals(d).iter().all(|(_, r)| r.is_none_or(|v| v <= tol))
let model = residual_model(d);
let tol = scale_tol(&model.x0) * 10.0;
residuals_with_model(d, model).all(|(_, r)| r.is_none_or(|v| v <= tol))
}
/// Check that a constraint's references make sense for its type.
+36 -16
View File
@@ -222,6 +222,27 @@ pub(crate) fn null_space(m: &[f64], rows: usize, cols: usize) -> (usize, Vec<Vec
(rank, basis)
}
/// Weighted normal matrix J W⁻¹ Jᵀ. Most constraint rows depend on only a few free coordinates.
fn normal_matrix(jac: &[f64], inverse_weights: &[f64], rows: usize) -> Vec<f64> {
let mut matrix = vec![0.0; rows * rows];
let mut terms = Vec::new();
let width = inverse_weights.len();
for (i, row) in jac.chunks_exact(width).enumerate() {
terms.clear();
terms.extend(row.iter().enumerate().filter(|(_, value)| **value != 0.0).map(|(col, &value)| (col, value, inverse_weights[col])));
for (k, other) in jac.chunks_exact(width).enumerate().skip(i) {
let sum = if terms.len() == width {
row.iter().zip(other).zip(inverse_weights).fold(0.0, |sum, ((&v, &other_v), &weight)| sum + v * other_v * weight)
} else {
terms.iter().fold(0.0, |sum, &(col, v, weight)| sum + v * other[col] * weight)
};
matrix[i * rows + k] = sum;
matrix[k * rows + i] = sum;
}
}
matrix
}
/// Run the solver from `x0`. Only `free` parameters change.
pub(crate) fn solve(f: &dyn Fn(&[f64], &mut Vec<f64>), x0: &[f64], free: &[usize], weights: &[f64], tol: f64, max_iter: usize) -> Outcome {
let mut x = x0.to_vec();
@@ -243,22 +264,7 @@ pub(crate) fn solve(f: &dyn Fn(&[f64], &mut Vec<f64>), x0: &[f64], free: &[usize
while iter < max_iter {
iter += 1;
let jac = jacobian(f, &x, free, rows);
// A = J W⁻¹ Jᵀ
let mut a = vec![0.0; rows * rows];
for i in 0..rows {
for k in i..rows {
let mut s = 0.0;
for (c, w) in winv.iter().enumerate() {
s += jac.get(i * nf + c).copied().unwrap_or(0.0) * jac.get(k * nf + c).copied().unwrap_or(0.0) * w;
}
if let Some(v) = a.get_mut(i * rows + k) {
*v = s;
}
if let Some(v) = a.get_mut(k * rows + i) {
*v = s;
}
}
}
let a = normal_matrix(&jac, &winv, rows);
let diag_max = (0..rows).map(|i| a.get(i * rows + i).copied().unwrap_or(0.0)).fold(0.0f64, f64::max).max(1e-12);
let mut improved = false;
for _ in 0..12 {
@@ -310,6 +316,20 @@ pub(crate) fn solve(f: &dyn Fn(&[f64], &mut Vec<f64>), x0: &[f64], free: &[usize
mod tests {
use super::*;
#[test]
fn sparse_and_dense_constraints_keep_their_weighted_cross_terms() {
// Includes an empty row, an unconstrained column in a sparse row, and a tiny derivative.
let rows = [[-0., 0., -0., -0.], [2., 0., -3., 0.], [0., 0., 0., 1e-12], [1., 3., 2., -5.]];
let weights = [1., 0.25, 0.5, 2.];
let matrix = normal_matrix(&rows.concat(), &weights, rows.len());
for (i, row) in rows.iter().enumerate() {
for (k, other) in rows.iter().enumerate() {
let reference = (0..weights.len()).fold(0.0, |sum, c| sum + row[c] * other[c] * weights[c]);
assert_eq!(matrix[i * rows.len() + k].to_bits(), reference.to_bits());
}
}
}
#[test]
fn dense_and_rank() {
let y = solve_dense(vec![2.0, 1.0, 1.0, 3.0], vec![3.0, 5.0], 2).unwrap();
+2
View File
@@ -328,6 +328,8 @@ fn invalid_references_and_purge() {
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
backwards: false,
upside_down: false,
}),
);
let bad = |d: &mut Drawing, c: Constraint| assert!(add(d, c, &SolveOptions::default()).is_err());
+11 -4
View File
@@ -46,15 +46,21 @@ mod layout;
mod proxy;
mod text;
mod wipeout;
mod xdata;
pub use xdata::{
MAX_XDATA_APP_NAME, MAX_XDATA_CHUNK, MAX_XDATA_GROUPS, MAX_XDATA_STRING, RESERVED_XDATA_APPS, XdataError, check_xdata_app_name,
check_xdata_groups, is_model_xdata_app, is_reserved_xdata_app, is_xdata_group, set_xdata_app, xdata_apps, xdata_of,
};
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal};
pub use common::{Common, Handle, Lineweight, RawTag, Transparency};
pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, PolyfaceMesh, Polyline3d, RayLine, Solid};
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
pub use fill::{Gradient, Hatch, HatchLoop};
pub use layout::{Image, Table, TableCell, Viewport};
pub use proxy::{ProxyTables, proxy_entities};
pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign};
pub use layout::{Image, Table, TableCell, Viewport, ViewportUcs};
pub use proxy::{ProxyTables, TableOrder, proxy_entities};
pub use text::{HAlign, MText, MTextBackground, MTextColumnType, MTextColumns, Text, VAlign};
pub use wipeout::Wipeout;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Unknown {
@@ -619,7 +625,8 @@ impl EntityKind {
EntityKind::Polyline3d(p) => p.points.iter().map(|q| q.xy()).collect(),
EntityKind::Spline(s) => {
if s.fit.is_empty() {
s.control.clone()
// One grip per control vertex: a closed spline's repeats have none (#3566).
s.control.iter().take(s.distinct_controls()).copied().collect()
} else {
s.fit.clone()
}
+40
View File
@@ -154,7 +154,43 @@ impl AttribProps {
#[derive(Clone, Copy, Debug)]
pub struct TagKey<'a>(pub &'a str);
#[cfg(test)]
std::thread_local! {
static TAG_CROSS_PROBE: std::cell::Cell<Option<(usize, [usize; 2])>> = const { std::cell::Cell::new(None) };
}
#[cfg(test)]
fn record_tag_cross_probe(left: &str, right: &str) {
TAG_CROSS_PROBE.with(|probe| {
let Some((position, mut counts)) = probe.get() else { return };
match (left.as_bytes().get(position), right.as_bytes().get(position)) {
(Some(b'A'), Some(b'D')) => counts[0] += 1,
(Some(b'D'), Some(b'A')) => counts[1] += 1,
_ => return,
}
probe.set(Some((position, counts)));
});
}
impl TagKey<'_> {
/// Count comparisons in both directions between the A and D fixture tag sets.
#[cfg(test)]
pub(crate) fn with_cross_probes<T>(position: usize, f: impl FnOnce() -> T) -> (T, [usize; 2]) {
struct Restore(Option<(usize, [usize; 2])>);
impl Drop for Restore {
fn drop(&mut self) {
TAG_CROSS_PROBE.with(|probe| probe.set(self.0));
}
}
TAG_CROSS_PROBE.with(|probe| {
let _restore = Restore(probe.replace(Some((position, [0; 2]))));
let value = f();
(value, probe.get().map_or([0; 2], |(_, counts)| counts))
})
}
/// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case`
/// finds equal.
fn folded(&self) -> impl Iterator<Item = u8> + '_ {
@@ -164,6 +200,8 @@ impl TagKey<'_> {
impl PartialEq for TagKey<'_> {
fn eq(&self, other: &Self) -> bool {
#[cfg(test)]
record_tag_cross_probe(self.0, other.0);
self.0.eq_ignore_ascii_case(other.0)
}
}
@@ -172,6 +210,8 @@ impl Eq for TagKey<'_> {}
impl Ord for TagKey<'_> {
fn cmp(&self, other: &Self) -> Ordering {
#[cfg(test)]
record_tag_cross_probe(self.0, other.0);
self.folded().cmp(other.folded())
}
}
+3 -2
View File
@@ -7,8 +7,9 @@ pub struct HatchLoop {
pub vertices: Vec<PolyVertex>,
#[serde(default)]
pub outer: bool,
/// Original DXF group 92 bits. Writing keeps only Derived (4), Textbox (8) and
/// Outermost (16), derives External (1) from `outer`, and sets Polyline (2).
/// Original DXF group 92 bits. Writing keeps only Textbox (8) and Outermost (16), derives
/// External (1) from `outer`, and sets Polyline (2). Derived (4) stays here but is not
/// written: the pixel size (group 47) it needs is not kept (#3664).
/// None uses the flags of a locally created loop.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub boundary_flags: Option<i64>,
+38 -1
View File
@@ -1,6 +1,6 @@
use cadcraft_geom::Mat3;
use super::common::Handle;
use super::common::{Handle, RawTag};
use super::{Color, Deserialize, Serialize, Vec2, Vec3, standard, yes};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -27,6 +27,19 @@ pub struct Viewport {
/// Display on (MVIEW ON/OFF). An off viewport shows its border but no model space.
#[serde(default = "yes")]
pub on: bool,
/// The viewport's own UCS (DXF groups 110–112, 79, 146, 345, 346), the one it keeps while
/// `ucs_per_viewport` is set.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ucs: Option<ViewportUcs>,
/// UCS per viewport (UCSVP, DXF group 71): the viewport keeps its own UCS instead of
/// following the current one.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub ucs_per_viewport: bool,
/// The viewport's groups CADCraft doesn't model (snap, grid, lens and clipping, render mode,
/// plot style sheet, shade plot, visual style, background, lighting…), as read: written back
/// on save and carried by copies, their references pointed at what they named.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub extra: Vec<RawTag>,
/// The view twist (DVIEW TWist inside the viewport; DXF group 51): radians counterclockwise,
/// the model view seen through the viewport is turned on the sheet by it. 0 is untwisted.
#[serde(default, skip_serializing_if = "is_zero_twist")]
@@ -62,6 +75,27 @@ impl Viewport {
}
}
/// A layout viewport's own UCS.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ViewportUcs {
pub origin: Vec3,
pub x_axis: Vec3,
pub y_axis: Vec3,
/// Elevation (DXF group 146).
#[serde(default)]
pub elevation: f64,
/// Orthographic type (DXF group 79): 0 none, 1 top, 2 bottom, 3 front, 4 back, 5 left, 6 right.
#[serde(default)]
pub ortho: u8,
/// The named UCS it is, by UCS table name (DXF group 345).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub named: Option<String>,
/// The UCS an orthographic one is based on, by UCS table name (DXF group 346); none: the WCS.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub base: Option<String>,
}
impl Default for Viewport {
fn default() -> Self {
Viewport {
@@ -76,6 +110,9 @@ impl Default for Viewport {
layer_colors: Vec::new(),
clip: None,
on: true,
ucs: None,
ucs_per_viewport: false,
extra: Vec::new(),
twist: 0.0,
}
}
+390 -82
View File
@@ -35,6 +35,36 @@ pub struct ProxyTables {
pub styles: Vec<(String, String)>,
}
/// The LAYER and LTYPE names the indices of proxy graphics count in, in table order (the
/// linetypes without ByBlock and ByLayer, as in [`ProxyTables`]).
#[derive(Clone, Copy, Debug, Default)]
pub struct TableOrder<'a> {
pub layers: &'a [String],
pub linetypes: &'a [String],
}
/// The chunk that sets the layer by its index (ATTRIBUTE_LAYER).
const LAYER_CHUNK: u32 = 16;
/// The chunk that sets the linetype by its index (ATTRIBUTE_LINETYPE).
const LINETYPE_CHUNK: u32 = 18;
/// The linetype indices that stand for ByBlock and ByLayer.
const LINETYPE_BYBLOCK: u32 = 32766;
const LINETYPE_BYLAYER: u32 = 32767;
/// The names a record's own graphics show for its table indices (`Unknown::names_by_index`).
#[derive(Default)]
struct Learned {
layers: std::collections::HashMap<u32, Option<String>>,
linetypes: std::collections::HashMap<u32, String>,
}
/// The names that stand for the table indices a record uses while it is decoded again to learn
/// them; an index without one leaves the layer, or gives ByLayer, as one past a table does.
struct Marks {
layers: std::collections::HashMap<u32, String>,
linetypes: std::collections::HashMap<u32, String>,
}
impl Unknown {
/// 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
@@ -92,21 +122,22 @@ impl Unknown {
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;
}
/// The record's groups with the table indices of its proxy graphics (ATTRIBUTE_LAYER and
/// ATTRIBUTE_LINETYPE) turned into the written tables `written`, by name; everything else as
/// read. The name of an index is the one the record's own decoded graphics use after it (so a
/// proxy copied from another drawing, or one whose layer was renamed, keeps what it shows);
/// an index no drawn entity follows takes the name from the file's tables `read` (see
/// [`crate::Drawing::proxy_layers`] and [`crate::Drawing::proxy_linetypes`]).
///
/// A layer that is gone becomes layer 0 (the proxy's own layer, as in a block); a layer 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. A linetype that is gone, or an index that names none,
/// becomes ByLayer (32767, what an index past the table means too); ByBlock (32766) and
/// ByLayer stay. The picture of a kept dimension (#3438) is rewritten too: by the tables alone
/// when the dimension draws its block instead. 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_tables(&self, read: TableOrder<'_>, written: TableOrder<'_>) -> Option<Vec<RawTag>> {
use std::collections::HashMap;
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) {
@@ -120,49 +151,72 @@ impl Unknown {
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();
// The ATTRIBUTE_LAYER (16) and ATTRIBUTE_LINETYPE (18) chunks: where each index sits.
let mut refs: Vec<(usize, u32, 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
if (kind == LAYER_CHUNK || kind == LINETYPE_CHUNK)
&& let Some(i) = u32_at(&bytes[..chunk + len], chunk + 8)
{
refs.push((chunk + 8, i));
refs.push((chunk + 8, kind, 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;
}
let of = |k: u32| -> Vec<u32> { refs.iter().filter(|r| r.1 == k).map(|r| r.2).collect() };
let learned = self.names_by_index(&bytes[..end], &of(LAYER_CHUNK), &of(LINETYPE_CHUNK), read.layers);
// 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 places = |names: &[String]| {
let mut place: HashMap<String, u32> = HashMap::new();
for (p, n) in names.iter().enumerate() {
place.entry(n.to_ascii_lowercase()).or_insert(u32::try_from(p).unwrap_or(u32::MAX));
}
place
};
let (layer_at, linetype_at) = (places(written.layers), places(written.linetypes));
let zero = layer_at.get("0").copied();
let len = |names: &[String]| u32::try_from(names.len()).unwrap_or(u32::MAX);
let layers_past = len(written.layers).max(len(read.layers));
let linetypes_past = len(written.linetypes).max(len(read.linetypes));
// Without the file's table or names from the graphics, an index can't be placed.
let known_layers = !read.layers.is_empty() || !learned.layers.is_empty();
let known_linetypes = !read.linetypes.is_empty() || !learned.linetypes.is_empty();
let layer = |i: u32| {
let name = match learned.layers.get(&i) {
Some(name) => name.as_deref(),
None => read.layers.get(i as usize).map(String::as_str),
};
match name.filter(|n| !n.is_empty()) {
Some(name) => layer_at.get(&name.to_ascii_lowercase()).copied().or(zero).unwrap_or(i),
None if i >= layers_past => i,
None => layers_past,
}
};
let linetype = |i: u32| {
if i == LINETYPE_BYBLOCK || i == LINETYPE_BYLAYER {
return i;
}
let name = learned.linetypes.get(&i).or_else(|| read.linetypes.get(i as usize)).map(String::as_str);
let by = |n: &str| n.eq_ignore_ascii_case("ByLayer") || n.eq_ignore_ascii_case("ByBlock");
match name.filter(|n| !n.is_empty() && !by(n)) {
Some(name) => linetype_at.get(&name.to_ascii_lowercase()).copied().unwrap_or(LINETYPE_BYLAYER),
None if i >= linetypes_past => i,
None => LINETYPE_BYLAYER,
}
};
let mut resolved: HashMap<(u32, u32), u32> = 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,
}
for (offset, kind, i) in refs {
let j = *resolved.entry((kind, i)).or_insert_with(|| match kind {
LAYER_CHUNK if known_layers => layer(i),
LINETYPE_CHUNK if known_linetypes => linetype(i),
_ => i,
});
if j != i {
bytes[offset..offset + 4].copy_from_slice(&j.to_le_bytes());
@@ -181,15 +235,20 @@ impl Unknown {
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.
/// The layer and linetype each index of `bytes` (the record's ATTRIBUTE_LAYER indices
/// `layers` and ATTRIBUTE_LINETYPE indices `linetypes`) stands for in this record's decoded
/// graphics: the bytes decoded again with each index `i` named `#i` give the same entities in
/// the same order, so each one's marker meets its real name. Only the indices the record uses
/// get a marker, so the work follows the chunks, not the largest index.
///
/// A layer is `None` for an index after which the graphics stay on the layer before (one past
/// the table it was read with). When the entities after an index stay on the layer before but
/// the file's LAYER table `read` names that layer at the index, it names it. An index whose
/// entities disagree is left out. Empty when the graphics don't match (not decoded from these
/// bytes, such as a kept dimension's reference to its block).
fn names_by_index(&self, bytes: &[u8], layers: &[u32], linetypes: &[u32], read: &[String]) -> Learned {
use std::collections::{HashMap, HashSet};
/// What the entities after a layer index say about it.
enum Seen {
/// They are on this layer, and the ones before them weren't.
Named(String),
@@ -199,27 +258,42 @@ impl Unknown {
/// 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() {
let mut out = Learned::default();
if self.graphics.is_empty() || self.graphics.iter().any(|g| matches!(g.kind, EntityKind::Insert(_))) {
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));
let mark = |i: &u32| (*i, format!("\u{1}{i}"));
let marks = Marks {
layers: layers.iter().map(mark).collect(),
linetypes: linetypes.iter().filter(|&&i| i != LINETYPE_BYBLOCK && i != LINETYPE_BYLAYER).map(mark).collect(),
};
let marked = decode(bytes, &ProxyTables::default(), Handle(0), Some(&marks));
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 index = |name: &str| name.strip_prefix('\u{1}').and_then(|i| i.parse::<u32>().ok());
let mut seen: HashMap<u32, Seen> = HashMap::new();
let mut conflict = HashSet::new();
let mut linetype_conflict = HashSet::new();
let mut before: Option<(&str, &str)> = None;
for (m, g) in marked.iter().zip(&self.graphics) {
if let Some(i) = index(&m.common.linetype) {
match out.linetypes.get(&i) {
Some(a) if !same(a, &g.common.linetype) => {
linetype_conflict.insert(i);
}
Some(_) => {}
None => {
out.linetypes.insert(i, g.common.linetype.clone());
}
}
}
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 };
let Some(i) = index(mark) 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.
@@ -247,10 +321,19 @@ impl Unknown {
}
}
for (i, s) in seen {
if !conflict.contains(&i) {
out.insert(i, if let Seen::Named(n) = s { Some(n) } else { None });
if conflict.contains(&i) {
continue;
}
let name = match s {
Seen::Named(n) => Some(n),
// Staying on the layer before says nothing when the table names that layer here:
// the index sets it again.
Seen::Kept(n) => read.get(i as usize).filter(|r| !r.is_empty() && same(r, &n)).map(|_| n),
Seen::Keeps => None,
};
out.layers.insert(i, name);
}
out.linetypes.retain(|i, _| !linetype_conflict.contains(i));
out
}
}
@@ -261,16 +344,27 @@ impl crate::Drawing {
/// 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)));
rename_in(&mut self.proxy_layers, old, new);
self.rename_in_graphics(old, new, TableName::Layer);
}
/// Rename linetype `old` to `new` where proxy graphics use it, as
/// [`crate::Drawing::rename_proxy_layer`] does for a layer: RENAME calls it.
pub fn rename_proxy_linetype(&mut self, old: &str, new: &str) {
rename_in(&mut self.proxy_linetypes, old, new);
self.rename_in_graphics(old, new, TableName::Linetype);
}
/// Rename the graphics' `field` from `old` to `new`.
fn rename_in_graphics(&mut self, old: &str, new: &str, field: TableName) {
let uses = |e: &Entity| matches!(&e.kind, EntityKind::Unknown(u) if u.graphics.iter().any(|g| field.of(&g.common).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();
for g in &mut u.graphics {
let n = field.of_mut(&mut g.common);
if n.eq_ignore_ascii_case(old) {
*n = new.to_string();
}
}
}
};
@@ -290,6 +384,36 @@ impl crate::Drawing {
}
}
/// The table name of an entity's properties that proxy graphics set by index.
#[derive(Clone, Copy)]
enum TableName {
Layer,
Linetype,
}
impl TableName {
fn of(self, c: &Common) -> &str {
match self {
TableName::Layer => &c.layer,
TableName::Linetype => &c.linetype,
}
}
fn of_mut(self, c: &mut Common) -> &mut String {
match self {
TableName::Layer => &mut c.layer,
TableName::Linetype => &mut c.linetype,
}
}
}
/// Rename `old` to `new` in the table order `names`.
fn rename_in(names: &mut [String], old: &str, new: &str) {
for n in names.iter_mut().filter(|n| n.eq_ignore_ascii_case(old)) {
*n = new.to_string();
}
}
/// 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();
@@ -304,8 +428,14 @@ fn push_hex(out: &mut Vec<u8>, s: &str) -> bool {
/// The entities the proxy graphics `bytes` draw, all with `handle` (the proxy's): selecting one
/// selects the proxy.
pub fn proxy_entities(bytes: &[u8], tables: &ProxyTables, handle: Handle) -> Vec<Entity> {
decode(bytes, tables, handle, None)
}
/// [`proxy_entities`], with the indices in `marks` named by them instead of `tables`.
fn decode(bytes: &[u8], tables: &ProxyTables, handle: Handle, marks: Option<&Marks>) -> Vec<Entity> {
let mut r = Decoder {
tables,
marks,
handle,
pen: Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..Common::default() },
fill: false,
@@ -327,6 +457,8 @@ pub fn proxy_entities(bytes: &[u8], tables: &ProxyTables, handle: Handle) -> Vec
struct Decoder<'a> {
tables: &'a ProxyTables,
/// Names standing for the indices while a record is decoded again (`Unknown::names_by_index`).
marks: Option<&'a Marks>,
handle: Handle,
/// Layer, colour, linetype and lineweight for the entities that follow.
pen: Common,
@@ -427,18 +559,26 @@ impl Decoder<'_> {
}
// 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)).filter(|n| !n.is_empty()) {
LAYER_CHUNK => {
let name = b.u32().and_then(|i| match self.marks {
Some(m) => m.layers.get(&i),
None => self.tables.layers.get(i as usize),
});
if let Some(name) = name.filter(|n| !n.is_empty()) {
self.pen.layer = name.clone();
}
}
// ATTRIBUTE_LINETYPE: index into the linetypes other than ByBlock and ByLayer;
// 32766 is ByBlock, 32767 and anything past the table ByLayer.
18 => {
LINETYPE_CHUNK => {
if let Some(i) = b.u32() {
let name = match self.marks {
Some(m) => m.linetypes.get(&i),
None => self.tables.linetypes.get(i as usize),
};
self.pen.linetype = match i {
32766 => "ByBlock".into(),
_ => self.tables.linetypes.get(i as usize).filter(|n| !n.is_empty()).cloned().unwrap_or_else(|| "ByLayer".into()),
LINETYPE_BYBLOCK => "ByBlock".into(),
_ => name.filter(|n| !n.is_empty()).cloned().unwrap_or_else(|| "ByLayer".into()),
};
}
}
@@ -596,6 +736,15 @@ impl Decoder<'_> {
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());
// A sweep too short for an arc or an elliptical arc to hold (it would read as a full
// turn): the chord between its ends.
if (a1 - a0).abs() <= cadcraft_geom::EPS {
let (p, q) = (on(a0), on(a1));
if p != q && p.is_finite() && q.is_finite() {
self.push(EntityKind::Line(Line { a: p.to3(0.0), b: q.to3(0.0) }));
}
return;
}
if round(u * r, v * r).is_some() {
return self.arc_3p(on(a0), on((a0 + a1) / 2.0), on(a1));
}
@@ -730,6 +879,8 @@ impl Decoder<'_> {
style,
halign: Default::default(),
valign: Default::default(),
backwards: false,
upside_down: false,
}));
}
}
@@ -767,6 +918,13 @@ fn round(u: Vec2, v: Vec2) -> Option<f64> {
/// 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};
// Conjugate radii on one line (a plane seen edge-on, also through an exact quarter turn,
// whose cosine leaves a tiny minor axis), relative to the longer: no ellipse, the caller
// draws the line it covers.
let longer = u.len().max(v.len());
if u.cross(v).abs() <= 1e-9 * longer * longer {
return None;
}
// 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();
@@ -1299,6 +1457,155 @@ mod tests {
assert!(own.proxy_graphics_bytes().is_empty());
}
/// The layer order `names` with no linetypes.
fn layers(names: &[String]) -> TableOrder<'_> {
TableOrder { layers: names, linetypes: &[] }
}
/// A record with the graphics `g`: in its proxy data for an ACAD_PROXY_ENTITY, else in its
/// `AcDbEntity` part (a kept dimension naming block `*D1`).
fn record(dxf_type: &str, g: &[u8], graphics: Vec<Entity>) -> Unknown {
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let hex: String = g.iter().map(|b| format!("{b:02X}")).collect();
let tags = if dxf_type == "ACAD_PROXY_ENTITY" {
vec![tag(100, "AcDbProxyEntity"), tag(92, &g.len().to_string()), tag(310, &hex)]
} else {
vec![tag(100, "AcDbEntity"), tag(8, "0"), tag(92, &g.len().to_string()), tag(310, &hex), tag(100, "AcDbDimension"), tag(2, "*D1")]
};
Unknown { dxf_type: dxf_type.into(), tags, graphics }
}
fn unit_circle() -> Vec<u8> {
let mut circle = pt(0.0, 0.0);
circle.extend(1.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0));
circle
}
/// Graphics that stay on the layer before after an index don't hide that the table names the
/// index: with layers 1, then 2 and 99, then 2, then 1 and 99 before four circles (A, B, B,
/// A), the second 2 sets B again, and saving keeps all four where they are.
#[test]
fn an_index_staying_on_the_layer_its_table_names_keeps_it() {
let circle = unit_circle();
let layer = |i: u32| chunk(16, &i.to_le_bytes());
let g = graphics(&[
layer(1),
chunk(2, &circle),
layer(2),
layer(99),
chunk(2, &circle),
layer(2),
chunk(2, &circle),
layer(1),
layer(99),
chunk(2, &circle),
]);
let read: Vec<String> = ["0", "A", "B"].map(String::from).to_vec();
let tables = ProxyTables { layers: read.clone(), ..ProxyTables::default() };
let u = record("ACAD_PROXY_ENTITY", &g, proxy_entities(&g, &tables, Handle(1)));
let on = |es: &[Entity]| es.iter().map(|e| e.common.layer.clone()).collect::<Vec<_>>();
assert_eq!(on(&u.graphics), ["A", "B", "B", "A"]);
assert!(u.with_proxy_tables(layers(&read), layers(&read)).is_none(), "nothing changes for the same table");
let written: Vec<String> = ["0", "X", "A", "B"].map(String::from).to_vec();
let again = Unknown { tags: u.with_proxy_tables(layers(&read), layers(&written)).expect("remapped"), ..u.clone() };
let w = ProxyTables { layers: written, ..ProxyTables::default() };
assert_eq!(on(&proxy_entities(&again.proxy_graphics_bytes(), &w, Handle(1))), ["A", "B", "B", "A"]);
}
/// Linetype indices follow the written LTYPE table by name, as layer indices do: a linetype
/// that is gone becomes ByLayer, and ByBlock, ByLayer and an index past the table stay.
#[test]
fn linetype_indices_follow_the_written_table() {
let circle = unit_circle();
let linetype = |i: u32| chunk(18, &i.to_le_bytes());
let g = graphics(&[
linetype(2),
chunk(2, &circle),
linetype(32766),
chunk(2, &circle),
linetype(1),
chunk(2, &circle),
linetype(9),
chunk(2, &circle),
]);
let read: Vec<String> = ["Continuous", "DASHED", "HIDDEN"].map(String::from).to_vec();
let tables = ProxyTables { linetypes: read.clone(), ..ProxyTables::default() };
let u = record("ACAD_PROXY_ENTITY", &g, proxy_entities(&g, &tables, Handle(1)));
let drawn = |es: &[Entity]| es.iter().map(|e| e.common.linetype.clone()).collect::<Vec<_>>();
assert_eq!(drawn(&u.graphics), ["HIDDEN", "ByBlock", "DASHED", "ByLayer"]);
let saved = |written: &[String]| {
let tags = u.with_proxy_tables(TableOrder { layers: &[], linetypes: &read }, TableOrder { layers: &[], linetypes: written });
let again = Unknown { tags: tags.unwrap_or_else(|| u.tags.clone()), ..u.clone() };
drawn(&proxy_entities(&again.proxy_graphics_bytes(), &ProxyTables { linetypes: written.to_vec(), ..ProxyTables::default() }, Handle(1)))
};
let names = |n: &[&str]| n.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(saved(&read), ["HIDDEN", "ByBlock", "DASHED", "ByLayer"]);
assert_eq!(saved(&names(&["Continuous", "CENTER", "DASHED", "HIDDEN"])), ["HIDDEN", "ByBlock", "DASHED", "ByLayer"]);
assert_eq!(saved(&names(&["Continuous", "HIDDEN"])), ["HIDDEN", "ByBlock", "ByLayer", "ByLayer"]);
}
/// A kept dimension's picture (#3438) follows the written LAYER table too: by its decoded
/// graphics when it draws them, by the file's table when it draws its block instead.
#[test]
fn a_kept_dimensions_picture_follows_the_written_table() {
let circle = unit_circle();
let g = graphics(&[chunk(16, &2u32.to_le_bytes()), chunk(2, &circle)]);
let read: Vec<String> = ["0", "UNUSED", "A"].map(String::from).to_vec();
let written: Vec<String> = ["0", "A", "Defpoints"].map(String::from).to_vec();
let tables = ProxyTables { layers: read.clone(), ..ProxyTables::default() };
let w = ProxyTables { layers: written.clone(), ..ProxyTables::default() };
for graphics in [proxy_entities(&g, &tables, Handle(1)), vec![block_ref()]] {
let u = record("LARGE_RADIAL_DIMENSION", &g, graphics);
let again = Unknown { tags: u.with_proxy_tables(layers(&read), layers(&written)).expect("remapped"), ..u.clone() };
assert_eq!(proxy_entities(&again.proxy_graphics_bytes(), &w, Handle(1))[0].common.layer, "A");
}
// A reference to the block on another layer isn't taken for the picture (one entity as
// well): the file's table names index 2.
let elsewhere = Entity { common: Common { layer: "Defpoints".into(), ..Common::default() }, ..block_ref() };
let u = record("LARGE_RADIAL_DIMENSION", &g, vec![elsewhere]);
assert!(u.names_by_index(&g, &[2], &[], &read).layers.is_empty());
}
fn block_ref() -> Entity {
Entity {
handle: Handle(1),
common: Common::default(),
kind: EntityKind::Insert(super::super::Insert { block: "*D1".into(), ..super::super::Insert::default() }),
}
}
/// An exact quarter turn about Y shows a circle edge-on: it draws as the line it covers, not
/// as an ellipse with the minor axis the turn's cosine leaves. An arc too short for its sweep
/// to be held draws as its chord, not as a full turn, round or under an uneven matrix.
#[test]
fn quarter_turns_and_tiny_sweeps_draw_lines() {
let matrix = |m: [f64; 16]| chunk(29, &m.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>());
let (s, c) = std::f64::consts::FRAC_PI_2.sin_cos();
let turn = matrix([c, 0.0, s, 0.0, 0.0, 1.0, 0.0, 0.0, -s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0]);
let line = |es: &[Entity]| match es {
[e] => match &e.kind {
EntityKind::Line(l) => (l.a.xy(), l.b.xy()),
other => panic!("{other:?}"),
},
_ => panic!("{es:?}"),
};
let near = |p: Vec2, x: f64, y: f64| (p - Vec2::new(x, y)).len() < 1e-12;
let (a, b) = line(&proxy_entities(&graphics(&[turn, chunk(2, &unit_circle())]), &tables(), Handle(1)));
assert!(near(a, 0.0, -1.0) && near(b, 0.0, 1.0), "{a:?} {b:?}");
let sweep = 5e-10f64;
let mut tiny = pt(0.0, 0.0);
tiny.extend(1.0f64.to_le_bytes());
tiny.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
tiny.extend(pt(1.0, 0.0));
tiny.extend(sweep.to_le_bytes());
let stretch = matrix([2.0, 0.0, 0.0, 10.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]);
for (chunks, x) in [(vec![chunk(4, &tiny)], 1.0), (vec![stretch, chunk(4, &tiny)], 12.0)] {
let (a, b) = line(&proxy_entities(&graphics(&chunks), &tables(), Handle(1)));
assert!(near(a, x, 0.0) && (b - Vec2::new(x, sweep)).len() < 1e-15, "{a:?} {b:?}");
}
}
/// 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]
@@ -1318,7 +1625,7 @@ mod tests {
};
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 tags = u.with_proxy_tables(layers(&read), layers(&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,
@@ -1328,8 +1635,8 @@ mod tests {
}
/// 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.
/// the index before it (3) look contradictory when that one comes again, and a large index
/// is found like any other.
#[test]
fn indices_are_named_around_kept_layers_and_huge_indices() {
let mut circle = pt(0.0, 0.0);
@@ -1345,12 +1652,13 @@ mod tests {
}
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();
let mut learned: Vec<(u32, Option<String>)> = u.names_by_index(&g, indices, &[], &tables.layers).layers.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()))]);
// Only the indices used get a marker: 70,000 keeps the layer before, as past the table.
assert_eq!(named(&[2, 70_000]), [(2, Some("C".into())), (70_000, None)]);
// 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(&[
@@ -1368,9 +1676,9 @@ mod tests {
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");
assert!(!u.names_by_index(&g, &[4, 1, 4], &[], &tables.layers).layers.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());
assert!(u.with_proxy_tables(layers(&tables.layers), layers(&tables.layers)).is_none());
}
/// Truncated chunks, sizes past the end, huge counts and garbage draw what they can and
+28
View File
@@ -42,6 +42,13 @@ pub struct Text {
pub halign: HAlign,
#[serde(default)]
pub valign: VAlign,
/// Mirrored left to right (AutoCAD's Backwards; DXF 71 bit 2). New text takes it from its
/// style; later style changes don't change it.
#[serde(default)]
pub backwards: bool,
/// Mirrored top to bottom (AutoCAD's Upside down; DXF 71 bit 4).
#[serde(default)]
pub upside_down: bool,
}
impl Text {
@@ -83,6 +90,27 @@ pub struct MText {
/// one column.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub columns: Option<MTextColumns>,
/// Background mask (DXF 90/63/421/45); `None` when off.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub background: Option<MTextBackground>,
}
/// MTEXT background mask (DXF 90, 63/421, 45).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MTextBackground {
/// DXF group 90 bitmask: bit 1 = fill colour set, bit 2 = use drawing background colour.
pub mask: u8,
/// DXF group 63 (ACI) or 421 (true colour); `None` when using drawing background.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub color: Option<super::Color>,
/// DXF group 45 border offset factor (default 1.5, valid 1.0..=5.0).
#[serde(default = "default_bg_scale")]
pub scale: f64,
}
fn default_bg_scale() -> f64 {
1.5
}
fn attach_tl() -> u8 {
+293
View File
@@ -0,0 +1,293 @@
//! Extended entity data (xdata): the groups 1000–1071 other applications attach to an entity,
//! kept raw in [`Common::xdata`](super::Common::xdata) as whole applications, each from its
//! `1001` group on. This module reads them per application, replaces or removes one
//! application's data, and checks data that comes from outside (a command's parameters, a LISP
//! list) before it goes onto an entity: input is hostile, so codes, values, brace nesting and
//! sizes are all checked and nothing here panics.
use super::RawTag;
/// Most xdata groups one object may carry (AutoCAD allows 16 KB of xdata per object).
pub const MAX_XDATA_GROUPS: usize = 16_384;
/// Longest application name, in bytes.
pub const MAX_XDATA_APP_NAME: usize = 255;
/// Longest string value (groups 1000 and 1003), in bytes: what one DXF group holds.
pub const MAX_XDATA_STRING: usize = 255;
/// Longest binary chunk (group 1004), in bytes.
pub const MAX_XDATA_CHUNK: usize = 127;
/// Applications whose xdata CADCraft writes itself, from its own model, when a drawing is saved.
/// It is never kept as an entity's raw xdata (the reader models it) and can't be set as such:
/// a copy written beside the generated data would contradict it.
pub const RESERVED_XDATA_APPS: &[&str] = &["CADCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD"];
/// Whether `name` (any case) is one of [`RESERVED_XDATA_APPS`].
pub fn is_reserved_xdata_app(name: &str) -> bool {
let up = name.trim().to_ascii_uppercase();
RESERVED_XDATA_APPS.contains(&up.as_str())
}
/// Whether application `name`'s xdata on an entity of `kind` is written from the model rather
/// than kept raw: the [`RESERVED_XDATA_APPS`] on any entity, and `ACAD` on a dimension, whose
/// `ACAD` run (`DSTYLE`) holds its dimension-style overrides. The reader models those too, so
/// raw groups set under such a name would be dropped on save; they are refused instead.
pub fn is_model_xdata_app(name: &str, kind: &super::EntityKind) -> bool {
is_reserved_xdata_app(name) || (name.trim().eq_ignore_ascii_case("ACAD") && matches!(kind, super::EntityKind::Dimension(_)))
}
/// Why an application name or a run of xdata groups was refused.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct XdataError(pub String);
impl std::fmt::Display for XdataError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for XdataError {}
fn err<T>(msg: impl Into<String>) -> Result<T, XdataError> {
Err(XdataError(msg.into()))
}
/// Check an application name: not empty, at most [`MAX_XDATA_APP_NAME`] bytes, no control
/// characters and none of the characters a symbol table name can't hold.
pub fn check_xdata_app_name(name: &str) -> Result<(), XdataError> {
let name = name.trim();
if name.is_empty() {
return err("an xdata application name must not be empty");
}
if name.len() > MAX_XDATA_APP_NAME {
return err(format!("an xdata application name may have at most {MAX_XDATA_APP_NAME} bytes"));
}
if name.chars().any(|c| c.is_control() || "<>/\\\":;?*|,=`".contains(c)) {
return err(format!("`{name}` is not a valid xdata application name (no control characters or <>/\\\":;?*|,=`)"));
}
Ok(())
}
/// Whether `code` is an xdata group code an application's data may hold (`1001`, the
/// application name, is not one of them: it starts an application).
pub fn is_xdata_group(code: i32) -> bool {
matches!(code, 1000 | 1002..=1005 | 1010..=1013 | 1020..=1023 | 1030..=1033 | 1040..=1042 | 1070 | 1071)
}
/// Check the groups of one application (after its `1001`): every code an xdata code with a
/// value of its kind, control strings `{` and `}` balanced, points complete (a `101x` group
/// followed by its `102x` and `103x`), at most [`MAX_XDATA_GROUPS`] groups.
pub fn check_xdata_groups(groups: &[RawTag]) -> Result<(), XdataError> {
if groups.len() > MAX_XDATA_GROUPS {
return err(format!("at most {MAX_XDATA_GROUPS} xdata groups per application"));
}
let mut depth: u32 = 0;
let mut i = 0;
while let Some(t) = groups.get(i) {
let v = t.value.trim();
match t.code {
1000 | 1003 => {
if t.value.len() > MAX_XDATA_STRING {
return err(format!("group {}: a string may have at most {MAX_XDATA_STRING} bytes", t.code));
}
if t.value.chars().any(|c| c == '\n' || c == '\r') {
return err(format!("group {}: a string may not hold a line break", t.code));
}
}
1002 => match v {
"{" => depth = depth.saturating_add(1),
"}" => match depth.checked_sub(1) {
Some(d) => depth = d,
None => return err("group 1002: a `}` without its `{`"),
},
_ => return err("group 1002 must be `{` or `}`"),
},
1004 => {
if v.len() > MAX_XDATA_CHUNK * 2 || v.len() % 2 != 0 || !v.bytes().all(|b| b.is_ascii_hexdigit()) {
return err(format!("group 1004 must be hex text of an even length, at most {MAX_XDATA_CHUNK} bytes"));
}
}
1005 => {
if v.is_empty() || v.len() > 16 || !v.bytes().all(|b| b.is_ascii_hexdigit()) {
return err("group 1005 must be a hex handle");
}
}
1010..=1013 => {
let (y, z) = (groups.get(i + 1), groups.get(i + 2));
let complete = y.is_some_and(|y| y.code == t.code + 10) && z.is_some_and(|z| z.code == t.code + 20);
if !complete {
return err(format!("group {}: a point needs its {} and {} groups", t.code, t.code + 10, t.code + 20));
}
for p in [Some(t), y, z].into_iter().flatten() {
real(p)?;
}
i += 3;
continue;
}
1020..=1023 | 1030..=1033 => return err(format!("group {} may only follow its {} group", t.code, t.code - (t.code - 1010) / 10 * 10)),
1040..=1042 => {
real(t)?;
}
1070 => {
let ok = v.parse::<i64>().is_ok_and(|n| i16::try_from(n).is_ok());
if !ok {
return err("group 1070 must be a 16-bit integer");
}
}
1071 => {
let ok = v.parse::<i64>().is_ok_and(|n| i32::try_from(n).is_ok());
if !ok {
return err("group 1071 must be a 32-bit integer");
}
}
1001 => return err("group 1001 (an application name) can't be inside an application's data"),
c => return err(format!("group {c} is not an xdata group code (1000–1071)")),
}
i += 1;
}
if depth != 0 {
return err("group 1002: a `{` without its `}`");
}
Ok(())
}
fn real(t: &RawTag) -> Result<f64, XdataError> {
match t.value.trim().parse::<f64>() {
Ok(v) if v.is_finite() => Ok(v),
_ => err(format!("group {} must be a finite number", t.code)),
}
}
/// The applications of an xdata run, in order: each name as written and its groups after the
/// `1001`. Groups before the first `1001` belong to nobody and are left out.
pub fn xdata_apps(xdata: &[RawTag]) -> Vec<(&str, &[RawTag])> {
let mut out = Vec::new();
let mut start: Option<(usize, &str)> = None;
for (i, t) in xdata.iter().enumerate() {
if t.code != 1001 {
continue;
}
if let Some((s, name)) = start.take() {
out.push((name, xdata.get(s + 1..i).unwrap_or(&[])));
}
start = Some((i, t.value.trim()));
}
if let Some((s, name)) = start {
out.push((name, xdata.get(s + 1..).unwrap_or(&[])));
}
out
}
/// The groups of application `app` (any case): those of its first run.
pub fn xdata_of<'a>(xdata: &'a [RawTag], app: &str) -> Option<&'a [RawTag]> {
xdata_apps(xdata).into_iter().find(|(name, _)| name.eq_ignore_ascii_case(app.trim())).map(|(_, g)| g)
}
/// Replace the xdata of application `app` (any case) with `groups`, or remove it (`None`, or no
/// groups). Every run of that application goes; new data is appended after the other
/// applications' data, with its `1001` group. The groups are taken as given: check them with
/// [`check_xdata_groups`] first when they come from outside.
pub fn set_xdata_app(xdata: &mut Vec<RawTag>, app: &str, groups: Option<&[RawTag]>) {
let app = app.trim();
let mut kept: Vec<RawTag> = Vec::with_capacity(xdata.len());
let mut skipping = false;
for t in xdata.drain(..) {
if t.code == 1001 {
skipping = t.value.trim().eq_ignore_ascii_case(app);
}
if !skipping {
kept.push(t);
}
}
if let Some(groups) = groups.filter(|g| !g.is_empty()) {
kept.push(RawTag { code: 1001, value: app.to_string() });
kept.extend(groups.iter().cloned());
}
*xdata = kept;
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
fn t(code: i32, value: &str) -> RawTag {
RawTag { code, value: value.into() }
}
#[test]
fn apps_are_split_at_their_names() {
let x = vec![t(1001, "A"), t(1000, "one"), t(1070, "1"), t(1001, "b"), t(1000, "two")];
let apps = xdata_apps(&x);
assert_eq!(apps.len(), 2);
assert_eq!(apps[0].0, "A");
assert_eq!(apps[0].1.len(), 2);
assert_eq!(apps[1], ("b", &x[4..]));
assert_eq!(xdata_of(&x, "B"), Some(&x[4..]));
assert_eq!(xdata_of(&x, "c"), None);
assert!(xdata_apps(&[t(1000, "stray")]).is_empty());
}
#[test]
fn set_replaces_removes_and_appends() {
let mut x = vec![t(1001, "A"), t(1000, "one"), t(1001, "B"), t(1000, "two"), t(1001, "a"), t(1000, "dup")];
set_xdata_app(&mut x, "a", Some(&[t(1070, "7")]));
assert_eq!(x, vec![t(1001, "B"), t(1000, "two"), t(1001, "a"), t(1070, "7")]);
set_xdata_app(&mut x, "B", None);
assert_eq!(x, vec![t(1001, "a"), t(1070, "7")]);
set_xdata_app(&mut x, "C", Some(&[]));
assert_eq!(x.len(), 2);
set_xdata_app(&mut x, "A", None);
assert!(x.is_empty());
}
#[test]
fn checks_accept_every_kind_and_refuse_bad_data() {
let good = vec![
t(1000, "text"),
t(1002, "{"),
t(1003, "Layer"),
t(1004, "DEADBEEF"),
t(1005, "1A2"),
t(1010, "1.5"),
t(1020, "2"),
t(1030, "0"),
t(1040, "2.5"),
t(1041, "1e3"),
t(1042, "-1"),
t(1070, "32767"),
t(1071, "2147483647"),
t(1002, "}"),
];
assert_eq!(check_xdata_groups(&good), Ok(()));
for bad in [
vec![t(1002, "}")],
vec![t(1002, "{")],
vec![t(1002, "x")],
vec![t(1001, "APP")],
vec![t(999, "comment")],
vec![t(8, "layer")],
vec![t(1010, "1"), t(1020, "2")],
vec![t(1020, "2")],
vec![t(1010, "nan"), t(1020, "2"), t(1030, "3")],
vec![t(1040, "inf")],
vec![t(1040, "x")],
vec![t(1070, "40000")],
vec![t(1071, "3000000000")],
vec![t(1004, "ABC")],
vec![t(1004, "XY")],
vec![t(1005, "")],
vec![t(1005, "zz")],
vec![t(1000, &"x".repeat(256))],
vec![t(1000, "a\nb")],
vec![t(1000, "x"); MAX_XDATA_GROUPS + 1],
] {
assert!(check_xdata_groups(&bad).is_err(), "{:?}", bad.first());
}
assert_eq!(check_xdata_app_name("PE_URL"), Ok(()));
assert_eq!(check_xdata_app_name("My App-1.0$"), Ok(()));
for bad in ["", " ", "a*b", "a\tb", "x/y", &"n".repeat(256)] {
assert!(check_xdata_app_name(bad).is_err(), "{bad:?}");
}
assert!(is_reserved_xdata_app("cadcraft") && !is_reserved_xdata_app("ACAD"));
}
}
+507 -43
View File
@@ -242,27 +242,126 @@ pub fn ole_frame_accepts(m: &cadcraft_geom::Mat3) -> bool {
m.b.abs() < t && m.c.abs() < t && m.a > 0.0 && (m.a - m.d).abs() <= t
}
/// Bounds of a single-line TEXT / ATTDEF / ATTRIB of `len` characters, following its justification
/// the same way the renderer places it (the stroke font is about 0.88 of the height per character).
/// How many characters a single-line text value draws, as the fonts read it: a `%%` code is the
/// one character it stands for (`%%d`, `%%p`, `%%c`, `%%%`, `%%nnn`) or none (the underline and
/// overline toggles `%%u` and `%%o`), `\U+XXXX` is one character, and invisible formatting
/// characters (joiners, directional marks) take no room.
fn drawn_chars(value: &str) -> usize {
let invisible = |c: char| matches!(c, '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2060}'..='\u{2069}' | '\u{FEFF}' | '\u{061C}');
let chars: Vec<char> = value.chars().collect();
let (mut i, mut drawn) = (0usize, 0usize);
while let Some(&c) = chars.get(i) {
let escaped = (c == '\\' && matches!(chars.get(i + 1), Some('U' | 'u')) && chars.get(i + 2) == Some(&'+'))
.then(|| chars.get(i + 3..i + 7))
.flatten()
.filter(|hex| hex.iter().all(char::is_ascii_hexdigit))
.and_then(|hex| u32::from_str_radix(&hex.iter().collect::<String>(), 16).ok())
.and_then(char::from_u32);
if let Some(u) = escaped {
drawn += usize::from(!invisible(u));
i += 7;
} else if c == '%' && chars.get(i + 1) == Some(&'%') {
match chars.get(i + 2).map_or(' ', char::to_ascii_lowercase) {
'u' | 'o' => i += 3,
'd' | 'p' | 'c' | '%' => (drawn, i) = (drawn + 1, i + 3),
digit if digit.is_ascii_digit() => {
let digits = chars.iter().skip(i + 2).take(3).take_while(|d| d.is_ascii_digit()).count();
(drawn, i) = (drawn + 1, i + 2 + digits);
}
// Not a code: the percent sign is drawn, and the next one is read again.
_ => (drawn, i) = (drawn + 1, i + 1),
}
} else {
drawn += usize::from(!invisible(c));
i += 1;
}
}
drawn
}
/// Bounds of a single-line TEXT / ATTDEF / ATTRIB of `len` drawn characters, following its
/// justification the same way the renderer places it (the stroke font is about 0.88 of the height
/// per character). Empty when nothing is drawn.
fn text_box(t: &crate::Text, len: usize) -> Bounds2 {
use crate::{HAlign, VAlign};
let w = t.height * 0.9 * t.width_factor.abs().max(0.01) * len.max(1) as f64;
if len == 0 {
return Bounds2::EMPTY;
}
let natural = t.height * 0.9 * t.width_factor.abs().max(0.01) * len as f64;
// Justified text (TL, ML and BL too) hangs from its alignment point (DXF group 11).
let origin = t.justify_point();
// Aligned and Fit text span their two points (groups 10 and 11) whatever rotation is stored:
// the line runs from the first to the second, Fit at its own height with its width stretched,
// Aligned at the height that keeps its proportions. With no second point, or one on the
// first, they are placed like left-justified text, as the renderer places them.
let second = t.align_pt.map(|p| p.xy()).filter(|_| matches!(t.halign, HAlign::Aligned | HAlign::Fit));
let span = second.map(|p| origin.dist(p)).filter(|d| d.is_finite() && *d > 1e-12);
// The fonts shape with the width factor as it is, not floored like the fallback width above,
// with 1 when it is unusable, and with a height of 1 when the height is.
let usable = t.width_factor.is_finite() && t.width_factor.abs() > 1e-6;
let wf = if usable { t.width_factor.abs() } else { 1.0 };
let height = if t.height.is_finite() && t.height > 0.0 { t.height } else { 1.0 };
let shaped = height * 0.9 * wf * len as f64;
// Fit text is stretched by scaling its width factor by span / shaped width and shaping again.
// When the scaled factor is one the fonts cannot use (the stored one is, or the span is a tiny
// part of the text's width), the text is not stretched: it is drawn at a factor of 1.
// The shaped width here is an estimate, and the fonts decide by their own: it is taken to be
// within this factor of the estimate. Where the fonts decide by a cutoff, the box is the larger
// of the two outcomes unless the estimate is clear of the cutoff by this factor.
const MARGIN: f64 = 4.0;
let fits = |d: f64| {
let fitted = wf * d / shaped;
usable && fitted.is_finite() && fitted > 1e-6 * MARGIN
};
let unstretched = height * 0.9 * len as f64;
// The fonts leave a line of next to no width as it is, neither stretched nor scaled: the same
// cutoff as theirs, with no margin, since a box scaled for text that is left alone is
// enormous.
let no_width = shaped <= 1e-12;
// Aligned text is scaled by span / shaped width, so the narrower the line, the taller it is
// drawn. The least width the stroke font gives a line: its narrowest characters are 1 unit
// wide on a cap height of 6, with 1.6 units between characters. The height from that width
// holds whatever the line is made of, also shrunk into a span shorter than its width.
let narrowest = height * wf * (2.6 * len as f64 - 1.6) / 6.0;
// The most width it gives one (its widest characters are 4 units wide), for the least height
// the line can be drawn at.
let widest = height * wf * (5.6 * len as f64 - 1.6) / 6.0;
// Width, the most and the least height the line is drawn at, and its direction.
let (w, h, low, rotation) = match (span, second) {
(Some(_), Some(p)) if no_width => (shaped, height, height, origin.angle_to(p)),
// Unstretched is the larger outcome: a span this near the cutoff is far shorter than the text.
(Some(d), Some(p)) if t.halign == HAlign::Fit && !fits(d) => (unstretched, height, height, origin.angle_to(p)),
(Some(d), Some(p)) if t.halign == HAlign::Fit => (d, height, height, origin.angle_to(p)),
(Some(d), Some(p)) => (d, height * d / narrowest, height * d / widest, origin.angle_to(p)),
_ => (natural, t.height, t.height, t.rotation),
};
let dx = match t.halign {
HAlign::Left | HAlign::Aligned | HAlign::Fit => 0.0,
HAlign::Center | HAlign::Middle => -w / 2.0,
HAlign::Right => -w,
};
let dy = match (t.halign, t.valign) {
(HAlign::Middle, _) => -t.height / 2.0,
(_, VAlign::Baseline) => 0.0,
(_, VAlign::Bottom) => t.height / 3.0,
(_, VAlign::Middle) => -t.height / 2.0,
(_, VAlign::Top) => -t.height,
// The box from its bottom to its top. Bottom justification lifts the line by a third of the
// height it is drawn at: the box starts where the shortest line would and ends where the
// tallest would.
let (y0, y1) = match (t.halign, t.valign) {
(HAlign::Middle, _) | (_, VAlign::Middle) => (-h / 2.0, h / 2.0),
(_, VAlign::Baseline) => (0.0, h),
(_, VAlign::Bottom) => (low / 3.0, h / 3.0 + h),
(_, VAlign::Top) => (-h, 0.0),
};
let local = [Vec2::new(dx, dy), Vec2::new(dx + w, dy), Vec2::new(dx + w, dy + t.height), Vec2::new(dx, dy + t.height)];
Bounds2::from_points(local.map(|p| origin + p.rotate(t.rotation)))
let local = [Vec2::new(dx, y0), Vec2::new(dx + w, y0), Vec2::new(dx + w, y1), Vec2::new(dx, y1)];
// Backwards and upside-down text is mirrored about the point it is placed by.
let (mx, my) = (if t.backwards { -1.0 } else { 1.0 }, if t.upside_down { -1.0 } else { 1.0 });
Bounds2::from_points(local.map(|p| origin + Vec2::new(p.x * mx, p.y * my).rotate(rotation)))
}
/// Whether `e` is a point on the layer Defpoints (the name in any case), as the block of a
/// dimension holds the dimension's definition points. The reference app selects a dimension and a
/// block reference by such a point of its block whatever a viewport freezes, the layer Defpoints
/// too, where a line on that layer follows the viewport. So a selection through a viewport counts
/// such a part of a block ([`ViewportBounds`]); the viewport itself does not draw it.
pub fn point_on_defpoints(e: &Entity) -> bool {
matches!(e.kind, EntityKind::Point(_)) && e.common.layer.eq_ignore_ascii_case("Defpoints")
}
/// Whether an entity inside a block definition shows: its own invisible flag and its layer count,
@@ -270,16 +369,27 @@ fn text_box(t: &crate::Text, len: usize) -> Bounds2 {
/// entities a visibility state hides are invisible this way, and they sit far from the block's
/// geometry in real drawings. Layer "0" takes the insert's layer, which the caller has checked.
/// `off_counts`: a layer turned off counts too, as in the drawing's extents ([`extent_bounds`]).
fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool) -> bool {
/// `frozen`: the layers frozen in the layout viewport measured through ([`ViewportBounds`]); a
/// point on the layer Defpoints counts whatever that viewport freezes ([`point_on_defpoints`]).
fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool, frozen: &[String]) -> bool {
let frozen: &[String] = if point_on_defpoints(e) { &[] } else { frozen };
// Attribute definitions are not drawn in an insert (its attribs are, see below), except
// constant ones, which the insert's bounds add on their own.
!matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts)
!matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts, frozen)
}
/// Whether what lies on `layer` inside an insert counts: layer "0" takes the insert's layer, which
/// the caller has checked; a frozen layer never counts, one turned off only with `off_counts`.
fn layer_counts(d: &Drawing, layer: &str, off_counts: bool) -> bool {
layer == "0" || d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts))
/// Nor does one of the layers in `frozen`, those frozen in the layout viewport measured through,
/// which does not draw them (the names compared as the renderer compares them).
fn layer_counts(d: &Drawing, layer: &str, off_counts: bool, frozen: &[String]) -> bool {
layer == "0" || (d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts)) && !frozen_in(frozen, layer))
}
/// Whether `layer` is one of the layers in `frozen`, those frozen in a layout viewport (the names
/// compared as the renderer compares them).
fn frozen_in(frozen: &[String], layer: &str) -> bool {
frozen.iter().any(|f| f.eq_ignore_ascii_case(layer))
}
/// The layer an insert's attribute draws on, as the renderer takes it: its own, else its
@@ -313,13 +423,18 @@ impl Contents<'_> {
}
}
/// [`Contents`] of `blk` referenced at `depth`, measured once and kept in `blocks`.
/// [`Contents`] of `blk` referenced at `depth`, measured once and kept in `blocks`: the parts that
/// count there ([`in_block_visible`], and a constant value by its layer as [`layer_counts`] says),
/// so those on a layer in `frozen` are left out ([`bounds_in`] says what the maps hold and why the
/// depth is part of the key).
fn contents<'a, 'm>(
d: &'a Drawing,
blk: &'a crate::Block,
depth: usize,
blocks: &'m mut HashMap<(&'a str, usize), Contents<'a>>,
in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>,
off_counts: bool,
frozen: &[String],
) -> Option<&'m Contents<'a>> {
let key = (blk.name.as_str(), depth);
if !blocks.contains_key(&key) {
@@ -334,11 +449,13 @@ fn contents<'a, 'm>(
&& attmode != 0
&& (!a.invisible || attmode == 2)
&& be.common.visible
&& layer_counts(d, &be.common.layer, off_counts) =>
&& layer_counts(d, &be.common.layer, off_counts, frozen) =>
{
c.constants.push((a.tag.as_str(), constant_box(a, be.common.matches_layout_orientation())));
}
_ if in_block_visible(d, be, off_counts) => c.geometry = c.geometry.union(&bounds_in(d, be, depth + 1, blocks, off_counts)),
_ if in_block_visible(d, be, off_counts, frozen) => {
c.geometry = c.geometry.union(&bounds_in(d, be, depth + 1, blocks, in_drawing, off_counts, frozen));
}
_ => {}
}
}
@@ -347,13 +464,27 @@ fn contents<'a, 'm>(
blocks.get(&key)
}
/// [`Contents`] of the block `blk`, referenced at `depth`, as the drawing shows them: no viewport's
/// frozen layers are left out. For a clipped reference measured through a viewport ([`bounds_in`]).
/// `in_drawing` keeps them, apart from that viewport's own block bounds.
fn drawing_contents<'a, 'm>(
d: &'a Drawing,
blk: &'a crate::Block,
depth: usize,
off_counts: bool,
in_drawing: &'m mut HashMap<(&'a str, usize), Contents<'a>>,
) -> Option<&'m Contents<'a>> {
// With no layer left out, the measure never asks for the drawing's boxes itself.
contents(d, blk, depth, in_drawing, &mut HashMap::new(), off_counts, &[])
}
/// The box of a constant attribute definition's value, as a block reference draws it: upright
/// when the definition matches the layout's orientation, like other text (#2498).
fn constant_box(a: &crate::Attrib, upright: bool) -> Bounds2 {
let turn = |r: f64| if upright { 0.0 } else { r };
match a.multiline_text() {
Some(m) if !blank(&m.contents) => mtext_box(&crate::MText { rotation: turn(m.rotation), ..m }),
None if !blank(&a.text.value) => text_box(&crate::Text { rotation: turn(a.text.rotation), ..a.text.clone() }, a.text.value.chars().count()),
None if !blank(&a.text.value) => text_box(&crate::Text { rotation: turn(a.text.rotation), ..a.text.clone() }, drawn_chars(&a.text.value)),
_ => Bounds2::EMPTY,
}
}
@@ -394,13 +525,13 @@ fn mtext_box(t: &crate::MText) -> Bounds2 {
/// The box of what `e` draws (block contents on layers turned off left out).
pub fn entity_bounds(d: &Drawing, e: &Entity, depth: usize) -> Bounds2 {
bounds_of(d, e, depth, false, &mut HashMap::new())
bounds_of(d, e, depth, false, &[], &mut HashMap::new(), &mut HashMap::new())
}
/// The box `e` takes in the drawing's extents: as [`entity_bounds`], but block contents on a layer
/// turned off count, as AutoCAD 2024's ZOOM Extents counts them (a frozen layer's do not).
pub fn extent_bounds(d: &Drawing, e: &Entity) -> Bounds2 {
bounds_of(d, e, 0, true, &mut HashMap::new())
bounds_of(d, e, 0, true, &[], &mut HashMap::new(), &mut HashMap::new())
}
/// The bounds of block contents measured so far, kept across the entities of one unchanged
@@ -418,35 +549,95 @@ pub struct BlockBoundsCache<'a> {
/// [`entity_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`.
pub fn entity_bounds_cached<'a>(d: &'a Drawing, e: &Entity, depth: usize, cache: &mut BlockBoundsCache<'a>) -> Bounds2 {
bounds_of(d, e, depth, false, &mut cache.drawn)
bounds_of(d, e, depth, false, &[], &mut cache.drawn, &mut HashMap::new())
}
/// [`extent_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`.
pub fn extent_bounds_cached<'a>(d: &'a Drawing, e: &Entity, cache: &mut BlockBoundsCache<'a>) -> Bounds2 {
bounds_of(d, e, 0, true, &mut cache.extents)
bounds_of(d, e, 0, true, &[], &mut cache.extents, &mut HashMap::new())
}
fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blocks: &mut HashMap<(&'a str, usize), Contents<'a>>) -> Bounds2 {
/// The boxes of what one layout viewport draws: [`entity_bounds`] with the block contents on the
/// layers frozen in that viewport left out, as the viewport leaves them out when it draws. It
/// keeps the block bounds it has measured, as a [`BlockBoundsCache`] does, so use one only while
/// the drawing it measured is unchanged. The layers belong to it, so the bounds measured through
/// one viewport never answer for another. Two things a selection counts whatever the viewport
/// draws stay in: a clipped reference (XCLIP) is selected by its boundary, so it keeps the box the
/// drawing gives it, and a dimension by its definition points, which its block holds as points on
/// the layer Defpoints, so such a point counts in any block ([`point_on_defpoints`]).
pub struct ViewportBounds<'a> {
/// The layers frozen in the viewport.
frozen: &'a [String],
/// By block name and depth, the box of the block contents the viewport draws.
blocks: HashMap<(&'a str, usize), Contents<'a>>,
/// The same with no layer of the viewport left out: the box the drawing gives the contents,
/// which a clipped reference keeps.
in_drawing: HashMap<(&'a str, usize), Contents<'a>>,
}
impl<'a> ViewportBounds<'a> {
/// For a viewport that freezes the layers in `frozen` (none: the drawing as it shows anywhere).
pub fn new(frozen: &'a [String]) -> Self {
ViewportBounds { frozen, blocks: HashMap::new(), in_drawing: HashMap::new() }
}
/// The layers frozen in the viewport.
pub fn frozen(&self) -> &'a [String] {
self.frozen
}
/// Whether the viewport leaves `part` out for its layer. `part` is an entity of the block
/// that an object the viewport draws is drawn from (a block reference, a dimension, a
/// multileader), and it is left out when its layer is frozen in the viewport, as in the
/// boxes above. A part on layer 0 never is: it takes the layer of the object, which the
/// caller has checked. What the drawing itself hides (a layer frozen for the whole drawing
/// or turned off) is not looked at here.
pub fn leaves_out(&self, part: &Entity) -> bool {
part.common.layer != "0" && frozen_in(self.frozen, &part.common.layer)
}
/// The box of what the viewport draws of `e`. Like [`entity_bounds`] it does not look at the
/// layer `e` itself is on: whether the viewport draws `e` at all is the caller's to check.
pub fn entity_bounds(&mut self, d: &'a Drawing, e: &Entity) -> Bounds2 {
bounds_of(d, e, 0, false, self.frozen, &mut self.blocks, &mut self.in_drawing)
}
}
/// The box of `e` at `depth` with the block bounds in `blocks` and `in_drawing`: [`bounds_in`], a
/// top-level annotative object measured as it draws.
fn bounds_of<'a>(
d: &'a Drawing,
e: &Entity,
depth: usize,
off_counts: bool,
frozen: &[String],
blocks: &mut HashMap<(&'a str, usize), Contents<'a>>,
in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>,
) -> Bounds2 {
// A top-level annotative object measures as it draws at the current annotation scale.
if depth == 0 {
match d.anno_draw(e) {
crate::AnnoDraw::Plain => {}
crate::AnnoDraw::Hidden => return Bounds2::EMPTY,
crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, off_counts),
crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, in_drawing, off_counts, frozen),
}
}
bounds_in(d, e, depth, blocks, off_counts)
bounds_in(d, e, depth, blocks, in_drawing, off_counts, frozen)
}
/// The bounds of a record kept as read that draws something: a proxy as its proxy graphics draw
/// (layer 0 in them is the proxy's layer), each at the next depth as a block's contents are, and an
/// OLE2FRAME as its frame.
/// OLE2FRAME as its frame. Measured through a viewport, the proxy graphics on a layer `frozen`
/// there are left out as a block's parts are ([`in_block_visible`]), and a reference among them
/// takes its boxes from `blocks` and `in_drawing` as any other does ([`bounds_in`]).
fn unknown_bounds<'a>(
d: &'a Drawing,
u: &crate::Unknown,
depth: usize,
blocks: &mut HashMap<(&'a str, usize), Contents<'a>>,
in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>,
off_counts: bool,
frozen: &[String],
) -> Bounds2 {
if u.graphics.is_empty() {
return ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points);
@@ -456,8 +647,8 @@ fn unknown_bounds<'a>(
}
u.graphics
.iter()
.filter(|g| in_block_visible(d, g, off_counts))
.fold(Bounds2::EMPTY, |b, g| b.union(&bounds_in(d, g, depth + 1, blocks, off_counts)))
.filter(|g| in_block_visible(d, g, off_counts, frozen))
.fold(Bounds2::EMPTY, |b, g| b.union(&bounds_in(d, g, depth + 1, blocks, in_drawing, off_counts, frozen)))
}
/// [`entity_bounds`] with the bounds of block contents (in block coordinates) already computed,
@@ -465,19 +656,29 @@ fn unknown_bounds<'a>(
/// expanding the block again, so nested or self-referencing blocks cost at most one pass over each
/// definition per depth instead of one per reference (which grows exponentially with the nesting
/// depth). The depth is part of the key because [`MAX_BLOCK_DEPTH`] cuts a deep visit short: its
/// bounds must not stand in for a shallower reference to the same block (#706).
fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<(&'a str, usize), Contents<'a>>, off_counts: bool) -> Bounds2 {
/// bounds must not stand in for a shallower reference to the same block (#706). The bounds in
/// `blocks` depend on `off_counts` and on `frozen` (see [`layer_counts`]), so one map goes with
/// one value of each. `in_drawing` is the map that goes with the same `off_counts` and no frozen
/// layer: a measure through a viewport takes from it the box the drawing gives the block of a
/// clipped reference ([`drawing_contents`]). A measure with no frozen layer does not use it.
fn bounds_in<'a>(
d: &'a Drawing,
e: &Entity,
depth: usize,
blocks: &mut HashMap<(&'a str, usize), Contents<'a>>,
in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>,
off_counts: bool,
frozen: &[String],
) -> Bounds2 {
match &e.kind {
EntityKind::Table(t) if t.is_broken() => t.bounds(),
EntityKind::Text(t) if blank(&t.value) => Bounds2::EMPTY,
EntityKind::MText(t) if blank(&t.contents) => Bounds2::EMPTY,
// Text that matches the layout's orientation is drawn upright (#2498).
EntityKind::Text(t) if e.common.matches_layout_orientation() => {
text_box(&crate::Text { rotation: 0.0, ..t.clone() }, t.value.chars().count())
}
EntityKind::Text(t) if e.common.matches_layout_orientation() => text_box(&crate::Text { rotation: 0.0, ..t.clone() }, drawn_chars(&t.value)),
EntityKind::MText(t) if e.common.matches_layout_orientation() => mtext_box(&crate::MText { rotation: 0.0, ..t.clone() }),
EntityKind::Text(t) => text_box(t, t.value.chars().count()),
EntityKind::AttDef(a) => text_box(&a.text, a.tag.chars().count()),
EntityKind::Text(t) => text_box(t, drawn_chars(&t.value)),
EntityKind::AttDef(a) => text_box(&a.text, drawn_chars(&a.tag)),
EntityKind::MText(t) => mtext_box(t),
EntityKind::Insert(ins) => {
if depth >= MAX_BLOCK_DEPTH {
@@ -490,9 +691,18 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
let mut defs = None;
if let Some(blk) = d.block(&ins.block) {
let m = ins.transform(blk.base.xy());
let c = contents(d, blk, depth, blocks, off_counts);
let c = contents(d, blk, depth, blocks, in_drawing, off_counts, frozen);
defs = c.map(|c| &c.defs);
let inner = c.map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
let mut inner = c.map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
// XCLIP: the reference app selects a clipped reference by its boundary whatever a
// viewport draws inside it, so a clipped reference keeps the box the drawing gives it.
// One that is not inverted and has a part drawn gets the boundary's box below as it is.
if !frozen.is_empty()
&& let Some(c) = ins.clip.as_ref().filter(|c| c.active())
&& (c.inverted || inner.is_empty())
{
inner = drawing_contents(d, blk, depth, off_counts, in_drawing).map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
}
b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) };
// XCLIP: the reference app takes the boundary's box, also where it reaches past the
// block or misses it (an inverted clip can show anything, so it keeps the block's).
@@ -514,10 +724,10 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
}
}
for a in &ins.attribs {
if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts) {
if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts, frozen) {
b = b.union(&match a.multiline_text() {
Some(m) => mtext_box(&m),
None => text_box(&a.text, a.text.value.chars().count()),
None => text_box(&a.text, drawn_chars(&a.text.value)),
});
}
}
@@ -551,7 +761,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
// Reuse the shared block-bounds cache (as the Insert branch does) so a dimension
// block with branching or self-referencing children costs one pass per definition
// per depth, not one per reference (which grows exponentially) (CWE-400).
let inner = contents(d, blk, depth, blocks, off_counts).map_or(Bounds2::EMPTY, |c| c.geometry);
let inner = contents(d, blk, depth, blocks, in_drawing, off_counts, frozen).map_or(Bounds2::EMPTY, |c| c.geometry);
// The block draws translated by the insertion point (group 12), so its bounds
// move with it (#2634); the cache above keeps the block's own bounds.
let off = dm.insertion_point.xy();
@@ -570,7 +780,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
}
if let Some(ins) = &m.block {
let be = Entity { handle: e.handle, common: e.common.clone(), kind: EntityKind::Insert(ins.clone()) };
b = b.union(&bounds_in(d, &be, depth, blocks, off_counts));
b = b.union(&bounds_in(d, &be, depth, blocks, in_drawing, off_counts, frozen));
}
b
}
@@ -590,7 +800,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
EntityKind::LwPolyline(p) => lwpolyline_bounds(p),
// A proxy measures as its proxy graphics draw. An OLE object's content is not drawn, but its
// frame is, so the frame counts (#2422).
EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => unknown_bounds(d, u, depth, blocks, off_counts),
EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => unknown_bounds(d, u, depth, blocks, in_drawing, off_counts, frozen),
kind => {
let mut b = Bounds2::EMPTY;
for p in kind.prims() {
@@ -682,6 +892,8 @@ mod tests {
style: "Standard".into(),
halign,
valign,
backwards: false,
upside_down: false,
}
}
@@ -701,6 +913,7 @@ mod tests {
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}
}
@@ -720,6 +933,15 @@ mod tests {
let b = bounds(EntityKind::MText(mtext("A LONG LINE OF WRAPPING TEXT", 5.0)));
assert!((b.max.x - b.min.x - 5.0).abs() < 1e-9, "width {}", b.max.x - b.min.x);
}
#[test]
fn mirrored_text_extends_the_other_way() {
let plain = bounds(EntityKind::Text(text(HAlign::Left, VAlign::Baseline)));
assert!(plain.min.x >= -1e-9 && plain.min.y >= -1e-9);
let back = bounds(EntityKind::Text(Text { backwards: true, upside_down: true, ..text(HAlign::Left, VAlign::Baseline) }));
assert!(back.max.x <= 1e-9 && back.max.y <= 1e-9, "{back:?}");
assert!((back.width() - plain.width()).abs() < 1e-9);
}
#[test]
fn right_justified_text_is_left_of_alignment_point() {
let b = bounds(EntityKind::Text(text(HAlign::Right, VAlign::Baseline)));
@@ -767,6 +989,7 @@ mod tests {
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
};
let ml = crate::MLeader {
leaders: vec![vec![Vec3::new(0.0, 0.0, 0.0)]],
@@ -874,6 +1097,247 @@ mod tests {
}
}
/// A viewport leaves a part of a block out for its layer when that layer is frozen in the
/// viewport, its name matched whatever its case. A part on layer 0 is never left out, also
/// where the viewport freezes layer 0: it takes the layer of the object drawn from the block.
/// A layer the drawing itself hides (frozen for the whole drawing, or turned off) is not the
/// viewport's to leave out, and a viewport that freezes no layer leaves nothing out.
#[test]
fn a_viewport_leaves_out_the_parts_on_its_frozen_layers() {
let part = |layer: &str| {
let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 0.0) });
let mut e = Entity::new(crate::Handle(1), kind);
e.common.layer = layer.into();
e
};
let frozen = ["hidden".to_string(), "0".to_string()];
let (through, plain) = (ViewportBounds::new(&frozen), ViewportBounds::new(&[]));
assert!(through.leaves_out(&part("Hidden")), "a layer frozen in the viewport, its name in another case");
assert!(!plain.leaves_out(&part("Hidden")), "the same part where no layer is frozen");
assert!(!through.leaves_out(&part("0")), "layer 0 takes the object's layer");
assert!(!through.leaves_out(&part("Other")), "a layer the viewport does not freeze");
}
/// Through a layout viewport the block contents on a layer frozen in it take no room: a part
/// of a reference, a part two blocks deep, a nested reference that is itself on that layer
/// (with everything in it), an attribute, the parts of the block a dimension or a multileader
/// draws (a reference nested in a dimension's block too), and the parts of an annotative
/// reference. A clipped reference (XCLIP) keeps the box the drawing gives it, whatever is drawn
/// of it. The layer's name is matched whatever its case. With no layer frozen
/// the box is the one [`entity_bounds`] gives, and one [`ViewportBounds`] gives every entity
/// the box a fresh one gives it.
#[test]
fn a_viewport_leaves_out_block_contents_on_the_layers_frozen_in_it() {
let line = |handle: u64, y: f64, layer: &str| {
let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) });
let mut e = Entity::new(crate::Handle(handle), kind);
e.common.layer = layer.into();
e
};
let reference = |block: &str| crate::Insert { block: block.into(), ..crate::Insert::default() };
let ins = |block: &str, layer: &str| {
let mut e = Entity::new(crate::Handle(2), EntityKind::Insert(reference(block)));
e.common.layer = layer.into();
e
};
let mut d = Drawing::new_metric();
d.ensure_layer("Hidden");
let mut add = |name: &str, parts: Vec<Entity>| {
let mut b = crate::Block::new(name);
for part in parts {
b.entities.push(part);
}
d.blocks.insert(name.into(), std::sync::Arc::new(b));
};
// B: a line on layer 0 along y = 0 and one on "Hidden" along y = 50. N nests B. Z holds a
// reference to B that is itself on "Hidden", and a line along y = 90. H is all on "Hidden".
add("B", vec![line(1, 0.0, "0"), line(3, 50.0, "Hidden")]);
add("N", vec![ins("B", "0")]);
add("Z", vec![ins("B", "Hidden"), line(1, 90.0, "0")]);
add("H", vec![line(1, 50.0, "Hidden")]);
// A reference to B with an attribute on "Hidden" at y = 70.
let mut tagged = ins("B", "0");
if let EntityKind::Insert(i) = &mut tagged.kind {
i.attribs.push(crate::Attrib {
tag: "T".into(),
text: Text { insert: Vec3::new(0.0, 70.0, 0.0), align_pt: None, ..text(HAlign::Left, VAlign::Baseline) },
invisible: false,
constant: false,
prompt: String::new(),
props: crate::AttribProps { layer: Some("Hidden".into()), ..Default::default() },
multiline: None,
modes: Default::default(),
});
}
// References to H clipped to a boundary around its line, and with that clip inverted: no
// part of either is drawn where "Hidden" is frozen in the viewport. And a reference to B
// with the inverted clip: its line along y = 0 is drawn there.
let clip = |block: &str, inverted: bool| {
let mut e = ins(block, "0");
if let EntityKind::Insert(i) = &mut e.kind {
let boundary = crate::ClipBoundary::new(vec![Vec2::new(-2.0, 40.0), Vec2::new(12.0, 60.0)]);
i.clip = Some(crate::ClipBoundary { inverted, ..boundary });
}
e
};
let (clipped, clipped_inverted, clipped_partly) = (clip("H", false), clip("H", true), clip("B", true));
// An annotative reference to B: measured as it draws at the annotation scale, here 1:1.
let mut scaled = ins("B", "0");
scaled.common.anno_scales = vec![crate::AnnoScale::unit()];
// Dimensions that draw B and N, and a multileader that draws B.
let dimension = |block: &str| {
let kind = EntityKind::Dimension(crate::Dimension {
kind: crate::DimKind::Aligned,
defpt: Vec3::new(5.0, 1.0, 0.0),
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::new(10.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 0.0,
text_rotation: 0.0,
user_text_pos: false,
block: Some(block.into()),
insertion_point: Vec3::ZERO,
overrides: Default::default(),
assoc: Vec::new(),
marks: Default::default(),
});
Entity::new(crate::Handle(3), kind)
};
let (dim, dim_nested) = (dimension("B"), dimension("N"));
let leader = Entity::new(
crate::Handle(4),
EntityKind::MLeader(crate::MLeader {
leaders: vec![vec![Vec3::ZERO]],
landing: Vec3::new(1.0, 0.0, 0.0),
dogleg: 0.45,
text: None,
style: "Standard".into(),
arrow_size: 1.0,
spline: false,
block: Some(reference("B")),
}),
);
let frozen = ["HIDDEN".to_string()];
let mut view = ViewportBounds::new(&frozen);
let ys = |b: Bounds2| (b.min.y, b.max.y);
assert_eq!(ys(entity_bounds(&d, &ins("B", "0"), 0)), (0.0, 50.0));
assert_eq!(ys(view.entity_bounds(&d, &ins("B", "0"))), (0.0, 0.0), "a part on the frozen layer");
assert_eq!(ys(view.entity_bounds(&d, &ins("N", "0"))), (0.0, 0.0), "a part two blocks deep");
assert_eq!(ys(entity_bounds(&d, &ins("Z", "0"), 0)), (0.0, 90.0));
assert_eq!(ys(view.entity_bounds(&d, &ins("Z", "0"))), (90.0, 90.0), "a nested reference on the frozen layer");
assert!(!entity_bounds(&d, &ins("H", "0"), 0).is_empty());
assert!(view.entity_bounds(&d, &ins("H", "0")).is_empty(), "nothing of it is drawn");
let boundary = (Vec2::new(-2.0, 40.0), Vec2::new(12.0, 60.0));
let (drawn, seen) = (entity_bounds(&d, &clipped, 0), view.entity_bounds(&d, &clipped));
assert_eq!((drawn.min, drawn.max), boundary);
assert_eq!((seen.min, seen.max), boundary, "a clipped reference no part of which is drawn keeps its boundary");
assert_eq!(ys(entity_bounds(&d, &clipped_inverted, 0)), (50.0, 50.0));
assert_eq!(ys(view.entity_bounds(&d, &clipped_inverted)), (50.0, 50.0), "and one clipped the other way its block's box");
assert_eq!(ys(entity_bounds(&d, &clipped_partly, 0)), (0.0, 50.0));
assert_eq!(ys(view.entity_bounds(&d, &clipped_partly)), (0.0, 50.0), "with a part drawn too");
assert!(entity_bounds(&d, &tagged, 0).max.y >= 70.0);
assert_eq!(ys(view.entity_bounds(&d, &tagged)), (0.0, 0.0), "an attribute on the frozen layer");
assert_eq!(ys(entity_bounds(&d, &scaled, 0)), (0.0, 50.0));
assert_eq!(ys(view.entity_bounds(&d, &scaled)), (0.0, 0.0), "an annotative reference");
assert_eq!(entity_bounds(&d, &dim, 0).max.y, 50.0);
assert!(view.entity_bounds(&d, &dim).max.y < 50.0, "the block a dimension draws");
assert_eq!(entity_bounds(&d, &dim_nested, 0).max.y, 50.0);
assert!(view.entity_bounds(&d, &dim_nested).max.y < 50.0, "a reference nested in the block a dimension draws");
assert_eq!(entity_bounds(&d, &leader, 0).max.y, 50.0);
assert!(view.entity_bounds(&d, &leader).max.y < 50.0, "the block a multileader draws");
let clips = [clipped, clipped_inverted, clipped_partly];
let all = [ins("B", "0"), ins("N", "0"), ins("Z", "0"), ins("H", "0"), tagged, scaled, dim, dim_nested, leader].into_iter().chain(clips);
let all: Vec<Entity> = all.collect();
let mut plain = ViewportBounds::new(&[]);
for e in &all {
let (shared, fresh) = (view.entity_bounds(&d, e), ViewportBounds::new(&frozen).entity_bounds(&d, e));
assert_eq!((shared.min, shared.max), (fresh.min, fresh.max));
let (unfrozen, drawn) = (plain.entity_bounds(&d, e), entity_bounds(&d, e, 0));
assert_eq!((unfrozen.min, unfrozen.max), (drawn.min, drawn.max));
}
}
/// With the layer Defpoints frozen in the viewport, a point on that layer that is a part of a
/// block still counts: in the block of a reference, one block deeper, in the block of a
/// dimension, as its definition points are held, and in that of a dimension that is itself a
/// part of a block. Here the point lies far above all the rest. A line on Defpoints, a point
/// on another frozen layer and a line on one are left out. One [`ViewportBounds`] gives each of
/// them the box a fresh one gives it.
#[test]
fn a_viewport_keeps_the_points_on_defpoints_in_a_block() {
let line = |handle: u64, y: f64, layer: &str| {
let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) });
let mut e = Entity::new(crate::Handle(handle), kind);
e.common.layer = layer.into();
e
};
let point = |handle: u64, y: f64, layer: &str| {
let mut e = Entity::new(crate::Handle(handle), EntityKind::Point(crate::Point { p: Vec3::new(5.0, y, 0.0), angle: 0.0 }));
e.common.layer = layer.into();
e
};
let ins = |block: &str| Entity::new(crate::Handle(9), EntityKind::Insert(crate::Insert { block: block.into(), ..crate::Insert::default() }));
let dimension = |block: &str| {
let kind = EntityKind::Dimension(crate::Dimension {
kind: crate::DimKind::Aligned,
defpt: Vec3::new(5.0, 1.0, 0.0),
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::new(10.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 0.0,
text_rotation: 0.0,
user_text_pos: false,
block: Some(block.into()),
insertion_point: Vec3::ZERO,
overrides: Default::default(),
assoc: Vec::new(),
marks: Default::default(),
});
Entity::new(crate::Handle(8), kind)
};
let mut d = Drawing::new_metric();
d.ensure_layer("Hidden");
d.ensure_layer("Defpoints");
let mut add = |name: &str, parts: Vec<Entity>| {
let mut block = crate::Block::new(name);
for part in parts {
block.entities.push(part);
}
d.blocks.insert(name.into(), std::sync::Arc::new(block));
};
// P: a line along y = 0 on layer 0, a point on Defpoints at y = 200, a line on Defpoints
// along y = 250 and a line on "Hidden" along y = 300. NP holds a reference to P, DP a
// dimension that draws P. H is P with the point on "Hidden".
add("P", vec![line(1, 0.0, "0"), point(2, 200.0, "Defpoints"), line(3, 250.0, "Defpoints"), line(4, 300.0, "Hidden")]);
add("NP", vec![ins("P")]);
add("DP", vec![dimension("P")]);
add("H", vec![line(1, 0.0, "0"), point(2, 200.0, "Hidden")]);
let ys = |b: Bounds2| (b.min.y, b.max.y);
assert_eq!(ys(entity_bounds(&d, &ins("P"), 0)), (0.0, 300.0));
let frozen = ["HIDDEN".to_string(), "defpoints".to_string()];
let mut view = ViewportBounds::new(&frozen);
assert_eq!(ys(view.entity_bounds(&d, &ins("P"))), (0.0, 200.0), "the point on Defpoints in a reference's block, not the lines");
assert_eq!(ys(view.entity_bounds(&d, &ins("NP"))), (0.0, 200.0), "the same one block deeper");
assert_eq!(view.entity_bounds(&d, &dimension("P")).max.y, 200.0, "a dimension's definition point");
assert_eq!(view.entity_bounds(&d, &ins("DP")).max.y, 200.0, "the same for a dimension in a block");
assert_eq!(ys(view.entity_bounds(&d, &ins("H"))), (0.0, 0.0), "a point on another frozen layer");
// Where the viewport freezes only the other layer, the line on Defpoints counts too.
let hidden = ["Hidden".to_string()];
assert_eq!(ys(ViewportBounds::new(&hidden).entity_bounds(&d, &ins("P"))), (0.0, 250.0));
for e in [ins("P"), ins("NP"), dimension("P"), ins("DP"), ins("H")] {
let (shared, fresh) = (view.entity_bounds(&d, &e), ViewportBounds::new(&frozen).entity_bounds(&d, &e));
assert_eq!((shared.min, shared.max), (fresh.min, fresh.max));
}
}
/// A turned array of references reaches its side copies, not only the first and the last;
/// a hostile count measures only the copies that are drawn.
#[test]
+35 -1
View File
@@ -42,11 +42,19 @@ pub struct ForeignExtra {
pub color_book: Option<(String, String)>,
/// Other unmodelled property groups (material 347, shadow mode 284).
pub props: Vec<RawTag>,
/// Unmodelled groups of the record's own last subclass, written just before its xdata. Filled
/// on save from the entity itself ([`crate::Viewport::extra`]), so that copies keep them.
pub tail: Vec<RawTag>,
}
impl ForeignExtra {
pub fn is_empty(&self) -> bool {
self.xdict.is_none() && self.reactors.is_empty() && self.xdata.is_empty() && self.color_book.is_none() && self.props.is_empty()
self.xdict.is_none()
&& self.reactors.is_empty()
&& self.xdata.is_empty()
&& self.color_book.is_none()
&& self.props.is_empty()
&& self.tail.is_empty()
}
}
@@ -89,11 +97,36 @@ pub struct Foreign {
/// The drawing's own `$ACADVER` is the version it is saved as, which SAVEAS changes, so a
/// later save must not take it for this one (#2471).
pub version: Option<String>,
/// Block references with kept annotation scale contexts, as they were read: what a context
/// is brought up to date from (see [`KeptPlacement`]), by handle.
pub placements: BTreeMap<Handle, KeptPlacement>,
/// The file's registered applications (APPID names as read, in file order). Saving writes
/// them all back, whether or not any xdata still names them.
pub appids: Vec<String>,
}
/// A block reference as read: its insertion point, rotation (radians) and scale, and each of its
/// attributes as read, in order. Its kept contexts were written for it then; what it did since
/// moves them.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct KeptPlacement {
pub insert: crate::geom::Vec3,
pub rotation: f64,
pub scale: crate::geom::Vec3,
pub attribs: Vec<KeptAttrib>,
}
/// An attribute of a block reference as read: its tag, insertion and alignment points and
/// rotation (radians). Found again by tag and place among the reference's attributes with that
/// tag, since the attributes can be reordered or replaced (ATTSYNC) after the file is read.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct KeptAttrib {
pub tag: String,
pub insert: crate::geom::Vec3,
pub align: crate::geom::Vec3,
pub rotation: f64,
}
impl Foreign {
/// The class of the file's CLASSES a proxy's group 91 names (see [`class_number`]), if any.
/// Saving as DWG keeps a proxy with that class and leaves out one whose class it can't name.
@@ -110,6 +143,7 @@ impl Foreign {
&& self.targets.is_empty()
&& self.class_order.is_empty()
&& self.data_store.is_empty()
&& self.placements.is_empty()
&& self.appids.is_empty()
}
+11 -3
View File
@@ -31,8 +31,8 @@ pub use cadcraft_geom as geom;
pub use constraint::*;
pub use entity::*;
pub use extents::{
BlockBoundsCache, MAX_BLOCK_DEPTH, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, ole_frame, ole_frame_accepts,
ole_frame_transform,
BlockBoundsCache, MAX_BLOCK_DEPTH, ViewportBounds, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, ole_frame,
ole_frame_accepts, ole_frame_transform, point_on_defpoints,
};
pub use format::Format;
pub use gdt::*;
@@ -41,7 +41,7 @@ pub use names::{Named, NamedList, NamedMap};
pub use plotstyle::*;
pub use plotter::*;
pub use raster::{Raster, Rasters};
pub use refedit::{RefEdit, WorkItem};
pub use refedit::{RefEdit, WorkItem, XrefSource};
pub use store::EntityStore;
pub use tables::*;
pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES};
@@ -121,6 +121,9 @@ pub struct Drawing {
pub model: EntityStore,
/// Model layout's page setup, or the default extents-to-fit setup for a new drawing.
pub model_page: Option<PageSetup>,
/// The Model layout's own flags as the file had them (see [`Layout::flags`]); `None` for a
/// new drawing.
pub model_layout_flags: Option<i64>,
/// Layouts in list order (`tab_order` orders the tabs); [`Drawing::layout`] looks them up by name.
pub layouts: NamedList<Layout>,
/// The layout a file marks active (its block is `*Paper_Space`, the others `*Paper_SpaceN`),
@@ -174,6 +177,9 @@ pub struct Drawing {
/// 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>,
/// The LTYPE table of that file in the same way, without ByBlock and ByLayer (proxy graphics
/// count the others).
pub proxy_linetypes: Vec<String>,
}
impl Default for Drawing {
@@ -219,6 +225,7 @@ impl Drawing {
blocks: NamedMap::default(),
model: EntityStore::new(),
model_page: None,
model_layout_flags: None,
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)].into(),
active_layout: None,
views: Vec::new(),
@@ -240,6 +247,7 @@ impl Drawing {
portable_fonts: false,
rasters: Rasters::default(),
proxy_layers: Vec::new(),
proxy_linetypes: Vec::new(),
}
}
+33
View File
@@ -250,6 +250,39 @@ pub fn pattern_for(d: &Drawing, name: &str) -> Option<HatchPattern> {
Some(if d.header.i64("MEASUREMENT", 0) == 1 { scaled_pattern(p, 25.4) } else { p })
}
/// The pattern name of a user-defined hatch, as the DXF Reference writes it (group 2). Its families
/// are not a named pattern's: a hatch stores them at unit scale, turned by its angle and spaced by
/// its scale (groups 52, 41 and 77 of a DXF file), so [`user_defined_lines`] makes them for a file
/// that lists none (AutoCAD's own are written with 78 = 0).
pub const USER_PATTERN: &str = "_USER";
/// Whether `name` is a user-defined hatch's pattern name ([`USER_PATTERN`], in any case).
pub fn is_user_pattern(name: &str) -> bool {
name.eq_ignore_ascii_case(USER_PATTERN)
}
/// Hatch pattern scales must be greater than this limit. For a user-defined hatch, the scale is its line spacing.
pub const MIN_HATCH_PATTERN_SCALE: f64 = 1e-9;
/// Whether the scale can be used for hatch pattern lines.
pub fn is_supported_hatch_pattern_scale(scale: f64) -> bool {
scale.is_finite() && scale > MIN_HATCH_PATTERN_SCALE
}
/// The effective scale of a stored hatch. Use unit scale when its scale is unusable.
pub fn effective_hatch_pattern_scale(scale: f64) -> f64 {
if is_supported_hatch_pattern_scale(scale) { scale } else { 1.0 }
}
/// The line families of a user-defined hatch at unit scale, as a pattern definition has them: lines
/// along the hatch's angle, its scale apart, and with `double` a second family at right angles to
/// them. The hatch's angle turns the families and its scale spaces them, so a hatch of spacing
/// `s` and lines at `a` stores angle `a`, scale `s` and these families.
pub fn user_defined_lines(double: bool) -> Vec<PatternLine> {
let family = || PatternLine { angle: 0.0, origin: (0.0, 0.0), delta: (0.0, 1.0), dashes: Vec::new() };
if double { vec![family(), PatternLine { angle: 90.0, ..family() }] } else { vec![family()] }
}
/// `p` with every length (origins, offsets, dashes) multiplied by `k`.
fn scaled_pattern(mut p: HatchPattern, k: f64) -> HatchPattern {
for l in &mut p.lines {
+30
View File
@@ -42,6 +42,36 @@ pub struct RefEdit {
/// Block objects taken out of the working set with their edits (block coordinates, the block
/// object's handle).
pub released: Vec<Entity>,
/// The nested references picked through to reach the edited block: block references inside
/// block definitions, outermost first. Empty when the picked reference's own block is edited.
pub path: Vec<Handle>,
/// Set when the edited block comes from an external reference: REFCLOSE Save writes it back
/// into its source drawing.
pub xref: Option<XrefSource>,
}
/// Where an xref edited in place is written back to.
#[derive(Clone, Debug, PartialEq)]
pub struct XrefSource {
/// The xref (its block name in this drawing).
pub xref: String,
/// The source drawing file.
pub file: String,
/// `file` with every symbolic link resolved when the edit began: the file that is written.
/// The save is refused when `file` leads somewhere else by then.
pub real: String,
/// The version the file was in when the edit began, as its `$ACADVER` code ("AC1015"): it
/// is written back in that version (`None`: in the drawing's own).
pub version: Option<String>,
/// Whether the file is a binary DXF (written back as one).
pub binary: bool,
/// The block of the source drawing being edited; `None` for its model space.
pub block: Option<String>,
/// The file's size and modification time when the edit began.
pub stamp: Option<(u64, std::time::SystemTime)>,
/// Edited block objects (their handles in this drawing) and the objects of the source
/// drawing they were loaded from.
pub sources: Vec<(Handle, Handle)>,
}
impl RefEdit {
+16
View File
@@ -725,9 +725,17 @@ pub struct Block {
pub explodable: bool,
#[serde(default)]
pub units: u8,
/// References to this block scale uniformly (the BLOCK_RECORD's group 281).
#[serde(default)]
pub scale_uniformly: bool,
/// The parameters of an associative array when this is an array block.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub array: Option<crate::ArrayParams>,
/// An xref's file as its loaded objects were read from it: size and modification time (as the
/// system gives it, so a time before 1970 is kept too). Kept per drawing, so an edit in place (REFEDIT) can tell whether
/// the file changed since this drawing loaded it (session state; not saved).
#[serde(skip)]
pub xref_stamp: Option<(u64, std::time::SystemTime)>,
}
/// The load state of an external reference.
@@ -773,7 +781,9 @@ impl Block {
xref_path: None,
explodable: true,
units: 0,
scale_uniformly: false,
array: None,
xref_stamp: None,
}
}
}
@@ -899,6 +909,11 @@ pub struct Layout {
/// them; `None` for a layout CADCraft made, written as 0,0 to 12,9 (#2109).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limits: Option<(Vec2, Vec2)>,
/// The layout's own flags (LAYOUT group 70 after the AcDbLayout marker; DXF Reference: 1 is
/// its PSLTSCALE and 2 its LIMCHECK, each the value while the layout is current) as the file
/// had them; `None` for a layout CADCraft made, saved with the drawing's PSLTSCALE.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub flags: Option<i64>,
}
impl Layout {
@@ -912,6 +927,7 @@ impl Layout {
ucs: None,
ucs_previous: Vec::new(),
limits: None,
flags: None,
}
}
}
+78 -3
View File
@@ -222,6 +222,8 @@ fn visible_attributes_of_a_missing_block_still_count() {
style: "Standard".into(),
halign: HAlign::Left,
valign: VAlign::Baseline,
backwards: false,
upside_down: false,
},
invisible,
constant: false,
@@ -483,6 +485,8 @@ fn plain_attrib(tag: &str) -> Attrib {
style: "Standard".into(),
halign: HAlign::Left,
valign: VAlign::Baseline,
backwards: false,
upside_down: false,
},
invisible: false,
constant: false,
@@ -638,6 +642,8 @@ fn attdef_in_block_is_ignored_in_insert_extents() {
style: "Standard".into(),
halign: HAlign::Left,
valign: VAlign::Baseline,
backwards: false,
upside_down: false,
},
invisible: false,
constant: false,
@@ -663,6 +669,8 @@ fn text_kind(value: &str) -> EntityKind {
style: "Standard".into(),
halign: HAlign::Left,
valign: VAlign::Baseline,
backwards: false,
upside_down: false,
})
}
@@ -678,6 +686,7 @@ fn mtext_kind(contents: &str) -> EntityKind {
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
})
}
@@ -931,6 +940,68 @@ fn constant_values_count_in_extents_as_attmode_shows_them() {
assert!(top(2, true) > 40.0, "ATTMODE 2 shows an invisible one");
}
#[test]
fn aligned_and_fit_text_extents_span_their_two_points() {
// Drawn from the first point to the second whatever rotation is stored: Fit at its own height,
// Aligned at the height that keeps its proportions.
let ext = |halign: HAlign, second: Option<Vec3>| {
let mut t = plain_attrib("T").text;
t.value = "AB".into();
(t.halign, t.align_pt) = (halign, second);
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap();
extents_pair(&d)
};
let left = ext(HAlign::Left, None);
// Along x to a far second point: both reach it; only Aligned grows taller.
let far = Some(Vec3::new(20.0, 0.0, 0.0));
let (fit, aligned) = (ext(HAlign::Fit, far), ext(HAlign::Aligned, far));
assert!((fit.1.x - 20.0).abs() < 1e-9 && (aligned.1.x - 20.0).abs() < 1e-9, "{fit:?} {aligned:?}");
assert!(fit.1.x > left.1.x + 10.0, "wider than the same text left-justified");
assert_eq!(fit.1.y, left.1.y, "Fit keeps its height");
assert!(aligned.1.y > left.1.y * 5.0, "Aligned scales its height with its width");
// Straight up: the line turns to run to the second point.
let up = ext(HAlign::Fit, Some(Vec3::new(0.0, 20.0, 0.0)));
assert!((up.1.y - 20.0).abs() < 1e-9 && up.1.x < 1.0 && up.0.x < -0.5, "{up:?}");
// No second point, or one on the first: placed like left-justified text.
assert_eq!(ext(HAlign::Fit, None), left);
assert_eq!(ext(HAlign::Aligned, Some(Vec3::ZERO)), left);
}
#[test]
fn aligned_text_extents_keep_the_proportions_of_a_narrow_width_factor() {
// The fonts shape with the width factor as stored, so a text ten times narrower fitted over
// the same span is drawn ten times taller: its extents grow with it.
let top = |width_factor: f64| {
let mut t = plain_attrib("T").text;
t.value = "AB".into();
(t.halign, t.align_pt, t.width_factor) = (HAlign::Aligned, Some(Vec3::new(20.0, 0.0, 0.0)), width_factor);
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap();
extents_pair(&d).1.y
};
assert!(top(0.001) > top(0.01) * 5.0, "{} {}", top(0.001), top(0.01));
}
#[test]
fn aligned_and_fit_text_extents_follow_how_unusable_sizes_are_drawn() {
let ext = |halign: HAlign, height: f64, width_factor: f64| {
let mut t = plain_attrib("T").text;
t.value = "AB".into();
(t.halign, t.align_pt, t.height, t.width_factor) = (halign, Some(Vec3::new(1000.0, 0.0, 0.0)), height, width_factor);
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap();
extents_pair(&d)
};
// A height of 0 is drawn as a height of 1: Aligned text still spans its points and has room.
let flat = ext(HAlign::Aligned, 0.0, 1.0);
assert!((flat.1.x - 1000.0).abs() < 1e-9 && flat.1.y > flat.0.y, "{flat:?}");
assert_eq!(flat, ext(HAlign::Aligned, 1.0, 1.0));
// Fit text with a width factor of 0 is not stretched to the second point.
assert!(ext(HAlign::Fit, 1.0, 0.0).1.x < 100.0);
assert!((ext(HAlign::Fit, 1.0, 1.0).1.x - 1000.0).abs() < 1e-9);
}
#[test]
fn an_attribute_lies_on_the_layer_of_the_first_definition_of_its_tag() {
// Two definitions of one tag, in different case, on a frozen layer and on layer 0: an
@@ -1005,9 +1076,13 @@ fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() {
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
ins.attribs = (0..N).map(|i| plain_attrib(&tag('A', i))).collect();
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let t = std::time::Instant::now();
assert!(!d.extents(&Space::Model).is_empty());
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
let (bounds, cross_probes) = crate::TagKey::with_cross_probes(1000, || d.extents(&Space::Model));
assert!(!bounds.is_empty());
// Layer inheritance and the constant-value filter each query the opposite set.
// With no matches, an unindexed scan bypasses the probe (zero) or compares every pair.
for probes in cross_probes {
assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {cross_probes:?}");
}
}
/// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N
+3
View File
@@ -151,6 +151,7 @@ impl Interactive for LeaderM {
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}),
EntityKind::MText(m) => Some(m.clone()),
_ => None,
@@ -324,6 +325,7 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}))?)
}
Annotation::Quick { lines, width } => {
@@ -341,6 +343,7 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}))?)
}
Annotation::Copy(m) => {
@@ -31,6 +31,7 @@ fn mleader_kind(s: &Session, pts: &[Vec2], text: &str, landing: bool) -> Option<
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}),
style: st.name.clone(),
arrow_size: st.arrow_size,
+25
View File
@@ -480,6 +480,31 @@ fn table_create_edit_merge() {
assert!(dl.prims.len() > 10);
}
#[test]
fn covered_text_survives_save_and_unmerge() {
let text = "CoveredText".repeat(30);
let table = cadcraft_doc::Table {
col_widths: vec![2.0, 2.0],
row_heights: vec![0.5],
cells: vec![vec![
cadcraft_doc::TableCell { text: "Title".into(), merged: Some((1, 2)), ..Default::default() },
cadcraft_doc::TableCell { text: text.clone(), ..Default::default() },
]],
..Default::default()
};
let mut drawing = cadcraft_doc::Drawing::new_imperial();
drawing.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Table(table)).unwrap();
let bytes = cadcraft_io::write(&drawing, "table.dxf").unwrap();
let drawing = cadcraft_io::read(&bytes, "table.dxf").unwrap();
let handle = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Table(_))).unwrap().handle;
let mut session = Session::new();
session.open_drawing(drawing, "table.dxf", None);
session.execute("table.unmerge", &json!({ "handle": handle.hex(), "row": 0, "col": 1 })).unwrap();
let EntityKind::Table(table) = &session.doc().unwrap().entity(handle).unwrap().kind else { panic!("expected table") };
assert_eq!(table.cells[0][0].merged, None);
assert_eq!(table.cells[0][1].text, text);
}
#[test]
fn table_interactive() {
let mut s = Session::new();
+16 -11
View File
@@ -18,7 +18,7 @@ use super::has_doc;
use crate::{Accept, AttribAsk, AttribEntry, EngineError, Input, Interactive, Origin, Prompt, Result, Session, Step};
mod attdef;
mod attedit;
pub(crate) mod attedit;
mod burst;
mod description;
mod dyngrip;
@@ -457,17 +457,20 @@ fn current_text_style(s: &Session) -> String {
s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into())
}
/// A text style's name as the table spells it, with the width factor and oblique angle an
/// attribute definition takes from it (the renderer uses the entity's own values). `None` when
/// the drawing has no such style.
fn style_values(s: &Session, name: &str) -> Result<Option<(String, f64, f64)>> {
Ok(s.doc()?.text_style(name).map(|t| (t.name.clone(), t.width_factor, t.oblique)))
/// A text style's name as the table spells it, with the width factor, the oblique angle and the
/// Backwards and Upside down effects an attribute definition takes from it (the renderer uses the
/// entity's own values).
type StyleValues = (String, f64, f64, (bool, bool));
/// The [`StyleValues`] of the style named `name`. `None` when the drawing has no such style.
fn style_values(s: &Session, name: &str) -> Result<Option<StyleValues>> {
Ok(s.doc()?.text_style(name).map(|t| (t.name.clone(), t.width_factor, t.oblique, (t.backwards, t.upside_down))))
}
/// The current text style (TEXTSTYLE) with its width factor and oblique angle.
fn current_style_values(s: &Session) -> (String, f64, f64) {
fn current_style_values(s: &Session) -> StyleValues {
let name = current_text_style(s);
style_values(s, &name).ok().flatten().unwrap_or((name, 1.0, 0.0))
style_values(s, &name).ok().flatten().unwrap_or((name, 1.0, 0.0, (false, false)))
}
/// A justification code as `-ATTDEF` takes it, typed or in `justify`. Align and Fit run between
@@ -482,7 +485,7 @@ fn attdef_justify(code: &str) -> Result<(HAlign, VAlign)> {
/// The named text style with its width factor and oblique angle, or the error both the JSON form
/// and the typed `Style` option give for a style the drawing doesn't have.
fn resolve_style(s: &Session, name: &str) -> Result<(String, f64, f64)> {
fn resolve_style(s: &Session, name: &str) -> Result<StyleValues> {
style_values(s, name)?.ok_or_else(|| bad("attdef", format!("no text style \"{name}\"")))
}
@@ -507,10 +510,10 @@ fn attdef_kind(
height: f64,
invisible: bool,
j: (HAlign, VAlign),
style: (String, f64, f64),
style: StyleValues,
) -> EntityKind {
let (halign, valign) = j;
let (style, width_factor, oblique) = style;
let (style, width_factor, oblique, (backwards, upside_down)) = style;
let left = halign == HAlign::Left && valign == VAlign::Baseline;
EntityKind::AttDef(Attrib {
tag: tag.to_ascii_uppercase(),
@@ -525,6 +528,8 @@ fn attdef_kind(
style,
halign,
valign,
backwards,
upside_down,
},
invisible,
constant: false,
+3 -1
View File
@@ -103,7 +103,7 @@ impl AttdefM {
fn finish(&mut self, s: &mut Session, rotation: f64) -> Result<Step> {
let (h, v) = self.justify;
let left = h == HAlign::Left && v == VAlign::Baseline;
let (style, width_factor, oblique) = super::resolve_style(s, &self.style)?;
let (style, width_factor, oblique, (backwards, upside_down)) = super::resolve_style(s, &self.style)?;
s.add_entity(EntityKind::AttDef(Attrib {
tag: self.tag.to_uppercase(),
text: Text {
@@ -117,6 +117,8 @@ impl AttdefM {
style,
halign: h,
valign: v,
backwards,
upside_down,
},
invisible: self.flags & INVISIBLE != 0,
constant: self.flags & CONSTANT != 0,
+105 -8
View File
@@ -3,7 +3,7 @@
//! time or by replacing a string in all of them. Attribute tags match in any case, as in AutoCAD.
use cadcraft_doc::color::Color;
use cadcraft_doc::{AttribProps, Common, EntityKind, HAlign, Handle, Text, VAlign};
use cadcraft_doc::{Attrib, AttribProps, Common, EntityKind, HAlign, Handle, Text, VAlign};
use cadcraft_geom::Vec3;
use serde_json::{Map, Value, json};
@@ -20,7 +20,7 @@ pub(super) fn attedit_spec() -> CommandSpec {
CommandSpec::new("attedit", "Single...", run)
.menu(&["Modify", "Object", "Attribute", "Single..."])
.alias(&["ate", "eattedit"])
.params("{handle, values: {TAG: value} (tags in any case)} → {changed, unknownTags?}")
.params("{handle, values?: {TAG: value} (tags in any case; every attribute with the tag), at?: {index: value} (one attribute, by its place in the reference, for repeated tags); constant attributes are left alone} → {changed, unknownTags?, constantTags?}")
.interactive(|_| Ok(Box::new(AtteditM::default())))
}
@@ -35,7 +35,11 @@ pub(super) fn dash_attedit_spec() -> CommandSpec {
/// The value `values` gives for `tag`, matching the tag in any case. Numbers and booleans count
/// as their text.
pub(super) fn value_for(values: &Map<String, Value>, tag: &str) -> Option<String> {
let v = values.get(tag).or_else(|| values.iter().find(|(k, _)| k.eq_ignore_ascii_case(tag)).map(|(_, v)| v))?;
text_of(values.get(tag).or_else(|| values.iter().find(|(k, _)| k.eq_ignore_ascii_case(tag)).map(|(_, v)| v))?)
}
/// A value given for an attribute as its text (numbers and booleans count as their text).
fn text_of(v: &Value) -> Option<String> {
match v {
Value::String(t) => Some(t.clone()),
Value::Number(n) => Some(n.to_string()),
@@ -63,18 +67,103 @@ pub(super) fn with_unknown_tags(s: &Session, h: Handle, values: &Map<String, Val
fn run(s: &mut Session, p: &Value) -> Result<Value> {
let h = targets(s, p)?.first().copied().ok_or_else(|| bad("attedit", "`handle` is required"))?;
let vals = p.get("values").and_then(Value::as_object).cloned().unwrap_or_default();
let Some(EntityKind::Insert(ins)) = s.doc()?.entity(h).map(|e| &e.kind) else {
return Err(bad("attedit", format!("{} is not a block reference", h.hex())));
};
if super::super::curves::is_locked(s, h) {
return Err(bad("attedit", "the reference is on a locked layer"));
}
// Values by place (`at`): one attribute each, where a tag repeats (a DXF reference may carry
// two attributes with one tag; `values` changes both).
let mut at: Vec<(usize, String)> = Vec::new();
if let Some(m) = p.get("at").filter(|v| !v.is_null()) {
let m = m.as_object().ok_or_else(|| bad("attedit", "`at` must be an object of {index: value}"))?;
for (k, v) in m {
let i = k
.trim()
.parse::<usize>()
.ok()
.filter(|i| *i < ins.attribs.len())
.ok_or_else(|| bad("attedit", format!("`at`: {k} is not the index of one of the reference's attributes")))?;
at.push((i, text_of(v).ok_or_else(|| bad("attedit", format!("`at`: the value for {k} must be text")))?));
}
}
let given = |i: usize, tag: &str| at.iter().find(|(j, _)| *j == i).map(|(_, v)| v.clone()).or_else(|| value_for(&vals, tag));
// Constant attributes keep their definition's value.
let constant: Vec<String> =
ins.attribs.iter().enumerate().filter(|(i, a)| a.constant && given(*i, &a.tag).is_some()).map(|(_, a)| a.tag.clone()).collect();
if let Some((_, a)) = ins.attribs.iter().enumerate().find(|(i, a)| given(*i, &a.tag).is_some_and(|v| v.len() > MAX_VALUE)) {
return Err(bad("attedit", format!("the value for {} is longer than {MAX_VALUE} bytes", a.tag)));
}
let mut n = 0;
s.doc_mut()?.modify_entity(h, |e| {
if let EntityKind::Insert(i) = &mut e.kind {
for a in &mut i.attribs {
if let Some(v) = value_for(&vals, &a.tag) {
for (j, a) in i.attribs.iter_mut().enumerate().filter(|(_, a)| !a.constant) {
if let Some(v) = given(j, &a.tag) {
set_value(&mut a.text, v);
n += 1;
}
}
}
})?;
Ok(with_unknown_tags(s, h, &vals, json!({ "changed": n })))
let mut r = with_unknown_tags(s, h, &vals, json!({ "changed": n }));
if !constant.is_empty()
&& let Some(o) = r.as_object_mut()
{
o.insert("constantTags".into(), json!(constant));
}
Ok(r)
}
/// One attribute of a block reference, as the Properties palette and the Edit Attributes dialog
/// list it.
#[derive(Clone, Debug, PartialEq)]
pub struct AttributeRow {
pub tag: String,
/// The definition's prompt (the tag when it has none).
pub prompt: String,
pub value: String,
/// Where the attribute's text is inserted: two attributes can share a tag and a value, and a
/// reorder of the block's definitions moves them.
pub at: Vec3,
/// Not constant: the value can be changed.
pub editable: bool,
pub invisible: bool,
/// A multiline attribute: its value may hold line breaks.
pub multiline: bool,
/// The whole stored attribute this row was made from. The fields above are what a list shows;
/// this is what a pending edit is bound to, so a row is stale when any stored property differs
/// (text height, rotation, alignment point, justification, style, its own layer/colour/
/// linetype/lineweight overrides, its modes, …) and not only when the shown ones do.
pub record: Attrib,
}
/// The attributes of block reference `h`, in order (empty for other objects). The prompt comes
/// from the attribute, else from its definition in the reference's block.
pub fn attributes(d: &cadcraft_doc::Drawing, h: Handle) -> Vec<AttributeRow> {
let Some(EntityKind::Insert(ins)) = d.entity(h).map(|e| &e.kind) else { return Vec::new() };
let block = d.block(&ins.block);
let def_prompt = |tag: &str| {
block.and_then(|b| {
b.entities.iter().find_map(|e| match &e.kind {
EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(tag) && !ad.prompt.is_empty() => Some(ad.prompt.clone()),
_ => None,
})
})
};
ins.attribs
.iter()
.map(|a| AttributeRow {
tag: a.tag.clone(),
prompt: if a.prompt.is_empty() { def_prompt(&a.tag).unwrap_or_else(|| a.tag.clone()) } else { a.prompt.clone() },
value: a.text.value.clone(),
at: a.text.insert,
editable: !a.constant,
invisible: a.invisible,
multiline: a.multiline.is_some(),
record: a.clone(),
})
.collect()
}
/// A block name, tag or value specification: comma-separated wildcard patterns, any case. For
@@ -220,7 +309,7 @@ fn modify_attrib(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut c
}
/// The layer and colour attribute `k` of block reference `h` is drawn with: its own, else its
/// definition's (layer 0 is the reference's layer).
/// definition's (layer 0 from the definition is the reference's layer).
fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color)> {
let d = s.doc().ok()?;
let e = d.entity(h)?;
@@ -230,7 +319,7 @@ fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color)
.block(&ins.block)
.and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag))));
let c = a.props.over(&def.map(|de| de.common.clone()).unwrap_or_else(Common::default));
let layer = if c.layer == "0" { e.common.layer.clone() } else { c.layer };
let layer = if a.props.layer.is_none() && c.layer == "0" { e.common.layer.clone() } else { c.layer };
Some((layer, c.color))
}
@@ -327,6 +416,14 @@ impl Interactive for AtteditM {
fn name(&self) -> &'static str {
"ATTEDIT"
}
/// A selected block reference is taken at once (Edit Attributes from the shortcut menu).
fn begin(&mut self, s: &mut Session) -> Result<Step> {
let pre = s.selection();
if s.settings.pickfirst && !pre.is_empty() && self.pick(s, &pre).is_ok() {
s.set_selection(Vec::new());
}
Ok(Step::Continue)
}
fn prompt(&self, _s: &Session) -> Prompt {
match self.attribs.get(self.values.len()) {
Some((_, tag, cur)) if self.block.is_some() => Prompt::new(format!("Enter value for {tag}"), Accept::TEXT).default(cur.clone()),
+74 -1
View File
@@ -104,12 +104,17 @@ pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec<Attrib>
let m = ins.transform(blk.base.xy());
// The reference's attributes by tag, gathered once for all the definitions (#1923).
let carried = ins.attribs_by_tag();
#[cfg(test)]
let carried = carried.into_iter().map(|(tag, attrib)| (tests::MeasuredTag(tag), attrib)).collect::<std::collections::BTreeMap<_, _>>();
defs.iter()
.map(|ad| {
let mut k = EntityKind::Text(ad.text.clone());
k.transform(&m);
let mut t = if let EntityKind::Text(t) = k { t } else { ad.text.clone() };
t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
let key = TagKey(&ad.tag);
#[cfg(test)]
let key = tests::MeasuredTag(key);
t.value = carried.get(&key).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
Attrib {
tag: ad.tag.clone(),
text: t,
@@ -359,6 +364,74 @@ impl Interactive for AttsyncM {
mod tests {
use super::*;
std::thread_local! {
static SYNC_CROSS_PROBES: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
}
/// Use the actual tag ordering and count only probes between different fixture sets.
pub(super) struct MeasuredTag<'a>(pub(super) TagKey<'a>);
impl MeasuredTag<'_> {
fn record(&self, other: &Self) {
let TagKey(left) = self.0;
let TagKey(right) = other.0;
let sides = (left.as_bytes().first(), right.as_bytes().first());
if matches!(sides, (Some(b'A'), Some(b'D')) | (Some(b'D'), Some(b'A'))) {
SYNC_CROSS_PROBES.with(|count| count.set(count.get().map(|n| n + 1)));
}
}
}
impl PartialEq for MeasuredTag<'_> {
fn eq(&self, other: &Self) -> bool {
self.record(other);
self.0 == other.0
}
}
impl Eq for MeasuredTag<'_> {}
impl PartialOrd for MeasuredTag<'_> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for MeasuredTag<'_> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.record(other);
self.0.cmp(&other.0)
}
}
#[test]
fn sync_uses_indexed_cross_set_tag_matching() {
const N: usize = 512;
let mut s = Session::new();
s.execute("attdef", &json!({"tag":"T", "default":"d", "at":[0, 1], "height":1.0})).unwrap();
s.execute("line", &json!({"points":[[0, 0], [10, 0]]})).unwrap();
let ids: Vec<_> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
s.execute("block", &json!({"name":"B", "base":[0, 0], "keep":"delete", "handles":ids})).unwrap();
let added = s.execute("insert", &json!({"name":"B", "at":[0, 0], "attribs":{"T":"v"}})).unwrap();
let handle = Handle::parse_hex(added["handle"].as_str().unwrap()).unwrap();
let doc = s.doc().unwrap();
let blk = doc.block("B").unwrap();
let base = (*attdefs(blk)[0]).clone();
let EntityKind::Insert(mut ins) = doc.entity(handle).unwrap().kind.clone() else { panic!("insert expected") };
let value = ins.attribs[0].clone();
let defs: Vec<_> = (0..N).map(|i| Attrib { tag: format!("D{i:05}"), ..base.clone() }).collect();
let defs: Vec<_> = defs.iter().collect();
ins.attribs = (0..N).map(|i| Attrib { tag: format!("A{i:05}"), ..value.clone() }).collect();
SYNC_CROSS_PROBES.with(|count| count.set(Some(0)));
let result = synced(blk, &defs, &ins);
let probes = SYNC_CROSS_PROBES.with(|count| count.replace(None).unwrap());
assert_eq!(result.len(), N);
assert!(result.iter().all(|a| a.text.value == "d"));
// No cross-set comparisons means this lookup was bypassed, whereas a scan does N*N.
assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {probes}");
}
#[test]
fn attdisp_keywords_map_to_attmode() {
assert_eq!([attmode("Normal"), attmode("on"), attmode("OFF"), attmode("x")], [Some(1), Some(2), Some(0), None]);
+3 -3
View File
@@ -41,13 +41,13 @@ fn burst_pieces(d: &Drawing, e: &Entity) -> Option<Vec<Entity>> {
}
/// The properties an attribute is drawn with: its own, else those of its definition `def`; layer
/// 0 is the reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the
/// block's objects.
/// 0 from the definition is the reference's layer (an attribute set on layer 0 itself stays there)
/// and ByBlock colour the reference's colour, as EXPLODE gives the block's objects.
fn attrib_common(e: &Entity, def: Option<&Entity>, props: &cadcraft_doc::AttribProps) -> Common {
// An attribute without a definition follows the reference.
let base = def.map(|de| de.common.clone()).unwrap_or_else(|| Common { color: Color::ByBlock, ..Common::default() });
let mut c = props.over(&base);
if c.layer == "0" {
if props.layer.is_none() && c.layer == "0" {
c.layer.clone_from(&e.common.layer);
}
if c.color == Color::ByBlock {
+9 -1
View File
@@ -115,7 +115,13 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
let defs = b.attdefs_by_tag();
out.extend(ins.attribs.iter().filter(|a| !a.invisible).map(|a| {
let def = defs.get(&TagKey(&a.tag)).map(|e| &e.common);
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
let own = a.props.over(def.unwrap_or(&by_block));
let mut common = under(&own, r);
// An attribute set on layer 0 itself stays there; only layer 0 from its definition is
// the reference's layer.
if a.props.layer.is_some() {
common.layer.clone_from(&own.layer);
}
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
None => EntityKind::Text(a.text.clone()),
@@ -274,6 +280,8 @@ mod tests {
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
backwards: false,
upside_down: false,
},
invisible: false,
constant: false,
+3 -2
View File
@@ -30,9 +30,10 @@ pub(super) struct FileRef {
}
impl FileRef {
/// Whether to ask before redefining: a plain path whose block already exists.
/// Whether to ask before redefining: a plain path whose block already exists. EXPERT 2 or
/// more answers Yes without asking.
pub fn ask_redefine(&self, s: &Session) -> bool {
!self.explicit && s.doc().is_ok_and(|d| d.block(&self.name).is_some())
!self.explicit && s.doc().is_ok_and(|d| d.block(&self.name).is_some() && d.header.i64("EXPERT", 0) < 2)
}
/// Read the file and (re)define its block. Returns the block's name.
+7 -2
View File
@@ -220,14 +220,19 @@ fn linetypes_inside(e: &cadcraft_doc::Entity) -> Vec<String> {
out
}
/// The linetypes named by objects, layers, dimension styles and multiline styles.
/// The linetypes named by objects, layers, dimension styles and multiline styles, and the ones
/// proxy graphics draw with (as for layers: saving names them by their index in the table).
fn linetypes_in_use(d: &Drawing) -> impl Iterator<Item = String> + '_ {
let objects = entities(d).map(|e| e.common.linetype.clone());
let graphics = entities(d).flat_map(|e| match &e.kind {
EntityKind::Unknown(u) => u.graphics.iter().map(|g| g.common.linetype.clone()).collect(),
_ => Vec::new(),
});
let inside = entities(d).flat_map(|e| linetypes_inside(e));
let layers = d.layers.iter().map(|l| l.linetype.clone());
let dims = d.dim_styles.iter().flat_map(|t| [t.dim_linetype.clone(), t.ext_linetype1.clone(), t.ext_linetype2.clone()]);
let mlines = d.mline_styles.iter().flat_map(|t| t.elements.iter().map(|e| e.linetype.clone()));
objects.chain(inside).chain(layers).chain(dims).chain(mlines)
objects.chain(graphics).chain(inside).chain(layers).chain(dims).chain(mlines)
}
/// Names of the unused objects of a named kind, in table order. This is PURGE's scan; `USAGE`
File diff suppressed because it is too large Load Diff
+69 -11
View File
@@ -134,7 +134,7 @@ struct Ctx {
}
/// The folder of the host drawing at `host` (a file path).
fn folder(host: Option<&Path>) -> Option<PathBuf> {
pub(crate) fn folder(host: Option<&Path>) -> Option<PathBuf> {
let p = host?.parent()?;
Some(if p.as_os_str().is_empty() { PathBuf::from(".") } else { p.to_path_buf() })
}
@@ -293,8 +293,17 @@ fn case_insensitive(p: &Path) -> Result<Option<PathBuf>, ()> {
Ok(out.is_file().then_some(out))
}
/// The first bytes of a file [`read`] keeps with the drawing (enough for a DWG's version and the
/// binary DXF sentinel).
const HEAD_BYTES: usize = 4096;
/// Read a drawing file through the host's io hooks, counting its bytes against the load's total.
fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
/// Also returns the [`Stamp`] of the bytes read: taken from the opened file, so it describes them
/// even when the path is pointed at another file meanwhile; `None` when the file changed while it
/// was read (or the system can't tell its time), so an edit in place refuses until it is reloaded.
/// And the first [`HEAD_BYTES`] of those bytes, so what is told from them (a DWG's version, a
/// binary DXF) describes the same read.
fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>), String> {
let hooks = super::super::super::file::io().ok_or("file formats are not available in this build")?;
#[cfg(not(target_arch = "wasm32"))]
{
@@ -303,7 +312,9 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
let left = MAX_XREF_TOTAL_BYTES.saturating_sub(cx.bytes);
let limit = MAX_XREF_BYTES.min(left);
let mut f = std::fs::File::open(file).map_err(|e| e.to_string())?;
let len = f.metadata().map_err(|e| e.to_string())?.len();
let meta = f.metadata().map_err(|e| e.to_string())?;
let len = meta.len();
let before = stamp_of(&meta);
let too_big = || {
if limit < MAX_XREF_BYTES {
format!("the referenced files are larger than {} MB together", MAX_XREF_TOTAL_BYTES >> 20)
@@ -321,7 +332,10 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
return Err(too_big());
}
cx.bytes = cx.bytes.saturating_add(n);
(hooks.read)(&bytes, &file.to_string_lossy())
let after = f.metadata().ok().as_ref().and_then(stamp_of);
let read_as = before.filter(|b| Some(*b) == after);
let head = bytes.get(..HEAD_BYTES).unwrap_or(&bytes).to_vec();
Ok(((hooks.read)(&bytes, &file.to_string_lossy())?, read_as, head))
}
#[cfg(target_arch = "wasm32")]
{
@@ -330,6 +344,33 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
}
}
/// A file's size and modification time: how an edit in place (REFEDIT) tells whether an xref's
/// file changed since it was read ([`cadcraft_doc::Block::xref_stamp`]). The time is kept as the
/// system gives it: counted from 1970, a file dated before then would have none and always look
/// changed.
pub(crate) type Stamp = (u64, std::time::SystemTime);
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
fn stamp_of(m: &std::fs::Metadata) -> Option<Stamp> {
Some((m.len(), m.modified().ok()?))
}
/// The [`Stamp`] of the file at `file` now.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn stamp(file: &Path) -> Option<Stamp> {
stamp_of(&std::fs::metadata(file).ok()?)
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn stamp(_file: &Path) -> Option<Stamp> {
None
}
/// Read the drawing file `file` (with the size limits of xref loading), with the [`Stamp`] and the
/// first bytes of the bytes read (see [`read`]).
pub(crate) fn read_file(file: &Path) -> Result<(Drawing, Option<Stamp>, Vec<u8>), String> {
read(file, &mut Ctx::new(None))
}
/// Load every xref of `d` that isn't unloaded from the paths saved in it; `host` is the drawing's
/// own path.
pub(crate) fn load_all(d: &mut Drawing, host: Option<&str>) -> Vec<Outcome> {
@@ -393,8 +434,14 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: &
let Some(path) = b.xref_path.clone() else { return (XrefStatus::Unresolved, "not an xref".into()) };
clear(d, &key);
let (status, detail) = match fetch(&path, host, chosen, cx, depth) {
Ok((x, file)) => match import(d, &key, &x, cx) {
Ok(()) => (XrefStatus::Loaded, file.to_string_lossy().into_owned()),
Ok((x, file, read_as)) => match import(d, &key, &x, cx) {
Ok(()) => {
// This drawing's own baseline: another drawing loading the file later doesn't move it.
if let Some(b) = d.blocks.get_mut(&key) {
Arc::make_mut(b).xref_stamp = read_as;
}
(XrefStatus::Loaded, file.to_string_lossy().into_owned())
}
Err(e) => {
// Whatever made it in before the failure goes again. A fetch that failed imported
// nothing, so it doesn't pay for a second scan of the block table.
@@ -409,7 +456,13 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: &
}
/// Read the drawing referenced as `path` and load its own attached xrefs into it.
fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usize) -> Result<(Drawing, PathBuf), (XrefStatus, String)> {
fn fetch(
path: &str,
host: Option<&Path>,
chosen: bool,
cx: &mut Ctx,
depth: usize,
) -> Result<(Drawing, PathBuf, Option<Stamp>), (XrefStatus, String)> {
let unresolved = |m: &str| (XrefStatus::Unresolved, m.to_string());
if depth >= MAX_BLOCK_DEPTH {
return Err(unresolved("xrefs are nested too deeply"));
@@ -423,7 +476,7 @@ fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usi
return Err(unresolved("too many referenced files"));
}
cx.files += 1;
let mut x = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?;
let (mut x, read_as, _) = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?;
cx.chain.push(canon);
let nested: Vec<String> =
x.blocks.values().filter(|b| b.xref_path.is_some() && !b.xref_overlay && !b.name.contains('|')).map(|b| b.name.clone()).collect();
@@ -434,15 +487,20 @@ fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usi
}
}
cx.chain.pop();
Ok((x, file))
Ok((x, file, read_as))
}
/// The objects loading drawing `x` as an xref counts against [`MAX_XREF_OBJECTS`]: its model
/// space and every block's.
pub(crate) fn object_count(x: &Drawing) -> usize {
x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len()))
}
/// Bring referenced drawing `x` into xref `key`: its model space becomes the block's objects, its
/// symbols and blocks are added as `key|name` (dependent symbols the host already has keep the
/// host's settings, so layer changes survive a reload).
fn import(d: &mut Drawing, key: &str, x: &Drawing, cx: &mut Ctx) -> Result<(), String> {
let count = x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len()));
cx.objects = cx.objects.saturating_add(count);
cx.objects = cx.objects.saturating_add(object_count(x));
if cx.objects > MAX_XREF_OBJECTS {
return Err(format!("more than {MAX_XREF_OBJECTS} objects"));
}
-22
View File
@@ -343,11 +343,6 @@ fn eq_variants(o: &TanObj) -> Vec<Eq3> {
/// Circle tangent to three objects, nearest the pick points (Newton on all sign combinations).
pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
ttt_where(objs, |_| true)
}
/// [`ttt`] among the circles `ok` accepts.
pub fn ttt_where(objs: [(TanObj, Vec2); 3], ok: impl Fn(&Circle) -> bool) -> Option<Circle> {
let [(o1, p1), (o2, p2), (o3, p3)] = objs;
let mut starts: Vec<[f64; 3]> = Vec::new();
let cen = (p1 + p2 + p3) / 3.0;
@@ -355,20 +350,6 @@ pub fn ttt_where(objs: [(TanObj, Vec2); 3], ok: impl Fn(&Circle) -> bool) -> Opt
starts.push([cen.x, cen.y, rad.max(1e-3)]);
if let Some(c) = Circle::from_3_points(p1, p2, p3) {
starts.push([c.center.x, c.center.y, c.radius]);
} else {
// The picks lie in one line. When the circles picked are centred on it too, every Newton
// step from a start on that line stays on it: start off it as well, on both sides, from
// the circle through the two picks farthest apart and a point beside them.
let (a, b) = [(p1, p2), (p1, p3), (p2, p3)].into_iter().max_by(|x, y| x.0.dist(x.1).total_cmp(&y.0.dist(y.1))).unwrap_or((p1, p3));
let span = a.dist(b);
let n = (b - a).normalized().perp();
if span.is_finite() && span > 0.0 && n.is_finite() {
for side in [1.0, -1.0] {
if let Some(c) = Circle::from_3_points(a, b, (a + b) / 2.0 + n * (span * side)) {
starts.push([c.center.x, c.center.y, c.radius]);
}
}
}
}
let mut best: Option<(f64, Circle)> = None;
let scale = rad.max(p1.dist(p2)).max(1e-6);
@@ -398,9 +379,6 @@ pub fn ttt_where(objs: [(TanObj, Vec2); 3], ok: impl Fn(&Circle) -> bool) -> Opt
continue;
}
let c = Circle::new(Vec2::new(x[0], x[1]), x[2]);
if !ok(&c) {
continue;
}
let sc = score(&c, &objs);
if best.is_none_or(|(b, _)| sc < b - 1e-12) {
best = Some((sc, c));
+5 -74
View File
@@ -2,7 +2,6 @@ use super::{
Accept, Arc, Circle, EntityKind, Input, Interactive, Prompt, Result, Session, Step, Value, Vec2, added, arc, bad, circle, f64_req, line, number,
point_param, size_param,
};
use crate::snap;
pub(super) fn run_circle(s: &mut Session, p: &Value) -> Result<Value> {
let c = if let Some(center) = point_param(p, "center") {
@@ -52,8 +51,6 @@ pub(super) fn run_arc(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) struct CircleM {
mode: u8, // 0 center-radius, 1 = 3P, 2 = 2P, 3 = TTR
pts: Vec<Vec2>,
/// 3P: the circle or arc each point was picked on with a tangent snap, by point.
tans: Vec<Option<snap::SnapCurve>>,
diameter: bool,
/// The `Ttr` option hands over to the tangent-circle machine.
delegate: Option<Box<dyn Interactive>>,
@@ -72,22 +69,18 @@ impl Interactive for CircleM {
match (self.mode, n) {
(0, 0) => Prompt::new("Specify center point for circle", Accept::POINT).kw(&["3P", "2P", "Ttr (tan tan radius)"]),
(0, _) if self.diameter => {
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance().deferred()
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance()
}
(0, _) => {
let p = Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER)
.kw(&["Diameter"])
.base_opt(self.pts.first().copied())
.distance()
.deferred();
let p =
Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER).kw(&["Diameter"]).base_opt(self.pts.first().copied()).distance();
if last_r > 0.0 { p.default(format!("{last_r:.4}")) } else { p }
}
(1, k) => Prompt::new(
["Specify first point on circle", "Specify second point on circle", "Specify third point on circle"].get(k).copied().unwrap_or(""),
Accept::POINT,
)
.base_opt(self.pts.last().copied())
.deferred(),
.base_opt(self.pts.last().copied()),
(2, k) => Prompt::new(
if k == 0 { "Specify first end point of circle's diameter" } else { "Specify second end point of circle's diameter" },
Accept::POINT,
@@ -127,14 +120,7 @@ impl Interactive for CircleM {
let r = if self.diameter { c.dist(*e) / 2.0 } else { c.dist(*e) };
Some(Circle::new(*c, r))
}
1 if self.pts.len() == 3 => match self.three_points() {
Some(c) => Some(c),
None => {
self.pts.pop();
self.tans.truncate(self.pts.len());
return Err(crate::EngineError::Other("Circle does not exist.".into()));
}
},
1 if self.pts.len() == 3 => Circle::from_3_points(self.pts[0], self.pts[1], self.pts[2]),
2 if self.pts.len() == 2 => Some(Circle::from_2_points(self.pts[0], self.pts[1])),
_ => None,
};
@@ -144,29 +130,6 @@ impl Interactive for CircleM {
}
Ok(Step::Continue)
}
// 3P: a point picked with a tangent snap makes the circle tangent to that curve (#1512).
Input::Deferred(d) if self.mode == 1 => {
let tan = (d.mode == snap::mode::TAN && !matches!(d.curve, snap::SnapCurve::Line { .. })).then_some(d.curve);
self.tans.resize(self.pts.len(), None);
self.tans.push(tan);
self.input(s, Input::Point(d.at))
}
// A tangent picked for the radius: the circle around the center that touches the
// curve, on the side it was picked (#1512).
Input::Deferred(d) if self.mode == 0 && self.pts.len() == 1 => {
let Some(&c) = self.pts.first() else { return Ok(Step::Continue) };
// Around the picked curve's own center the circle would lie on it, not touch it.
let concentric =
matches!(d.curve, snap::SnapCurve::Circle { center, .. } | snap::SnapCurve::Arc { center, .. } if center.near(c, 1e-9));
let touch = d.curve.perpendiculars(c, d.at).into_iter().filter(|_| !concentric).min_by(|a, b| a.dist(d.at).total_cmp(&b.dist(d.at)));
match touch.map(|t| c.dist(t)).filter(|r| *r > 1e-12 && r.is_finite()) {
Some(r) => {
finish_circle(s, Circle::new(c, r))?;
Ok(Step::Done)
}
None => Err(crate::EngineError::Other("No circle around the center is tangent there.".into())),
}
}
Input::Text(t) if self.mode == 0 && self.pts.len() == 1 => {
let v = number(&t).ok_or_else(|| crate::EngineError::Other("Requires numeric distance or second point.".into()))?;
let r = if self.diameter { v / 2.0 } else { v };
@@ -211,38 +174,6 @@ impl Interactive for CircleM {
}
}
impl CircleM {
/// The 3P circle: through the three points, or tangent to the curves picked with TAN.
fn three_points(&self) -> Option<Circle> {
let [a, b, c] = <[Vec2; 3]>::try_from(self.pts.as_slice()).ok()?;
if self.tans.iter().all(Option::is_none) {
return Circle::from_3_points(a, b, c);
}
let tan = |i: usize| self.tans.get(i).copied().flatten();
// A plain point is a circle of radius zero to pass through; an arc is solved as its circle.
let target = |i: usize, p: Vec2| {
let circle = match tan(i) {
Some(snap::SnapCurve::Circle { center, radius } | snap::SnapCurve::Arc { center, radius, .. }) => Circle::new(center, radius),
_ => Circle::new(p, 0.0),
};
crate::cmd::curves::TanObj::Circle(circle)
};
let pts = [a, b, c];
// The circle must touch an arc within its sweep, not elsewhere on the arc's circle, and
// not be the picked circle itself (which lies on it rather than touching it).
let touches = |found: &Circle| {
pts.iter().enumerate().all(|(i, p)| {
tan(i).is_none_or(|t| {
let same = matches!(target(i, *p), crate::cmd::curves::TanObj::Circle(o)
if o.center.dist(found.center) + (o.radius - found.radius).abs() <= 1e-9 * o.radius);
!same && t.contains(target(i, *p).touch(found))
})
})
};
crate::cmd::curves::ttt_where([(target(0, a), a), (target(1, b), b), (target(2, c), c)], touches)
}
}
fn finish_circle(s: &mut Session, c: Circle) -> Result<()> {
s.add_entity(circle(c.center, c.radius))?;
s.doc_mut()?.header.set_f64("CIRCLERAD", c.radius);
+6
View File
@@ -37,6 +37,9 @@ pub(crate) fn justify_prompt(two_points: bool) -> Prompt {
pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotation: f64, j: (HAlign, VAlign)) -> EntityKind {
let style = s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into());
// New text takes Backwards and Upside down from its style, as AutoCAD's does; later style
// changes don't change them.
let (backwards, upside_down) = s.doc().ok().and_then(|d| d.text_style(&style)).map_or((false, false), |t| (t.backwards, t.upside_down));
let (h, v) = j;
let left = h == HAlign::Left && v == VAlign::Baseline;
EntityKind::Text(Text {
@@ -50,6 +53,8 @@ pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotatio
style,
halign: h,
valign: v,
backwards,
upside_down,
})
}
@@ -92,6 +97,7 @@ pub(super) fn run_mtext(s: &mut Session, p: &Value) -> Result<Value> {
line_spacing: f64_or(p, "lineSpacing", 1.0),
line_spacing_exact: bool_or(p, "lineSpacingExact", false),
columns: crate::cmd::mtext_opts::json_columns(p, height, width)?,
background: None,
});
added(s.add_entity(k)?)
}
+1 -1
View File
@@ -273,7 +273,7 @@ impl Interactive for RectM2 {
let msg = if self.center { "Specify center point for rectangle" } else { "Specify first corner point" };
Prompt::new(msg, Accept::POINT).kw(&["Chamfer", "CEnter", "Elevation", "Fillet", "Thickness", "Width"])
}
Some(p) => Prompt::new("Specify other corner point", Accept::POINT).kw(&["Area", "Dimensions", "Rotation"]).corner(p),
Some(p) => Prompt::new("Specify other corner point", Accept::POINT).kw(&["Area", "Dimensions", "Rotation"]).corner(p).xy(),
}
}
/// Consumes one input: option keywords (`Center` only switches the first point's meaning
+22 -3
View File
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("export", "Export...", run_export)
.menu(&["File", "Export..."])
.alias(&["exp"])
.params("{path? (else returns base64 `data`), format?: dxf|dwg|svg|png|pdf (default: the path's extension)} → {format, bytes, path? | data, warnings?: what an image draws short of the drawing}")
.params("{path? (else returns base64 `data`), format?: dxf|dwg|svg|png|pdf (default: the path's extension), version?: 2000|2004|2007|2010|2013|2018 (DXF and DWG; default: the drawing's own), binary?: false (DXF only)} → {format, bytes, version? (DXF and DWG), path? | data, warnings?: what an image draws short of the drawing}")
.noundo(),
CommandSpec::new("preview", "Plot Preview", run_preview)
.menu(&["File", "Plot Preview"])
@@ -123,7 +123,23 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("export", "`format` must be dxf, dwg, svg, png or pdf (or give a `path` with one of those extensions)"));
}
let file = format!("export.{format}");
let (bytes, notes) = super::file::write_noted(hooks, s.doc()?, &file).map_err(|e| bad("export", e))?;
// DXF and DWG take SAVEAS's version and binary options; the drawing keeps its own version and
// name (an export is not a save).
let opts = super::file::save_options("export", p)?;
let drawing_format = matches!(format.as_str(), "dxf" | "dwg");
if opts.version.is_some() && !drawing_format {
return Err(bad("export", "`version` applies to DXF and DWG files only"));
}
if opts.binary && format != "dxf" {
return Err(bad("export", "`binary` applies to DXF files only"));
}
let (bytes, notes) = if opts.version.is_some() || opts.binary {
let w =
super::file::write_as().ok_or_else(|| bad("export", "exporting at a chosen version or as binary DXF is not available in this build"))?;
(w(s.doc()?, &file, &opts).map_err(|e| bad("export", e))?, Vec::new())
} else {
super::file::write_noted(hooks, s.doc()?, &file).map_err(|e| bad("export", e))?
};
let folder = path.and_then(super::file::new_folder);
let mut r = match path {
Some(path) => {
@@ -132,8 +148,11 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
}
None => json!({ "data": base64_encode(&bytes), "format": format, "bytes": bytes.len() }),
};
if let (Some(v), Some(o)) = (opts.version, r.as_object_mut()) {
o.insert("version".into(), json!(v.year()));
}
super::file::report_new_folder(s, &mut r, folder);
super::file::report_loss(s, &mut r, &file);
super::file::report_loss(s, &mut r, &file, opts.version);
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
+11 -9
View File
@@ -258,7 +258,7 @@ fn version_list() -> String {
/// The `version` and `binary` parameters of a save: a version is a year (2018 or "2018"), "R2018"
/// or an `$ACADVER` code ("AC1032").
fn save_options(cmd: &str, p: &Value) -> Result<SaveAs> {
pub(super) fn save_options(cmd: &str, p: &Value) -> Result<SaveAs> {
let version = match p.get("version") {
None | Some(Value::Null) => None,
Some(v) => {
@@ -853,12 +853,13 @@ fn adopt_source_group(out: &std::fs::File, src: &std::fs::Metadata) -> std::io::
/// ([`crate::atomic_write::write_atomic_with`]). Nothing
/// to keep when there is no file yet. A file that doesn't look like a drawing
/// ([`looks_like_drawing`]) is not backed up, and the `.bak` already there is left alone.
/// Returns whether the backup was written. Also used for an xref REFEDIT writes back.
#[cfg(not(target_arch = "wasm32"))]
fn backup(path: &std::path::Path) -> std::io::Result<()> {
pub(crate) fn backup(path: &std::path::Path) -> std::io::Result<bool> {
let mut src = match std::fs::File::open(path) {
Ok(f) if f.metadata()?.is_file() => f,
Ok(_) => return Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Ok(_) => return Ok(false),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(e) => return Err(e),
};
let (head, tail, len) = ends(&mut src)?;
@@ -867,7 +868,7 @@ fn backup(path: &std::path::Path) -> std::io::Result<()> {
// the roots (or to another computer) isn't looked at.
if !backup_replaced(&head, &tail, len, std::fs::symlink_metadata(&bak).is_ok()) {
log::warn!("save: {} doesn't look like a whole drawing; its backup is left as it was", path.display());
return Ok(());
return Ok(false);
}
// The backup is no more readable than the drawing, nor than the .bak it replaces (a private
// 0600 drawing or .bak stays private). The mode is set as the new file is created, so a
@@ -893,7 +894,8 @@ fn backup(path: &std::path::Path) -> std::io::Result<()> {
}
std::io::Write::write_all(out, &head)?;
std::io::copy(&mut src, out).map(|_| ())
})
})?;
Ok(true)
}
/// Store the bytes, then mark the drawing saved under `path`. If storing fails the drawing keeps
@@ -1124,10 +1126,10 @@ pub(crate) fn lost_writing(d: &Drawing, path: &str, version: Version) -> std::co
}
/// Report what the file `path`, just written from the active document (what EXPORT writes: the
/// block while the Block Editor is open) at its own version, left out.
pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
/// block while the Block Editor is open) at version `asked` (else its own), left out.
pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str, asked: Option<Version>) {
let Ok(d) = s.doc() else { return };
let version = own_version(d, path);
let version = asked.unwrap_or_else(|| own_version(d, path));
let lost = lost_writing(d, path, version);
let notes = if drops_unknown(path) { dwg_notes(d) } else { Vec::new() };
report_lost(s, r, path, version, &lost);
+90 -4
View File
@@ -1,7 +1,7 @@
//! `grip.*` commands: the undoable, scriptable form of grip editing (see `crate::grips`).
use cadcraft_doc::{Entity, EntityKind, Handle};
use cadcraft_geom::{Mat3, Vec2};
use cadcraft_geom::{Mat3, Vec2, Vec3};
use serde_json::{Value, json};
use super::curves;
@@ -78,6 +78,70 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result<Value> {
Ok(json!({ "handle": h.hex(), "handles": edits.iter().map(|(o, _)| o.hex()).collect::<Vec<_>>() }))
}
/// Z coordinate of grip `index` on `kind` (matching `EntityKind::grips()` order), when the
/// entity stores a 3D position for that grip.
pub(super) fn grip_z(kind: &EntityKind, index: usize) -> Option<f64> {
let text_z = |t: &cadcraft_doc::Text| match (t.halign, t.valign) {
(cadcraft_doc::HAlign::Left, cadcraft_doc::VAlign::Baseline) | (cadcraft_doc::HAlign::Aligned | cadcraft_doc::HAlign::Fit, _) => t.insert.z,
_ => t.align_pt.unwrap_or(t.insert).z,
};
let z = match kind {
EntityKind::Line(l) => match index {
0 => Some(l.a.z),
1 => Some((l.a.z + l.b.z) * 0.5),
2 => Some(l.b.z),
_ => None,
},
EntityKind::Point(p) => (index == 0).then_some(p.p.z),
EntityKind::Circle(c) => (index < 5).then_some(c.center.z),
EntityKind::Arc(a) => (index < 4).then_some(a.center.z),
EntityKind::Ellipse(e) => (index < 5).then_some(e.center.z),
EntityKind::LwPolyline(p) => (index < kind.grips().len()).then_some(p.elevation),
EntityKind::Polyline3d(p) => p.points.get(index).map(|q| q.z),
EntityKind::Helix(h) => match index {
0 => Some(h.center.z),
1 => Some(h.start_point().z),
2 => Some(h.end_point().z),
_ => None,
},
EntityKind::Ray(r) | EntityKind::XLine(r) => match index {
0 => Some(r.base.z),
1 => Some(r.base.z + r.dir.z),
_ => None,
},
EntityKind::Text(t) => (index == 0).then(|| text_z(t)),
EntityKind::MText(t) => (index == 0).then_some(t.insert.z),
EntityKind::AttDef(a) => (index == 0).then(|| text_z(&a.text)),
EntityKind::Insert(i) => {
if index == 0 {
Some(i.insert.z)
} else {
i.grip_attribs().nth(index - 1).map(|(_, a)| text_z(&a.text))
}
}
EntityKind::Dimension(d) => match index {
0 => Some(d.p13.z),
1 => Some(d.p14.z),
2 => Some(d.defpt.z),
3 => Some(d.text_mid.z),
_ => None,
},
EntityKind::MLine(m) => m.vertices.get(index).map(|v| v.p.z),
EntityKind::Leader(l) => l.vertices.get(index).map(|v| v.z),
EntityKind::MLeader(m) => m.leaders.iter().flatten().map(|v| v.z).chain(std::iter::once(m.landing.z)).nth(index),
EntityKind::Hatch(h) => (index == 0).then_some(h.elevation),
EntityKind::Solid(s) | EntityKind::Trace(s) => s.corners.get(index).map(|c| c.z),
EntityKind::Face3d(f) => f.corners.get(index).map(|c| c.z),
EntityKind::PolyfaceMesh(m) => m.vertices.get(index).map(|v| v.z),
EntityKind::Viewport(v) => (index < 4).then_some(v.center.z),
EntityKind::Image(i) => (index == 0).then_some(i.insert.z),
EntityKind::Table(t) => (index < kind.grips().len()).then_some(t.insert.z),
EntityKind::Tolerance(t) => (index == 0).then_some(t.insert.z),
EntityKind::Spline(_) | EntityKind::Region(_) | EntityKind::Wipeout(_) | EntityKind::Unknown(_) => None,
};
z.filter(|v| v.is_finite())
}
/// Base point: `base`, or grip `index` of `baseHandle` (default: the first target).
fn base_point(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec2> {
if let Some(b) = point_param(p, "base") {
@@ -91,6 +155,27 @@ fn base_point(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec2>
g.get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))
}
/// 3D base point for SCALE: explicit `base` (with optional Z or ELEVATION), or the selected grip's
/// full 3D position so the grip stays stationary in all three coordinates.
fn base_point_3d(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec3> {
if let Some(b) = point_param(p, "base") {
return match p.get("base").and_then(|v| v.get(2)) {
Some(z) => z.as_f64().filter(|v| v.is_finite()).map(|z| Vec3::new(b.x, b.y, z)).ok_or_else(|| bad(cmd, "`base` Z must be a number")),
None => Ok(super::modify::at_elevation(s, b)),
};
}
let h = curves::handle_param(p, "baseHandle")
.or_else(|| hs.first().copied())
.ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?;
let i = index_param(cmd, p)?;
let e = curves::entity(s, h)?;
let g = e.kind.grips().get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))?;
Ok(match grip_z(&e.kind, i) {
Some(z) => Vec3::new(g.x, g.y, z),
None => super::modify::at_elevation(s, g),
})
}
fn apply(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<Value> {
let r = super::modify::transform_entities(s, hs, m, copy)?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
@@ -252,16 +337,17 @@ fn run_grip_rotate(s: &mut Session, p: &Value) -> Result<Value> {
fn run_grip_scale(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let base = base_point(s, "grip.scale", p, &hs)?;
// Why: Selected grip is the SCALE base point and must remain stationary in all three coordinates.
let base = base_point_3d(s, "grip.scale", p, &hs)?;
let f = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) {
Some(f) if f > 1e-12 => f,
Some(_) => return Err(bad("grip.scale", "factor must be positive")),
None => {
let f = base.dist(point_req("grip.scale", p, "to")?);
let f = base.xy().dist(point_req("grip.scale", p, "to")?);
if f.is_finite() && f > 1e-12 { f } else { return Err(bad("grip.scale", "scale factor would be zero")) }
}
};
let r = super::modify::scale_entities(s, &hs, super::modify::at_elevation(s, base), f, bool_or(p, "copy", false))?;
let r = super::modify::scale_entities(s, &hs, base, f, bool_or(p, "copy", false))?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
+13 -11
View File
@@ -9,7 +9,7 @@
use std::sync::Arc;
use cadcraft_doc::{Drawing, EntityKind, Handle};
use cadcraft_geom::{Mat3, Vec2};
use cadcraft_geom::{Mat3, Vec2, Vec3};
use super::gripcmds::stretch_grips;
use super::helpers::line;
@@ -47,6 +47,7 @@ pub(crate) struct GripEdit {
/// selection that the view being edited shows.
targets: Vec<Handle>,
base: Vec2,
base_z: Option<f64>,
mode: GripMode,
copy: bool,
ask: Ask,
@@ -84,6 +85,7 @@ impl GripEdit {
picking: false,
targets: Vec::new(),
base: Vec2::ZERO,
base_z: None,
mode: GripMode::Stretch,
copy: false,
ask: Ask::Mode,
@@ -109,6 +111,7 @@ impl GripEdit {
}
if self.hot.is_empty() {
self.base = p;
self.base_z = s.doc().ok().and_then(|d| d.entity(h)).and_then(|e| super::gripcmds::grip_z(&e.kind, i));
self.targets.push(h);
self.targets.extend(s.selection().into_iter().filter(|x| *x != h && shown(s, *x)));
} else if !self.targets.contains(&h) {
@@ -250,7 +253,13 @@ impl GripEdit {
return Err(other("Invalid point."));
}
let before = s.state()?.doc.clone();
let changed = !scale_entities(s, &self.targets, at_elevation(s, self.base), f, self.copy)?.is_empty();
// Why: Selected grip is the SCALE base point and must remain stationary in all three
// coordinates; fall back to ELEVATION only when the base has no stored 3D Z.
let base = match self.base_z.filter(|z| z.is_finite()) {
Some(z) => Vec3::new(self.base.x, self.base.y, z),
None => at_elevation(s, self.base),
};
let changed = !scale_entities(s, &self.targets, base, f, self.copy)?.is_empty();
self.finish_edit(before, changed)
}
@@ -299,7 +308,7 @@ impl GripEdit {
s.echo(self.label());
Ok(Step::Continue)
}
Input::Point(p) => {
Input::Point(p) | Input::Deferred(crate::snap::Deferred { at: p, .. }) => {
if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(p))
} else {
@@ -307,14 +316,6 @@ impl GripEdit {
self.edit(s, p, m)
}
}
Input::Deferred(d) => {
if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(d.at))
} else {
let m = self.matrix(d.at);
self.edit(s, d.at, m)
}
}
Input::Text(t) => match self.mode {
GripMode::Rotate => {
let a = s.angle_settings().rotation(&t).filter(|a| a.is_finite()).ok_or_else(|| other("Requires an angle or point."))?;
@@ -458,6 +459,7 @@ impl Interactive for GripEdit {
Ask::Base => match i {
Input::Point(p) => {
self.base = p;
self.base_z = None;
self.ask = Ask::Mode;
Ok(Step::Continue)
}
+409 -19
View File
@@ -7,6 +7,7 @@ pub(super) use patfile::run_patterns;
pub use patfile::{PatternChoice, pattern_choices};
use cadcraft_color::Color;
use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_scale};
use cadcraft_doc::{Drawing, Entity, EntityKind, Gradient, Handle, Hatch, HatchLoop, Space, entity_bounds};
use cadcraft_geom::{Bounds2, PolyVertex, Polyline, Vec2, point_in_polygon};
use serde_json::{Value, json};
@@ -26,10 +27,24 @@ use super::has_doc;
pub(crate) use assoc::update as refill_associative;
pub use pick::{HatchPicks, PickMode};
/// HATCH's parameters, for its JSON form and its catalog entry (the same for -HATCH).
const HATCH_PARAMS: &str = "{points?: [[x,y]] (internal points) and/or handles?: [hex] (closed objects), pattern?: \"ANSI31\" (built in, or defined by patternFile | patternText), patternFile?: path to a .pat file | patternText?: its contents (loads the patterns it defines), scale?, angle? (degrees), associative? (HPASSOC), separate? (HPSEPARATE: a hatch per point/object), origin?: [x,y] (HPORIGIN) | originMode?: \"current\"|\"bottomLeft\"|\"bottomRight\"|\"topLeft\"|\"topRight\"|\"center\" (HPORIGINMODE), style?: \"normal\"|\"outer\"|\"ignore\" (HPISLANDDETECTION)} — gaps up to HPGAPTOL close";
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("hatch", "Hatch...", run_hatch).menu(&["Draw", "Hatch..."]).alias(&["h", "bh", "-hatch"]).params("{points?: [[x,y]] (internal points) and/or handles?: [hex] (closed objects), pattern?: \"ANSI31\" (built in, or defined by patternFile | patternText), patternFile?: path to a .pat file | patternText?: its contents (loads the patterns it defines), scale?, angle? (degrees), associative? (HPASSOC), separate? (HPSEPARATE: a hatch per point/object), origin?: [x,y] (HPORIGIN) | originMode?: \"current\"|\"bottomLeft\"|\"bottomRight\"|\"topLeft\"|\"topRight\"|\"center\" (HPORIGINMODE), style?: \"normal\"|\"outer\"|\"ignore\" (HPISLANDDETECTION)} — gaps up to HPGAPTOL close").interactive(|s| Ok(Box::new(HatchM::new(s, false)))),
CommandSpec::new("gradient", "Gradient...", run_gradient).menu(&["Draw", "Gradient..."]).alias(&["gd"]).params("{points? and/or handles?, name?: \"LINEAR\"|\"CYLINDER\"|\"CURVED\"|\"SPHERICAL\"|\"HEMISPHERICAL\" or INV… (colours swapped), color1?, color2?, angle? (degrees), centered? (default true)}").interactive(|s| Ok(Box::new(HatchM::new(s, true)))),
// An AutoLISP routine's `(command …)` call answers HATCH's published command-line questions
// (pattern, how it is drawn, then the boundary). A person, and a script's own HATCH line,
// get the interface's dialog, or the prompts of AutoCAD's -HATCH when it is off: a script
// keeps picking the boundary first as it always has.
CommandSpec::new("hatch", "Hatch...", run_hatch)
.menu(&["Draw", "Hatch..."])
.alias(&["h", "bh"])
.params(HATCH_PARAMS)
.interactive(|s| Ok(Box::new(HatchM::new(s, false, s.lisp_program_input())))),
// -HATCH: the command-line form, a script's too. Its own id, so a dashed start takes its
// prompts and never the HATCH sequence above.
CommandSpec::new("-hatch", "Hatch", run_hatch).params(HATCH_PARAMS).interactive(|s| Ok(Box::new(HatchM::new(s, false, false)))),
CommandSpec::new("gradient", "Gradient...", run_gradient).menu(&["Draw", "Gradient..."]).alias(&["gd"]).params("{points? and/or handles?, name?: \"LINEAR\"|\"CYLINDER\"|\"CURVED\"|\"SPHERICAL\"|\"HEMISPHERICAL\" or INV… (colours swapped), color1?, color2?, angle? (degrees), centered? (default true)}").interactive(|s| Ok(Box::new(HatchM::new(s, true, false)))),
CommandSpec::new("boundary", "Boundary...", run_boundary).menu(&["Draw", "Boundary..."]).alias(&["bo", "bpoly"]).params("{points: [[x,y]]}").interactive(|_| Ok(Box::new(BoundaryM { region: false }))),
CommandSpec::new("region", "Region", run_region)
.menu(&["Draw", "Region"])
@@ -327,7 +342,12 @@ pub(crate) fn gradient_name(t: &str) -> Option<&'static str> {
struct HatchSettings {
pattern: String,
scale: f64,
/// HPSPACE for user-defined patterns. The entity stores it as its scale.
user_spacing: f64,
angle: f64,
/// A user-defined pattern is doubled ("Double hatch area?", DXF group 77): a second family of
/// lines at right angles to the first.
double: bool,
gradient: Option<Gradient>,
associative: bool,
/// HPSEPARATE: one hatch per picked point or selected object.
@@ -352,10 +372,13 @@ impl HatchSettings {
angle: f64_or(p, "angle", 0.0).to_radians(),
centered: bool_or(p, "centered", true),
});
let scale = f64_or(p, "scale", hdr.1).max(1e-9);
HatchSettings {
pattern,
scale: f64_or(p, "scale", hdr.1).max(1e-9),
scale,
user_spacing: scale,
angle: p.get("angle").and_then(Value::as_f64).map(f64::to_radians).unwrap_or(hdr.2),
double: false,
gradient: g,
associative: bool_or(p, "associative", s.doc().map_or(true, |d| d.header.i64("HPASSOC", 1) != 0)),
separate: bool_or(p, "separate", s.doc().is_ok_and(|d| d.header.i64("HPSEPARATE", 0) != 0)),
@@ -379,19 +402,22 @@ impl HatchSettings {
loops.iter_mut().for_each(|l| l.sources.clear());
}
let solid = self.gradient.is_some() || self.pattern == "SOLID";
let user_defined = cadcraft_doc::library::is_user_pattern(&self.pattern);
EntityKind::Hatch(Hatch {
pattern: if self.gradient.is_some() { "SOLID".into() } else { self.pattern.clone() },
solid,
origin: self.origin_mode.origin(&loops, self.origin),
loops,
scale: self.scale,
scale: if user_defined { self.user_spacing } else { self.scale },
angle: self.angle,
associative: self.associative,
style: self.style,
elevation: 0.0,
gradient: self.gradient.clone(),
background: None,
pattern_lines: patfile::lines_for(&self.pattern),
// A user-defined hatch's families come from its angle, spacing and double flag, not
// from a pattern definition; any other hatch takes the loaded pattern's, if any.
pattern_lines: if user_defined { cadcraft_doc::library::user_defined_lines(self.double) } else { patfile::lines_for(&self.pattern) },
})
}
}
@@ -582,6 +608,12 @@ fn pattern_exists(name: &str) -> bool {
cadcraft_doc::library::pattern(name).is_some() || patfile::user_pattern(name).is_some()
}
/// Whether `t` answers the pattern prompt with the user-defined form (U, User, User defined), as
/// AutoCAD's HATCH takes it from an AutoLISP routine.
fn user_pattern_keyword(t: &str) -> bool {
matches!(t.trim().to_ascii_lowercase().replace([' ', '-', '_'], "").as_str(), "u" | "user" | "userdefined")
}
/// The existing pattern `name` means, typed at the pattern prompt: read upper-cased, else a loaded
/// pattern's own name when only its Greek spelling differs in case or accent (σολιδ for ΣΟΛΙΔ).
pub(crate) fn pattern_named(name: &str) -> Option<String> {
@@ -599,11 +631,22 @@ enum HatchAsk {
Pattern,
Scale,
Angle,
/// The user-defined pattern's line angle: the same answer as [`HatchAsk::Angle`], asked as
/// AutoCAD's user-defined hatch asks it.
UserAngle,
/// The user-defined pattern's spacing between its lines (stored as the hatch's scale).
Spacing,
/// "Double hatch area?": a second family of lines at right angles.
Double,
Origin,
}
struct HatchM {
gradient: bool,
/// An AutoLISP routine's `(command …)` call started HATCH ([`Session::lisp_program_input`]): the
/// published command-line sequence (the pattern or the user-defined form, then its values, then the
/// objects) rather than a boundary picked first, as a person and a script's own HATCH line do.
legacy: bool,
settings: HatchSettings,
/// Loops by pick (one hatch each when separate).
loops: Vec<Vec<HatchLoop>>,
@@ -616,9 +659,10 @@ struct HatchM {
}
impl HatchM {
fn new(s: &Session, gradient: bool) -> Self {
fn new(s: &Session, gradient: bool, legacy: bool) -> Self {
HatchM {
gradient,
legacy: legacy && !gradient,
settings: HatchSettings::from(s, &Value::Null, gradient),
loops: Vec::new(),
asking: None,
@@ -648,14 +692,29 @@ impl HatchM {
fn answer(&mut self, s: &mut Session, a: HatchAsk, t: &str) -> Result<bool> {
match a {
HatchAsk::Pattern => {
let up = match patfile::typed_file(s, t.trim()) {
let t = t.trim();
// "?": the patterns there are, as AutoCAD lists them; the pattern is asked again.
if t == "?" {
s.echo(format!("Available patterns: {}", patfile::names().join(", ")));
return Ok(false);
}
// The user-defined form asks for its lines next, not a named pattern's scale and angle.
if self.legacy && user_pattern_keyword(t) {
self.settings.pattern = cadcraft_doc::library::USER_PATTERN.to_string();
self.settings.user_spacing = s.last_used.hatch_spacing;
self.settings.double = s.last_used.hatch_double;
return Ok(true);
}
let up = match patfile::typed_file(s, t) {
// Nothing loaded from it: the pattern is asked again.
Some(n) if n.is_empty() => return Ok(false),
Some(n) => n,
None => t.trim().to_ascii_uppercase(),
None => t.to_ascii_uppercase(),
};
if pattern_exists(&up) {
self.settings.pattern = up.clone();
// A named pattern, SOLID included, is not the user-defined one.
self.settings.double = false;
s.doc_mut()?.header.set_str("HPNAME", &up);
} else {
s.echo(format!("Unknown pattern {up}. Available: {}", patfile::names().join(", ")));
@@ -663,16 +722,35 @@ impl HatchM {
}
}
HatchAsk::Scale => {
let Some(v) = super::machines::number(t).filter(|v| v.is_finite() && *v > 0.0) else { return Ok(false) };
self.settings.scale = v;
let Some(v) = super::machines::number(t).filter(|v| v.is_finite() && *v > 0.0) else {
s.echo("Value must be positive and nonzero.");
return Ok(false);
};
s.doc_mut()?.header.set_f64("HPSCALE", v);
self.settings.scale = v;
}
HatchAsk::Angle => {
HatchAsk::Spacing => {
let Some(spacing) = super::machines::number(t).filter(|v| is_supported_hatch_pattern_scale(*v)) else {
s.echo(format!("Hatch spacing must be greater than {MIN_HATCH_PATTERN_SCALE:e} drawing units."));
return Ok(false);
};
self.settings.user_spacing = spacing;
s.last_used.hatch_spacing = spacing;
}
HatchAsk::Angle | HatchAsk::UserAngle => {
// Turns the pattern from the X axis (not from ANGBASE), clockwise when ANGDIR is 1.
let Some(a) = s.angle_settings().rotation(t).filter(|a| a.is_finite()) else { return Ok(false) };
self.settings.angle = a;
s.doc_mut()?.header.set_f64("HPANG", a);
}
HatchAsk::Double => {
self.settings.double = match t.trim().to_ascii_lowercase().as_str() {
"y" | "yes" => true,
"n" | "no" => false,
_ => return Ok(false),
};
s.last_used.hatch_double = self.settings.double;
}
HatchAsk::Origin => {
let mode = match t {
"Bottom left" => OriginMode::BottomLeft,
@@ -688,15 +766,27 @@ impl HatchM {
Ok(true)
}
/// The angle prompt `msg` with the current angle as its default, offered as it would be typed.
fn angle_prompt(&self, s: &Session, msg: &str) -> Prompt {
let (au, ap) = s.doc().map(|d| (d.header.i64("AUNITS", 0), d.header.i64("AUPREC", 0))).unwrap_or((0, 0));
// Offered as it would be typed: clockwise is positive when ANGDIR is 1.
let a = if s.angle_settings().clockwise { -self.settings.angle } else { self.settings.angle };
Prompt::new(msg, Accept::NUMBER).default(crate::units::format_angle(a, au, ap))
}
/// The sub-prompt that follows `a` (`taken`: its answer was taken). The Pattern option goes
/// on, as AutoCAD 2024's -HATCH Properties does, from the pattern name to its scale and then
/// its angle (a solid fill has neither), and asks again for a pattern or a value it refused.
/// The user-defined form goes instead to its lines' angle, their spacing and the double answer.
fn after(&self, a: HatchAsk, taken: bool) -> Option<HatchAsk> {
if !self.properties {
return None;
}
match a {
_ if !taken => Some(a),
HatchAsk::Pattern if cadcraft_doc::library::is_user_pattern(&self.settings.pattern) => Some(HatchAsk::UserAngle),
HatchAsk::UserAngle => Some(HatchAsk::Spacing),
HatchAsk::Spacing => Some(HatchAsk::Double),
HatchAsk::Pattern if self.settings.pattern != "SOLID" => Some(HatchAsk::Scale),
HatchAsk::Scale => Some(HatchAsk::Angle),
_ => None,
@@ -715,6 +805,13 @@ impl Interactive for HatchM {
self.settings.scale,
self.settings.angle.to_degrees()
));
if self.legacy {
// A routine answers the published questions first: the pattern, how it is drawn, then the
// boundary objects. A person picks the boundary first, and so does a script's own line.
self.asking = Some(HatchAsk::Pattern);
self.properties = true;
self.selecting = true;
}
Ok(Step::Continue)
}
fn prompt(&self, s: &Session) -> Prompt {
@@ -724,17 +821,26 @@ impl Interactive for HatchM {
let p = Prompt::new("Enter a pattern name", Accept::TEXT)
.default(self.settings.pattern.clone())
.picker(Picker::HatchPattern(self.settings.pattern.clone()));
return if self.gradient { p } else { p.kw(&["Solid"]) };
return if self.gradient {
p
} else if self.legacy {
// The published command-line answers: a pattern, a solid fill, the user-defined
// form, or the pattern list.
p.kw(&["?", "Solid", "User defined"])
} else {
p.kw(&["Solid"])
};
}
Some(HatchAsk::Scale) => {
return Prompt::new("Specify a scale for the hatch pattern", Accept::NUMBER).default(format!("{:.4}", self.settings.scale));
}
Some(HatchAsk::Angle) => {
let (au, ap) = s.doc().map(|d| (d.header.i64("AUNITS", 0), d.header.i64("AUPREC", 0))).unwrap_or((0, 0));
// Offered as it would be typed: clockwise is positive when ANGDIR is 1.
let a = if s.angle_settings().clockwise { -self.settings.angle } else { self.settings.angle };
let d = crate::units::format_angle(a, au, ap);
return Prompt::new("Specify an angle for the hatch pattern", Accept::NUMBER).default(d);
Some(HatchAsk::Angle) => return self.angle_prompt(s, "Specify an angle for the hatch pattern"),
Some(HatchAsk::UserAngle) => return self.angle_prompt(s, "Specify an angle for the hatch lines"),
Some(HatchAsk::Spacing) => {
return Prompt::new("Specify a spacing between the lines", Accept::NUMBER).default(self.settings.user_spacing.to_string());
}
Some(HatchAsk::Double) => {
return Prompt::new("Double hatch area?", Accept::TEXT).kw(&["Yes", "No"]).default(if self.settings.double { "Y" } else { "N" });
}
Some(HatchAsk::Origin) => return Prompt::new("Specify the pattern origin", Accept::POINT).kw(&ORIGIN_KW).default("Use current"),
None => {}
@@ -814,7 +920,10 @@ impl Interactive for HatchM {
self.asking = Some(HatchAsk::Pattern);
self.properties = !self.gradient;
}
"sCale" => self.asking = Some(HatchAsk::Scale),
"sCale" => {
let ask = if cadcraft_doc::library::is_user_pattern(&self.settings.pattern) { HatchAsk::Spacing } else { HatchAsk::Scale };
self.asking = Some(ask);
}
"Angle" => self.asking = Some(HatchAsk::Angle),
"Origin" => self.asking = Some(HatchAsk::Origin),
"sEparate" => {
@@ -882,6 +991,16 @@ mod tests {
d.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some((e.handle.hex(), h.clone())) } else { None }).unwrap()
}
/// How many hatches the drawing has.
fn hatch_count(s: &Session) -> usize {
s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Hatch(_))).count()
}
/// The closed 4000 × 2000 polyline the older LISP routines draw before they hatch it.
fn lisp_rectangle(s: &mut Session) {
s.cmdline("(command \"_.pline\" '(0 0) '(4000 0) '(4000 2000) '(0 2000) \"_c\")").unwrap();
}
#[test]
fn hatchedit_pattern_replaces_gradient() {
let mut s = Session::new();
@@ -991,6 +1110,277 @@ mod tests {
s.cancel();
}
/// HATCH started by a LISP routine takes the published command-line answers in order: the
/// pattern name, its scale and angle, then the boundary objects (issue #3498).
#[test]
fn lisp_hatch_takes_pattern_scale_and_angle_then_the_objects() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"dots\" 50 0 \"_l\" \"\")").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(hatch_count(&s), 1);
let h = only_hatch(&s).1;
assert_eq!((h.pattern.as_str(), h.loops.len()), ("DOTS", 1));
assert!((h.scale - 50.0).abs() < 1e-9, "{}", h.scale);
assert!(h.angle.abs() < 1e-12, "{}", h.angle);
}
/// The user-defined answer (U) asks for the lines' angle, their spacing and whether to double
/// them, as AutoCAD's HATCH does, and makes one hatch of the selection.
#[test]
fn lisp_user_defined_hatch_takes_angle_spacing_and_double() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"_u\" 45 100 \"_n\" \"_l\" \"\")").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(hatch_count(&s), 1);
let h = only_hatch(&s).1;
assert_eq!(h.pattern, cadcraft_doc::library::USER_PATTERN);
assert!(!h.solid);
assert!((h.angle - 45f64.to_radians()).abs() < 1e-12, "{}", h.angle);
assert!((h.scale - 100.0).abs() < 1e-9, "{}", h.scale);
assert_eq!(h.pattern_lines.len(), 1, "not doubled");
let absolute = h.pattern_lines[0].angle + h.angle.to_degrees();
assert!((absolute - 45.0).abs() < 1e-9, "lines at {absolute} degrees");
}
/// A doubled user-defined hatch has a second family of lines at right angles to the first.
#[test]
fn a_doubled_user_defined_hatch_has_a_second_family_at_right_angles() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"_u\" 45 100 \"_y\" \"_l\" \"\")").unwrap();
let h = only_hatch(&s).1;
assert_eq!(h.pattern_lines.len(), 2, "double hatch area: two families");
let absolute = |i: usize| h.pattern_lines[i].angle + h.angle.to_degrees();
assert!((absolute(1) - absolute(0) - 90.0).abs() < 1e-9, "{} and {}", absolute(0), absolute(1));
}
/// Enter at each question takes its default: the current pattern, scale and angle (the
/// user-defined form's angle, spacing and double flag too).
#[test]
fn lisp_hatch_enter_takes_the_current_values() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"\" \"\" \"\" \"_l\" \"\")").unwrap();
let h = only_hatch(&s).1;
assert_eq!((h.pattern.as_str(), h.scale, h.angle), ("ANSI31", 1.0, 0.0));
// The user-defined questions too: ANSI31 is replaced, the current angle and spacing kept,
// and "Double hatch area?" defaults to No.
s.cmdline("(command \"_.hatch\" \"_u\" \"\" \"\" \"\" \"_l\" \"\")").unwrap();
let h = s
.doc()
.unwrap()
.model
.iter()
.filter_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None })
.find(|h| h.pattern == cadcraft_doc::library::USER_PATTERN)
.unwrap();
assert_eq!(h.pattern, cadcraft_doc::library::USER_PATTERN);
assert!((h.scale - 1.0).abs() < 1e-12 && h.angle.abs() < 1e-12, "{} {}", h.scale, h.angle);
assert_eq!(h.pattern_lines.len(), 1, "not doubled");
}
#[test]
fn lisp_user_hatch_reads_spacing_and_double_across_drawings() {
let mut s = Session::new();
s.cmdline("(setvar \"HPSPACE\" 12.5)").unwrap();
s.cmdline("(setvar \"HPDOUBLE\" 1.0)").unwrap();
s.new_drawing(false);
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"_u\" \"\" \"\")").unwrap();
assert!(s.prompt_text().ends_with("<Y>:"), "{}", s.prompt_text());
for answer in ["", "_l", ""] {
s.cmdline(answer).unwrap();
}
let h = only_hatch(&s).1;
assert_eq!((h.scale, h.pattern_lines.len()), (12.5, 2));
}
#[test]
fn lisp_user_hatch_answers_leave_named_scale_unchanged() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(setvar \"HPSCALE\" 2.0)").unwrap();
s.cmdline("(command \"_.hatch\" \"_u\" 45 10 \"_y\" \"_l\" \"\")").unwrap();
assert_eq!(crate::sysvars::get(&s, "HPSCALE"), Some(json!(2.0)));
assert_eq!(crate::sysvars::get(&s, "HPSPACE"), Some(json!(10.0)));
assert_eq!(crate::sysvars::get(&s, "HPDOUBLE"), Some(json!(1)));
}
/// Solid asks neither a scale nor an angle, as it never has.
#[test]
fn lisp_hatch_solid_takes_no_scale_or_angle() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"_s\" \"_l\" \"\")").unwrap();
let h = only_hatch(&s).1;
assert!(h.solid);
assert_eq!(h.pattern, "SOLID");
}
/// "?" lists the patterns and asks again, as AutoCAD does.
#[test]
fn lisp_hatch_question_mark_lists_patterns_and_asks_again() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"?\")").unwrap();
assert!(s.log.iter().any(|l| l.contains("Available patterns") && l.contains("ANSI31")), "{:?}", s.log);
assert!(s.prompt_text().contains("Enter a pattern name"), "{}", s.prompt_text());
for answer in ["ansi31", "", "", "_l", ""] {
s.cmdline(answer).unwrap();
}
assert_eq!(only_hatch(&s).1.pattern, "ANSI31");
}
/// A zero, a negative number, NaN or text answers a scale or spacing question again, changing
/// nothing; the answers after it are read as the values they are, and nothing panics.
#[test]
fn a_refused_hatch_scale_or_spacing_changes_nothing() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"ansi31\" \"0\" \"-5\" \"nan\" \"x\" 2 30 \"_l\" \"\")").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let h = only_hatch(&s).1;
assert_eq!(h.pattern, "ANSI31");
assert!((h.scale - 2.0).abs() < 1e-9, "{}", h.scale);
assert!((h.angle - 30f64.to_radians()).abs() < 1e-12, "{}", h.angle);
assert!(s.log.iter().any(|l| l.contains("Value must be positive and nonzero.")), "{:?}", s.log);
// A spacing refused and then cancelled leaves no hatch behind.
let before = hatch_count(&s);
s.cmdline("(command \"_.hatch\" \"_u\" 45 \"0\")").unwrap();
assert!(s.running.is_some(), "still asking for the spacing");
assert!(s.prompt_text().contains("spacing"), "{}", s.prompt_text());
s.cancel();
assert_eq!(hatch_count(&s), before);
}
#[test]
fn user_hatch_spacing_at_the_limit_is_refused_and_just_above_it_draws_and_saves() {
let limit = MIN_HATCH_PATTERN_SCALE;
let spacing = limit.next_up();
let mut s = Session::new();
lisp_rectangle(&mut s);
s.execute("setvar", &json!({ "name": "HPSPACE", "value": spacing })).unwrap();
for value in [limit / 2.0, limit] {
let result = s.execute("setvar", &json!({ "name": "HPSPACE", "value": value }));
assert!(result.unwrap_err().to_string().contains("greater than"));
}
s.cmdline("(command \"_.hatch\" \"_u\" 0)").unwrap();
for value in [limit / 2.0, limit] {
s.cmdline(&value.to_string()).unwrap();
assert!(s.prompt_text().contains("Specify a spacing"), "{}", s.prompt_text());
}
assert!(s.log.iter().any(|line| line.contains("Hatch spacing must be greater than")), "{:?}", s.log);
let default = s.current_prompt().unwrap().default.unwrap().parse::<f64>().unwrap();
assert_eq!(default, spacing);
assert_eq!(crate::sysvars::get(&s, "HPSPACE"), Some(json!(spacing)));
for answer in ["", "_n", "_l", ""] {
s.cmdline(answer).unwrap();
}
// Draw a strip with room for a few lines so the sweep stays within its line budget.
let opts = cadcraft_render::Options { view: Some(Bounds2::from_points([Vec2::ZERO, Vec2::new(1.0, spacing * 5.0)])), ..Default::default() };
let original = s.doc().unwrap();
let reopened = cadcraft_io::read_dxf(cadcraft_io::write_dxf(original).as_bytes()).unwrap();
for drawing in [original, &reopened] {
let hatch = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap();
let display = cadcraft_render::build(drawing, &Space::Model, &opts);
let lines: Vec<_> = display
.prims
.iter()
.filter(|p| p.handle == hatch.handle && p.kind == cadcraft_render::Kind::Polyline)
.map(|p| display.points(p)[0].y)
.collect();
assert!(lines.len() >= 2, "expected multiple hatch lines, got {lines:?}");
for pair in lines.windows(2) {
let measured = (pair[1] - pair[0]).abs();
assert!((measured / spacing - 1.0).abs() < 1e-12, "drawn spacing {measured}, requested {spacing}");
}
}
}
/// A script's own HATCH line is not a routine's call: it keeps the interface's prompts and picks
/// the boundary first, as it did before a routine's answers were published.
#[test]
fn a_script_hatch_keeps_the_interface_prompts() {
let mut s = Session::new();
s.script("pline 0,0 4000,0 4000,2000 0,2000 c\nhatch\n").unwrap();
// The boundary question comes first: no pattern, scale or angle is asked.
assert!(s.prompt_text().contains("Pick internal point"), "{}", s.prompt_text());
s.cmdline("2000,1000").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let h = only_hatch(&s).1;
assert_eq!((h.pattern.as_str(), h.scale), ("ANSI31", 1.0));
}
/// A routine's `(command …)` inside a script is still a routine's call: it takes the published
/// order, though the script's own HATCH line above does not.
#[test]
fn a_lisp_hatch_call_from_a_script_takes_the_published_order() {
let mut s = Session::new();
s.script("pline 0,0 4000,0 4000,2000 0,2000 c\n(command \"_.hatch\" \"dots\" 50 0 \"_l\" \"\")\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let h = only_hatch(&s).1;
assert_eq!(h.pattern, "DOTS");
assert!((h.scale - 50.0).abs() < 1e-9, "{}", h.scale);
}
/// A script that a routine starts with `(command "_.script" …)` runs its lines as a script: its
/// HATCH line takes the interface's options (A for the angle), not the routine's order.
#[test]
fn a_script_a_routine_starts_keeps_the_interface_prompts() {
let dir = std::env::temp_dir().join(format!("cadcraft-hatch-script-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("angle.scr");
std::fs::write(&file, "hatch A 45\n\n").unwrap();
let mut s = Session::new();
let path = file.to_string_lossy().replace('\\', "/");
s.cmdline(&format!("(command \"_.script\" \"{path}\")")).unwrap();
let a = s.doc().unwrap().header.f64("HPANG", 0.0);
let _ = std::fs::remove_dir_all(&dir);
assert!((a - std::f64::consts::FRAC_PI_4).abs() < 1e-9, "HPANG {a}; {}", s.prompt_text());
assert!(!s.lisp_program_input(), "the routine's flag is restored after the script");
}
/// -HATCH keeps its own questions, a routine's included: it picks the boundary first, and the
/// Properties option takes the pattern, scale and angle as before.
#[test]
fn dash_hatch_keeps_its_pick_boundary_prompts() {
let mut s = Session::new();
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap();
s.cmdline("(command \"_.-hatch\")").unwrap();
assert!(s.prompt_text().contains("Pick internal point"), "{}", s.prompt_text());
s.cancel();
// Typed by a person (the interface's dialog off) it is the same command line.
s.start("hatch").unwrap();
assert!(s.prompt_text().contains("Pick internal point"), "{}", s.prompt_text());
s.cancel();
}
/// A user-defined hatch is saved as one (pattern `_USER`, pattern type 0, its double flag) and
/// read back with its angle, spacing and families.
#[test]
fn a_user_defined_hatch_survives_a_dxf_save_and_read() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"_u\" 45 100 \"_y\" \"_l\" \"\")").unwrap();
let text = cadcraft_io::write_dxf(s.doc().unwrap());
let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
let h = d.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).unwrap();
assert_eq!(h.pattern, cadcraft_doc::library::USER_PATTERN);
assert!(!h.solid);
assert!((h.scale - 100.0).abs() < 1e-9, "{}", h.scale);
assert!((h.angle - 45f64.to_radians()).abs() < 1e-12, "{}", h.angle);
assert_eq!(h.pattern_lines.len(), 2, "the doubled families are made again");
}
#[test]
fn unknown_pattern_error_and_catalog_name_the_pat_file_route() {
let mut s = Session::new();
+15 -2
View File
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("status", "Status", run_status).menu(&["Tools", "Inquiry", "Status"]).noundo(),
CommandSpec::new("drawing.inspect", "Inspect Drawing", run_inspect).params("{entities?: bool, limit?: n}").noundo(),
CommandSpec::new("entities", "Query Entities", run_entities)
.params("{type?, layer?, selected?: bool (default false; true = current selection in active space), window?: [[x,y],[x,y]], crossing?: bool (default true; false = entirely inside), limit?, offset?} → {count (all matches), returned, offset, entities}")
.params("{type?, layer?, selected?: bool (default false; true = current selection in active space), window?: [[x,y],[x,y]], crossing?: bool (default true; false = entirely inside), xdata?: true | \"APP\" | [\"APP\", …] (add each entity's extended data {\"APP\": [[code, value], …]}; a name also keeps only entities carrying that application's data), limit?, offset?} → {count (all matches), returned, offset, entities}")
.noundo(),
CommandSpec::new("shapes", "Analyze Shapes", shapes::run).params(shapes::PARAMS).noundo(),
CommandSpec::new("usage", "Analyze Usage", usage::run).params(usage::PARAMS).noundo(),
@@ -658,6 +658,7 @@ fn run_entities(s: &mut Session, p: &Value) -> Result<Value> {
.transpose()?;
let crossing = given("crossing").map_or(Ok(true), |v| v.as_bool().ok_or_else(|| bad(CMD, "`crossing` must be true or false")))?;
let selected = given("selected").map_or(Ok(false), |v| v.as_bool().ok_or_else(|| bad(CMD, "`selected` must be true or false")))?;
let xdata = super::props::xdata::XdataSelect::parse(given("xdata")).map_err(|m| bad(CMD, m))?;
let limit = count("limit", 500)?;
let offset = count("offset", 0)?;
let st = s.state()?;
@@ -671,8 +672,20 @@ fn run_entities(s: &mut Session, p: &Value) -> Result<Value> {
.filter(|e| ty.as_ref().is_none_or(|t| e.kind.type_name().to_ascii_lowercase() == *t || e.kind.dxf_name().to_ascii_lowercase() == *t))
.filter(|e| layer.as_ref().is_none_or(|l| e.common.layer.to_ascii_lowercase() == *l))
.filter(|e| window.as_ref().is_none_or(|w| crate::select::in_window(d, e, None, w, crossing, tol)))
.filter(|e| !xdata.filters() || xdata.matches(&e.common.xdata))
.collect();
let page: Vec<Value> = matches
.iter()
.skip(offset)
.take(limit)
.map(|e| {
let mut v = entity_summary(e);
if let (Some(x), Some(o)) = (xdata.json(&e.common.xdata), v.as_object_mut()) {
o.insert("xdata".into(), x);
}
v
})
.collect();
let page: Vec<Value> = matches.iter().skip(offset).take(limit).map(|e| entity_summary(e)).collect();
// `count` is every match; `returned` is this page of them (`offset`, `limit`).
Ok(json!({ "count": matches.len(), "returned": page.len(), "offset": offset, "entities": page }))
}
+30
View File
@@ -836,6 +836,36 @@ mod tests {
assert_eq!(graphics_layer(&s), "0");
}
/// The same for linetypes: PURGE keeps one only proxy graphics draw with, and RENAME takes
/// the graphics and the file's LTYPE order with it.
#[test]
fn linetypes_proxy_graphics_draw_with_are_in_use_and_renamed() {
let mut s = proxy_on_b();
for name in ["DASHED", "HIDDEN"] {
s.execute("linetype", &json!({ "load": name })).unwrap();
}
let d = s.doc_mut().unwrap();
d.proxy_linetypes = vec!["Continuous".into(), "DASHED".into(), "HIDDEN".into()];
let h = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::Unknown(_))).unwrap().handle;
d.modify_entity(h, |e| {
if let cadcraft_doc::EntityKind::Unknown(u) = &mut e.kind {
u.graphics[0].common.linetype = "DASHED".into();
}
})
.unwrap();
s.execute("purge", &json!({})).unwrap();
let d = s.doc().unwrap();
assert!(d.linetype("DASHED").is_some() && d.linetype("HIDDEN").is_none());
s.execute("rename", &json!({ "table": "linetype", "from": "DASHED", "to": "DASH2" })).unwrap();
let d = s.doc().unwrap();
let linetype = d.model.iter().find_map(|e| match &e.kind {
cadcraft_doc::EntityKind::Unknown(u) => Some(u.graphics[0].common.linetype.clone()),
_ => None,
});
assert_eq!(linetype.as_deref(), Some("DASH2"));
assert_eq!(d.proxy_linetypes, ["Continuous", "DASH2", "HIDDEN"]);
}
#[test]
fn rename_repoints_paper_space_and_block_entities() {
let mut s = Session::new();
+1
View File
@@ -466,6 +466,7 @@ fn run_copy(s: &mut Session, p: &Value) -> Result<Value> {
ucs: src.ucs,
ucs_previous: Vec::new(),
limits: src.limits,
flags: src.flags,
});
Ok(json!({ "name": to }))
}
+108 -50
View File
@@ -604,59 +604,117 @@ fn plot_path_extension_picks_the_format_like_export() {
}
#[test]
fn osnap_in_mspace_skips_vplayer_frozen_layers() {
fn layout_set_frames_extents_away_from_origin() {
let mut s = Session::new();
s.execute("layer.new", &json!({"name": "Hidden"})).unwrap();
s.execute("line", &json!({"points": [[60, -25], [70, -25]]})).unwrap();
let line_h = s.doc().unwrap().model.iter().last().unwrap().handle;
s.execute("properties.set", &json!({"handles": [line_h], "layer": "Hidden"})).unwrap();
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.execute("mview", &json!({"p1": [20, 20], "p2": [220, 120]})).unwrap();
let vp_h = viewports(&s, "Layout1").last().unwrap().0;
s.execute("vplayer", &json!({"handles": [vp_h], "freeze": ["Hidden"]})).unwrap();
s.execute("mspace", &json!({"handle": vp_h})).unwrap();
s.doc_mut().unwrap().layouts.push(cadcraft_doc::Layout::new("COVER", 2));
let paper = Space::Paper("COVER".into());
s.doc_mut()
.unwrap()
.add(
&paper,
cadcraft_doc::Common::default(),
cadcraft_doc::EntityKind::Line(cadcraft_doc::Line {
a: cadcraft_geom::Vec3::new(12049.0, 4307.0, 0.0),
b: cadcraft_geom::Vec3::new(12449.0, 4594.0, 0.0),
}),
)
.unwrap();
s.execute("layout.set", &json!({"name": "COVER"})).unwrap();
let v = s.state().unwrap().view();
assert!((v.center.x - 12249.0).abs() < 1e-6, "center.x={}", v.center.x);
assert!((v.center.y - 4450.5).abs() < 1e-6, "center.y={}", v.center.y);
assert!(v.height >= 287.0, "height={}", v.height);
}
let ap = s.pixel_size() * s.settings.aperture.max(1.0);
let d = ap * 0.5;
let model_before = s.doc().unwrap().model.len();
for (ovr, pt, name) in [
("end", format!("{},-25", 60.0 + d), "Endpoint"),
("mid", format!("{},-25", 65.0 + d), "Midpoint"),
("nea", format!("63,{}", -25.0 + d), "Nearest"),
] {
s.cmdline("line").unwrap();
s.cmdline(ovr).unwrap();
s.cmdline(&pt).unwrap();
assert_eq!(
s.log.last().map(String::as_str),
Some(format!("No {name} found for specified point.").as_str()),
"{ovr} should not snap to a line on a VPLAYER-frozen layer; log: {:?}",
s.log
);
s.cmdline("").unwrap();
#[test]
fn layout_set_ignores_off_layer_entities_far_from_visible_content() {
let mut s = Session::new();
let paper = Space::Paper("COVER".into());
{
let doc = s.doc_mut().unwrap();
doc.layouts.push(cadcraft_doc::Layout::new("COVER", 2));
let mut off_layer = cadcraft_doc::Layer::new("HIDDEN_REF");
off_layer.on = false;
doc.layers.push(off_layer);
doc.add(
&paper,
cadcraft_doc::Common::default(),
cadcraft_doc::EntityKind::Polyline3d(cadcraft_doc::Polyline3d {
points: vec![
cadcraft_geom::Vec3::new(12000.0, 4000.0, 0.0),
cadcraft_geom::Vec3::new(12400.0, 4000.0, 0.0),
cadcraft_geom::Vec3::new(12400.0, 4300.0, 0.0),
cadcraft_geom::Vec3::new(12000.0, 4300.0, 0.0),
],
closed: true,
}),
)
.unwrap();
doc.add(
&paper,
cadcraft_doc::Common { layer: "HIDDEN_REF".into(), ..Default::default() },
cadcraft_doc::EntityKind::Line(cadcraft_doc::Line {
a: cadcraft_geom::Vec3::new(1_000_000.0, 1_000_000.0, 0.0),
b: cadcraft_geom::Vec3::new(1_000_100.0, 1_000_100.0, 0.0),
}),
)
.unwrap();
}
assert_eq!(s.doc().unwrap().model.len(), model_before, "no new line should be created");
s.execute("layout.set", &json!({"name": "COVER"})).unwrap();
let v = s.state().unwrap().view();
assert!((v.center.x - 12200.0).abs() < 1e-6, "center.x={}", v.center.x);
assert!((v.center.y - 4150.0).abs() < 1e-6, "center.y={}", v.center.y);
assert!(v.height >= 300.0 && v.height < 2000.0, "height={}", v.height);
// Running osnaps through snap_cursor must also ignore the VPLAYER-frozen layer.
s.settings.osmode = crate::snap::mode::END | crate::snap::mode::MID | crate::snap::mode::NEA;
let cs = s.snap_cursor(
cadcraft_geom::Vec2::new(60.0 + d, -25.0),
&crate::snap::tracking::CursorQuery { base: None, deferred: false, corner: false, aperture: ap, tol: ap, now: 0.0, shift: false },
);
assert!(cs.snap.is_none(), "running osnap should not snap to a VPLAYER-frozen line: {:?}", cs.snap);
// Explicit ZOOM Extents continues to include entities on turned-off layers.
s.execute("zoom", &json!({"mode": "extents"})).unwrap();
let after_zoom = s.state().unwrap().view();
assert!(after_zoom.center.x > 100_000.0, "zoom extents center.x={}", after_zoom.center.x);
assert!(after_zoom.height > v.height * 100.0, "zoom extents height={}", after_zoom.height);
}
// A block reference on layer "0" containing an entity on "Hidden" must also not snap.
s.execute("block", &json!({"name": "B", "base": [60, -25], "handles": [line_h]})).unwrap();
let model_with_block = s.doc().unwrap().model.len();
s.cmdline("line").unwrap();
s.cmdline("end").unwrap();
s.cmdline(&format!("{},-25", 60.0 + d)).unwrap();
assert_eq!(
s.log.last().map(String::as_str),
Some("No Endpoint found for specified point."),
"end should not snap to a block entity on a VPLAYER-frozen layer; log: {:?}",
s.log
);
s.cmdline("").unwrap();
assert_eq!(s.doc().unwrap().model.len(), model_with_block);
#[test]
fn layout_set_falls_back_to_sheet_when_all_layers_hidden() {
let mut s = Session::new();
let paper = Space::Paper("ALL_OFF".into());
{
let doc = s.doc_mut().unwrap();
doc.layouts.push(cadcraft_doc::Layout::new("ALL_OFF", 2));
let mut off_layer = cadcraft_doc::Layer::new("OFF_LAYER");
off_layer.on = false;
doc.layers.push(off_layer);
let mut frozen_layer = cadcraft_doc::Layer::new("FROZEN_LAYER");
frozen_layer.frozen = true;
doc.layers.push(frozen_layer);
doc.add(
&paper,
cadcraft_doc::Common { layer: "OFF_LAYER".into(), ..Default::default() },
cadcraft_doc::EntityKind::Line(cadcraft_doc::Line {
a: cadcraft_geom::Vec3::new(12000.0, 4000.0, 0.0),
b: cadcraft_geom::Vec3::new(12400.0, 4300.0, 0.0),
}),
)
.unwrap();
doc.add(
&paper,
cadcraft_doc::Common { layer: "FROZEN_LAYER".into(), ..Default::default() },
cadcraft_doc::EntityKind::Line(cadcraft_doc::Line {
a: cadcraft_geom::Vec3::new(15000.0, 5000.0, 0.0),
b: cadcraft_geom::Vec3::new(15400.0, 5300.0, 0.0),
}),
)
.unwrap();
}
let (expected_center, expected_height) = {
let doc = s.doc().unwrap();
let page = doc.layout("ALL_OFF").map(|l| l.page.clone()).unwrap_or_default();
let (w, h) = if page.landscape { (page.height_mm, page.width_mm) } else { (page.width_mm, page.height_mm) };
let unit = if doc.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 1.0 / 25.4 };
(cadcraft_geom::Vec2::new(w * unit / 2.0, h * unit / 2.0), h * unit * 1.15)
};
s.execute("layout.set", &json!({"name": "ALL_OFF"})).unwrap();
let v = s.state().unwrap().view();
assert!((v.center.x - expected_center.x).abs() < 1e-6, "center.x={}", v.center.x);
assert!((v.center.y - expected_center.y).abs() < 1e-6, "center.y={}", v.center.y);
assert!((v.height - expected_height).abs() < 1e-6, "height={}", v.height);
}
+4 -4
View File
@@ -50,8 +50,8 @@ fn source(p: &Value) -> Result<(String, String)> {
}
/// The result of a blocking LISP run as JSON, with the lines it printed.
fn report(s: &Session, from_log: usize, r: Option<std::result::Result<Lv, String>>) -> Value {
let output: Vec<String> = s.log.get(from_log..).map(|l| l.to_vec()).unwrap_or_default();
fn report(s: &Session, from_log: u64, r: Option<std::result::Result<Lv, String>>) -> Value {
let output: Vec<String> = s.log_since(from_log).to_vec();
match r {
Some(Ok(v)) => json!({ "value": to_text(&v, true), "output": output }),
Some(Err(e)) => json!({ "error": e, "output": output }),
@@ -62,7 +62,7 @@ fn report(s: &Session, from_log: usize, r: Option<std::result::Result<Lv, String
fn run_appload(s: &mut Session, p: &Value) -> Result<Value> {
let (name, text) = source(p)?;
let before = s.lisp_commands();
let from = s.log.len();
let from = s.log_mark();
let r = s.lisp_load(&name, &text, true)?;
let mut out = report(s, from, r);
// The commands the file defined, so a caller can run them next (a failed file may still
@@ -82,7 +82,7 @@ fn input_value(v: &Value) -> Lv {
fn run_lisp(s: &mut Session, p: &Value) -> Result<Value> {
let code = str_param(p, "code").ok_or_else(|| bad("lisp", "`code` is required"))?;
let inputs = p.get("inputs").and_then(Value::as_array).map(|a| a.iter().map(input_value).collect()).unwrap_or_default();
let from = s.log.len();
let from = s.log_mark();
let r = s.lisp_eval(code, false, true, inputs).map_err(|e| match e {
EngineError::Other(m) => bad("lisp", m),
e => e,
+3
View File
@@ -105,6 +105,8 @@ fn explode_mtext(e: &Entity, m: &cadcraft_doc::MText) -> Vec<Entity> {
style: m.style.clone(),
halign: Default::default(),
valign: Default::default(),
backwards: false,
upside_down: false,
}),
}
})
@@ -177,6 +179,7 @@ fn explode_dimension(d: &cadcraft_doc::Drawing, e: &Entity, dm: &cadcraft_doc::D
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}),
});
}
+80 -20
View File
@@ -11,6 +11,7 @@ use cadcraft_geom::{Bounds2, Line, Vec2, line_line, point_in_polygon};
use serde_json::{Value, json};
use super::offset::offset_points;
use super::trim::ON_CUT;
use super::{Edges, trim};
use crate::cmd::helpers::lwpoly;
use crate::cmd::{CommandSpec, bad, point_param, targets};
@@ -22,7 +23,7 @@ const MAX_FENCE: usize = 10_000;
const MAX_OBJECTS: usize = 10_000;
/// Most stretches one call removes (an object can lose several).
const MAX_STRETCHES: usize = 10_000;
/// Most objects the preview draws (beyond that it shows nothing, to keep the cursor smooth).
/// Most parts the preview draws (beyond that it shows nothing, to keep the cursor smooth).
const MAX_PREVIEW: usize = 2000;
/// The traced line's distance from the edge, as a fraction of the edge's size.
const TRACE_GAP: f64 = 1e-5;
@@ -30,7 +31,7 @@ const TRACE_GAP: f64 = 1e-5;
pub(super) fn spec() -> CommandSpec {
CommandSpec::new("extrim", "Extended Trim", run_extrim)
.menu(&["Tools", "Additional Tools", "Extended Trim"])
.params("{edge: hex (line, arc, circle, ellipse, polyline or spline), side: [x,y] (inside or outside a closed edge, an arc's circle or an elliptical arc's ellipse; one side of an open edge)} → trimmed, handles, skipped: {locked, other, uncut}")
.params("{edge: hex (line, arc, circle, ellipse, polyline or spline), side: [x,y] (inside or outside a closed edge, an arc's circle or an elliptical arc's ellipse; one side of an open edge)} → trimmed, handles, skipped: {locked, other, uncut, partly (of uncut, those cut in part)}")
.interactive(|s| Ok(Box::new(ExtrimM::new(s))))
}
@@ -146,6 +147,11 @@ struct Edge {
impl Edge {
/// The cutting edge `h`: a line, arc, circle, ellipse, polyline or spline of the current space.
/// Whether the edge is still an object of the space being edited (MSPACE and PSPACE change
/// it while EXTRIM runs): only there can TRIM cut with it.
fn in_space(&self, s: &Session) -> bool {
s.doc().is_ok_and(|d| d.space_of(self.handle).as_ref() == Some(&s.space()))
}
fn new(s: &Session, h: Handle) -> Result<Edge> {
let d = s.doc()?;
let e = d.entity(h).ok_or_else(|| bad("extrim", format!("no object {}", h.hex())))?;
@@ -394,14 +400,16 @@ fn stretches_of(pts: &[Vec2], closed: bool, edge: &Grid, trace: &Grid) -> Option
}
/// The trim of everything crossing `edge` on `side`, worked out without changing anything.
fn plan(d: &Drawing, space: &cadcraft_doc::Space, edge: &Edge, side: Side) -> Result<Plan> {
/// `frozen`: the layers the active layout viewport freezes, whose objects it doesn't draw and
/// so leaves alone, as a selection through it does.
fn plan(d: &Drawing, space: &cadcraft_doc::Space, frozen: &[String], edge: &Edge, side: Side) -> Result<Plan> {
let trace = edge.trace(side);
let trace_grid = Grid::new(&trace);
let edge_grid = Grid::new(&edge.pts);
let tol = edge.gap / 20.0;
let mut p = Plan::default();
let mut stretches_total = 0;
for h in crate::select::select_fence(d, space, &trace) {
for h in crate::select::select_fence_in(d, space, frozen, &trace) {
if h == edge.handle {
continue;
}
@@ -462,6 +470,23 @@ fn midpoint(pts: &[Vec2]) -> Option<Vec2> {
pts.last().copied()
}
/// Whether `e` has no length at all: every point of its outline the same f64 point.
fn degenerate(d: &Drawing, e: &Entity, tol: f64) -> bool {
length(d, e, tol) <= 0.0
}
/// Whether TRIM would pass over a cut at `st`'s end (within ON_CUT of its pick) and run on to the
/// next one, taking more than `st`: such a stretch is left, by the trim and by its preview. The
/// ends and the pick lie on the outline traced within `tol` (and the pick is then brought onto
/// the object), so a true cut can be up to 3 `tol` nearer than the end found: that is the margin.
/// TRIM measures along the object, and so does this: the pick is the middle of the stretch's
/// longest part, half of that part from the nearer of its ends along the outline (straight across,
/// a folded polyline can bring an end next to the pick however far away it is along it).
fn too_short(st: &Stretch, tol: f64) -> bool {
let longest = st.parts.iter().map(|p| arc_length(p)).fold(0.0, f64::max);
longest / 2.0 <= ON_CUT + 3.0 * tol
}
/// The length of an object's drawn outline.
fn length(d: &Drawing, e: &Entity, tol: f64) -> f64 {
crate::select::hit_polylines(d, e, tol).iter().flat_map(|pl| pl.windows(2).filter_map(|w| Some(w.first()?.dist(*w.get(1)?)))).sum()
@@ -488,11 +513,15 @@ pub(super) fn run_extrim(s: &mut Session, p: &Value) -> Result<Value> {
/// Trim every object crossing `edge` on `side`: one undo step, everything checked first.
fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result<Value> {
if !edge.in_space(s) {
return Err(bad("extrim", "the cutting edge is not in the space being edited; pick it again there"));
}
let space = s.space();
let plan = plan(s.doc()?, &space, edge, side)?;
let plan = plan(s.doc()?, &space, s.viewport_frozen(), edge, side)?;
let edges = Edges { only: Some(std::slice::from_ref(&edge.handle)), implied: false };
let tol = edge.gap / 20.0;
let mut trimmed = 0;
let mut partly = 0;
let mut created = Vec::new();
// Objects some planned cut failed on, reported rather than counted as done.
let mut uncut = plan.uncut;
@@ -501,7 +530,16 @@ fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result<Value> {
let mut cut = false;
// The object as it is before any cut: its lines and arcs, exactly.
let exact = s.doc()?.entity(h).and_then(|e| exact_outline(&e.kind));
for x in stretches.into_iter().map(|st| st.pick) {
for st in stretches {
// TRIM passes over a cut within ON_CUT of the pick and runs on to the next one, which
// would take more than this stretch: a stretch that short is left, and said so.
if too_short(&st, tol) {
if !uncut.contains(&h) {
uncut.push(h);
}
continue;
}
let x = st.pick;
// The pick lies on the flattened outline, which strays from a large-radius arc by up to
// a millionth of its radius (far more than `tol` next to a short edge): bring it onto
// the object itself, and measure the pieces exactly too.
@@ -540,9 +578,10 @@ fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result<Value> {
cut = true;
live.retain(|l| *l != t);
for n in pieces {
// Never leave a piece of no length behind.
// Never leave a piece of no length behind; a short one that has length stays, as
// TRIM leaves it.
let d = s.doc()?;
if d.entity(n).is_some_and(|e| length(d, e, tol) <= tol) {
if d.entity(n).is_some_and(|e| degenerate(d, e, tol)) {
s.doc_mut()?.remove_entity(n);
} else {
live.push(n);
@@ -550,7 +589,12 @@ fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result<Value> {
}
}
if cut {
trimmed += 1;
// A partly cut object is counted once, with those not cut everywhere.
if uncut.contains(&h) {
partly += 1;
} else {
trimmed += 1;
}
created.extend(live.into_iter().filter(|l| *l != h));
}
}
@@ -562,12 +606,13 @@ fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result<Value> {
message.push_str(&format!(" {} that can't be trimmed (blocks, hatches, text…) left as they are.", plan.other));
}
if !uncut.is_empty() {
message.push_str(&format!(" {} could not be cut everywhere the edge crosses them.", uncut.len()));
message.push_str(&format!(" {} could not be cut everywhere the edge crosses them", uncut.len()));
message.push_str(&if partly > 0 { format!(" ({partly} of them cut in part).") } else { ".".to_string() });
}
Ok(json!({
"trimmed": trimmed,
"handles": created.iter().map(|h| h.hex()).collect::<Vec<_>>(),
"skipped": { "locked": plan.locked, "other": plan.other, "uncut": uncut.len() },
"skipped": { "locked": plan.locked, "other": plan.other, "uncut": uncut.len(), "partly": partly },
"message": message,
}))
}
@@ -595,15 +640,19 @@ fn on_outline(segs: &[cadcraft_geom::Segment], p: Vec2) -> Vec2 {
}
/// The parts the trim would remove, drawn red.
fn preview(d: &Drawing, space: &cadcraft_doc::Space, edge: &Edge, side: Side) -> Vec<Entity> {
let Ok(plan) = plan(d, space, edge, side) else { return Vec::new() };
if plan.work.len() > MAX_PREVIEW {
fn preview(d: &Drawing, space: &cadcraft_doc::Space, frozen: &[String], edge: &Edge, side: Side) -> Vec<Entity> {
let Ok(plan) = plan(d, space, frozen, edge, side) else { return Vec::new() };
let tol = edge.gap / 20.0;
// What costs is what is drawn: an object can lose many stretches, each of several parts.
let parts: usize =
plan.work.iter().flat_map(|(_, st)| st).filter(|st| !too_short(st, tol)).map(|st| st.parts.iter().filter(|p| p.len() >= 2).count()).sum();
if parts > MAX_PREVIEW {
return Vec::new();
}
let mut out = Vec::new();
for (h, stretches) in plan.work {
let Some(e) = d.entity(h) else { continue };
for part in stretches.into_iter().flat_map(|st| st.parts).filter(|p| p.len() >= 2) {
for part in stretches.into_iter().filter(|st| !too_short(st, tol)).flat_map(|st| st.parts).filter(|p| p.len() >= 2) {
let mut ent = Entity::new(Handle(0), lwpoly(part.into_iter().map(cadcraft_geom::PolyVertex::new).collect(), false));
ent.common.color = Color::Index(1);
ent.common.layer = e.common.layer.clone();
@@ -615,10 +664,15 @@ fn preview(d: &Drawing, space: &cadcraft_doc::Space, edge: &Edge, side: Side) ->
/// EXTRIM at the prompts: the cutting edge (or the one object selected beforehand), then the side,
/// with the parts that will go shown red as the cursor moves.
/// What a cached EXTRIM preview was worked out for: the space being edited and the frozen layers.
type PreviewFor = (cadcraft_doc::Space, Vec<String>);
pub(super) struct ExtrimM {
edge: Option<Edge>,
/// The preview for each side (left, right), worked out once.
previews: RefCell<[Option<Vec<Entity>>; 2]>,
/// The preview for each side (left, right), worked out once for the space being edited and the
/// layers the active viewport freezes then: a VPLAYER or MSPACE run meanwhile changes what the
/// trim works on.
previews: RefCell<[Option<(PreviewFor, Vec<Entity>)>; 2]>,
}
impl ExtrimM {
@@ -693,16 +747,22 @@ impl Interactive for ExtrimM {
}
fn preview_objects(&self, s: &Session, cursor: Vec2) -> Vec<Entity> {
let Some(edge) = &self.edge else { return Vec::new() };
// An edge left in another space cuts nothing here, so nothing is shown going.
if !edge.in_space(s) {
return Vec::new();
}
let Some(side) = edge.side(cursor) else { return Vec::new() };
let slot = usize::from(side == Side::Right);
let cached = self.previews.borrow().get(slot).cloned().flatten();
let (space, frozen) = (s.space(), s.viewport_frozen());
let cached =
self.previews.borrow().get(slot).cloned().flatten().filter(|((sp, f), _)| *sp == space && f.as_slice() == frozen).map(|(_, v)| v);
let mut v = match cached {
Some(v) => v,
None => {
let Ok(d) = s.doc() else { return Vec::new() };
let v = preview(d, &s.space(), edge, side);
let v = preview(d, &space, frozen, edge, side);
if let Some(c) = self.previews.borrow_mut().get_mut(slot) {
*c = Some(v.clone());
*c = Some(((space.clone(), frozen.to_vec()), v.clone()));
}
v
}
+132 -65
View File
@@ -106,6 +106,74 @@ impl SelectThen {
}
}
/// The preview with the cursor at `c` and the base point at `base`.
fn preview_from(&self, s: &Session, base: Vec2, c: Vec2) -> Vec<EntityKind> {
let (m, rubber_from) = match self.op {
Op::Move | Op::Copy => (Mat3::translate(c - base), base),
Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base),
Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base),
Op::Scale => match self.scale_reference_factor(base, c) {
Some((f, from)) => (Mat3::scale_about(base, f), from),
None => return self.ref_from.map(|a| vec![line(a, c)]).unwrap_or_default(),
},
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
_ => return Vec::new(),
};
let Ok(d) = s.doc() else { return Vec::new() };
let mut out: Vec<EntityKind> = self
.objs
.iter()
.take(500)
.filter_map(|h| d.entity(*h))
.map(|e| {
let mut k = e.kind.clone();
if self.op == Op::Mirror {
mirror_kind(&mut k, &m);
} else {
k.transform(&m);
}
k
})
.collect();
out.push(line(rubber_from, c));
out
}
/// The drag with the cursor at `c` and the base point at `base`.
fn drag_from(&self, s: &Session, base: Vec2, c: Vec2) -> Option<crate::prompt::Drag> {
let (matrix, rubber_from) = match self.op {
Op::Move | Op::Copy => (Mat3::translate(c - base), base),
Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base),
Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base),
Op::Scale => {
let (f, from) = self.scale_reference_factor(base, c)?;
(Mat3::scale_about(base, f), from)
}
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
_ => return None,
};
let mut extra = vec![line(rubber_from, c)];
if self.op != Op::Mirror {
return Some(crate::prompt::Drag { handles: self.objs.clone(), matrix, extra, clipboard: false });
}
// 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 individual = 0;
for h in &self.objs {
let Some(e) = d.entity(*h) else { continue };
if !needs_mirror_preview(&e.kind) {
handles.push(*h);
} else if individual < MAX_MIRROR_OBJECT_PREVIEW {
individual += 1;
let mut k = e.kind.clone();
mirror_kind(&mut k, &matrix);
extra.push(k);
}
}
Some(crate::prompt::Drag { handles, matrix, extra, clipboard: false })
}
/// COPY's prompt once the base point is known, as AutoCAD 2024 asks it.
fn copy_prompt(&self, base: Option<Vec2>) -> Prompt {
match self.copy_array {
@@ -603,7 +671,7 @@ impl Interactive for SelectThen {
}
(Op::Scale, 1, inp @ (Input::Point(_) | Input::Text(_) | Input::Enter)) => {
let f = match inp {
Input::Point(p) => self.pts[0].dist(p),
Input::Point(p) => require_length(Some(self.pts[0].dist(p)))?,
Input::Text(t) => {
number(&t).filter(|f| f.is_finite() && *f > 0.0).ok_or_else(|| EngineError::Other("Requires a positive number.".into()))?
}
@@ -637,35 +705,7 @@ impl Interactive for SelectThen {
return Vec::new();
}
let Some(base) = self.pts.first().copied() else { return Vec::new() };
let (m, rubber_from) = match self.op {
Op::Move | Op::Copy => (Mat3::translate(c - base), base),
Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base),
Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base),
Op::Scale => match self.scale_reference_factor(base, c) {
Some((f, from)) => (Mat3::scale_about(base, f), from),
None => return self.ref_from.map(|a| vec![line(a, c)]).unwrap_or_default(),
},
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
_ => return Vec::new(),
};
let Ok(d) = s.doc() else { return Vec::new() };
let mut out: Vec<EntityKind> = self
.objs
.iter()
.take(500)
.filter_map(|h| d.entity(*h))
.map(|e| {
let mut k = e.kind.clone();
if self.op == Op::Mirror {
mirror_kind(&mut k, &m);
} else {
k.transform(&m);
}
k
})
.collect();
out.push(line(rubber_from, c));
out
self.preview_from(s, base, c)
}
/// Separate shared GPU transforms from objects that need an individual MIRROR preview.
fn drag(&self, s: &Session, c: Vec2) -> Option<crate::prompt::Drag> {
@@ -673,38 +713,7 @@ impl Interactive for SelectThen {
return None;
}
let base = self.pts.first().copied()?;
let (matrix, rubber_from) = match self.op {
Op::Move | Op::Copy => (Mat3::translate(c - base), base),
Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base),
Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base),
Op::Scale => {
let (f, from) = self.scale_reference_factor(base, c)?;
(Mat3::scale_about(base, f), from)
}
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
_ => return None,
};
let mut extra = vec![line(rubber_from, c)];
if self.op != Op::Mirror {
return Some(crate::prompt::Drag { handles: self.objs.clone(), matrix, extra, clipboard: false });
}
// 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 individual = 0;
for h in &self.objs {
let Some(e) = d.entity(*h) else { continue };
if !needs_mirror_preview(&e.kind) {
handles.push(*h);
} else if individual < MAX_MIRROR_OBJECT_PREVIEW {
individual += 1;
let mut k = e.kind.clone();
mirror_kind(&mut k, &matrix);
extra.push(k);
}
}
Some(crate::prompt::Drag { handles, matrix, extra, clipboard: false })
self.drag_from(s, base, c)
}
}
@@ -715,15 +724,55 @@ pub(super) struct DisplaceM {
displacement: bool,
/// COPY's mOde option: asking Single or Multiple.
ask_mode: bool,
/// A perpendicular or tangent picked at the base point prompt, waiting for the second point
/// it is measured from (#3481), as LINE's first point does.
deferred_base: Option<crate::snap::Deferred>,
/// The last second point gave the deferred base no perpendicular foot or tangent point: the
/// prompt says so and asks for another.
no_base_from_second: bool,
}
impl DisplaceM {
pub(super) fn new(op: Op) -> Self {
DisplaceM { inner: SelectThen::new(op), displacement: false, ask_mode: false }
DisplaceM { inner: SelectThen::new(op), displacement: false, ask_mode: false, deferred_base: None, no_base_from_second: false }
}
/// At "Specify base point": objects selected, no point yet.
fn at_base(&self) -> bool {
self.inner.sel.done && self.inner.pts.is_empty() && !self.displacement
self.inner.sel.done && self.inner.pts.is_empty() && !self.displacement && self.deferred_base.is_none()
}
/// The base a deferred perpendicular or tangent `d` resolves to from the second point `p`:
/// the foot of the perpendicular from `p`, or the tangent point seen from it.
fn resolve_base(d: crate::snap::Deferred, p: Vec2) -> Option<Vec2> {
crate::snap::resolve_deferred(crate::snap::LineEnd::Deferred(d), crate::snap::LineEnd::Point(p)).map(|(base, _)| base)
}
/// The second point after a deferred base: the base is resolved from it, then the point
/// moves or copies the objects as if the base had been picked (COPY keeps the base).
/// Anything but a point, or a point the base cannot be resolved from, asks again; the prompt
/// then says why ([`Self::second_point_prompt`]), so the text reaches the user translated.
fn second_point_after_deferred(&mut self, s: &mut Session, d: crate::snap::Deferred, i: Input) -> Result<Step> {
let Input::Point(p) = i else { return Ok(Step::Continue) };
let Some(base) = Self::resolve_base(d, p) else {
self.no_base_from_second = true;
return Ok(Step::Continue);
};
self.no_base_from_second = false;
self.deferred_base = None;
self.inner.pts.push(base);
self.inner.input(s, Input::Point(p))
}
/// The second point prompt after the deferred base `d`. Each message is a whole English
/// sentence, the key the interface translates the prompt by.
fn second_point_prompt(&self, d: crate::snap::Deferred) -> Prompt {
let message = match (self.no_base_from_second, d.mode == crate::snap::mode::TAN) {
(false, _) => "Specify second point",
(true, true) => "No tangent from that point. Specify another second point",
(true, false) => "No perpendicular from that point. Specify another second point",
};
Prompt::new(message, Accept::POINT)
}
/// The deferred base resolved from the cursor `c`, for the preview.
fn preview_base(&self, c: Vec2) -> Option<Vec2> {
Self::resolve_base(self.deferred_base?, c)
}
}
@@ -751,7 +800,10 @@ impl Interactive for DisplaceM {
Op::Copy => &["Displacement", "mOde"],
_ => &["Displacement"],
};
return Prompt::new("Specify base point", Accept::POINT).kw(kw).default("Displacement");
return Prompt::new("Specify base point", Accept::POINT).kw(kw).default("Displacement").deferred();
}
if let Some(d) = self.deferred_base {
return self.second_point_prompt(d);
}
self.inner.prompt(s)
}
@@ -779,6 +831,15 @@ impl Interactive for DisplaceM {
self.ask_mode = false;
return Ok(Step::Continue);
}
if let Some(d) = self.deferred_base {
return self.second_point_after_deferred(s, d, i);
}
if self.at_base()
&& let Input::Deferred(d) = i
{
self.deferred_base = Some(d);
return Ok(Step::Continue);
}
if self.at_base() && (matches!(&i, Input::Enter) || matches!(&i, Input::Keyword(k) if k == "Displacement")) {
self.displacement = true;
return Ok(Step::Continue);
@@ -802,12 +863,18 @@ impl Interactive for DisplaceM {
if self.displacement {
return Vec::new();
}
if self.deferred_base.is_some() {
return self.preview_base(c).map(|base| self.inner.preview_from(s, base, c)).unwrap_or_default();
}
self.inner.preview(s, c)
}
fn drag(&self, s: &Session, c: Vec2) -> Option<crate::prompt::Drag> {
if self.displacement {
return None;
}
if self.deferred_base.is_some() {
return self.inner.drag_from(s, self.preview_base(c)?, c);
}
self.inner.drag(s, c)
}
}
+19 -3
View File
@@ -49,9 +49,9 @@ pub(crate) fn edge_segments_over(s: &Session, edges: Edges, exclude: Handle, ove
// its first piece under the object's handle and the others under new ones, so only the first
// stays one of the picked edges, as in a run of trims on the drawing itself.
let is_edge = |h: &Handle| edges.only.is_none_or(|es| es.contains(h));
for e in store.iter() {
let mut visit = |e: &Entity| {
if !d.is_visible(e) {
continue;
return;
}
match overlay.get(&e.handle) {
Some(pieces) => {
@@ -64,6 +64,22 @@ pub(crate) fn edge_segments_over(s: &Session, edges: Edges, exclude: Handle, ove
None if e.handle != exclude && is_edge(&e.handle) => add(&e.kind),
None => {}
}
};
match edges.only {
// Only the given edges: look them up rather than scan the whole space for them. A piece
// of one is keyed by its handle in the overlay, and the other pieces are never edges.
Some(es) => {
let mut seen = std::collections::HashSet::new();
for e in es.iter().filter(|h| seen.insert(**h) && store.contains(**h)).filter_map(|h| d.entity(*h)) {
visit(e);
}
}
// Every object is an edge (Quick mode, run on every preview): walk the space as it is.
None => {
for e in store.iter() {
visit(e);
}
}
}
Ok(out)
}
@@ -392,7 +408,7 @@ const MAX_SELF_CROSSINGS: usize = 1 << 16;
/// across it, on lines, arcs and circles too. On open polylines from 1e-3 to 1e9 long it was within
/// 5e-7, and 5.1e-7 away trimmed at the cut (around a closed rectangle it reached a little further,
/// to 1e-6; on a line, further still, to 5e-4 on one 10 long).
const ON_CUT: f64 = 5e-7;
pub(crate) const ON_CUT: f64 = 5e-7;
/// The refusal when every cut was passed over ([`ON_CUT`]): the object meets an edge, at the pick,
/// so Quick mode leaves it in place rather than erasing it as one no edge crosses.
+5 -31
View File
@@ -240,34 +240,8 @@ fn tolerance(sp: &Spline, tol: f64) -> Result<Spline> {
// ---------------- control points ----------------
/// The number of distinct control points: control points that wrap round repeat their first
/// `degree` at the end, and a clamped closed spline repeats its first at the end.
fn distinct(sp: &Spline) -> usize {
let n = sp.control.len();
if sp.wraps() {
n.saturating_sub(sp.degree)
} else if sp.closed && n > 2 && sp.control.first().zip(sp.control.last()).is_some_and(|(a, b)| a.near(*b, 1e-12)) {
n - 1
} else {
n
}
}
/// Indices holding distinct control point `j` (with its repeats).
fn copies(sp: &Spline, j: usize) -> Vec<usize> {
let (n, u) = (sp.control.len(), distinct(sp));
if j >= u {
return Vec::new();
}
let mut out = vec![j];
if u < n {
out.extend((j + u..n).step_by(u.max(1)));
}
out
}
fn move_control(sp: &Spline, j: usize, to: Vec2) -> Result<Spline> {
let ix = copies(sp, j);
let ix = sp.control_copies(j);
if ix.is_empty() {
return Err(bad("splinedit", "control point index out of range"));
}
@@ -284,7 +258,7 @@ fn set_weight(sp: &Spline, j: usize, w: f64) -> Result<Spline> {
if !(w.is_finite() && w > 0.0) {
return Err(other("Requires a positive weight."));
}
let ix = copies(sp, j);
let ix = sp.control_copies(j);
if ix.is_empty() {
return Err(bad("splinedit", "control point index out of range"));
}
@@ -307,7 +281,7 @@ fn set_weight(sp: &Spline, j: usize, w: f64) -> Result<Spline> {
/// shape as far as it can.
fn delete_control(sp: &Spline, j: usize) -> Result<Spline> {
let p = sp.degree;
let (n, u) = (sp.control.len(), distinct(sp));
let (n, u) = (sp.control.len(), sp.distinct_controls());
if j >= u {
return Err(bad("splinedit", "control point index out of range"));
}
@@ -478,7 +452,7 @@ impl SplineditM {
if fit {
sp.fit.clone()
} else {
let u = distinct(&sp);
let u = sp.distinct_controls();
sp.control.into_iter().take(u).collect()
}
}
@@ -820,7 +794,7 @@ impl Interactive for SplineditM {
Sub::VertexOrder => self.input_order(s, &sp, &i)?,
Sub::VertexDelete => match point {
Some(p) => {
let u = distinct(&sp);
let u = sp.distinct_controls();
let j = nearest(sp.control.get(..u).unwrap_or_default(), p).ok_or_else(|| other("The spline has no control points."))?;
self.apply(s, json!({ "option": "vertexdelete", "index": j }))?;
}
+3
View File
@@ -411,6 +411,9 @@ fn chspace_json_and_command_line() {
layer_colors: Vec::new(),
clip: None,
on: true,
ucs: None,
ucs_per_viewport: false,
extra: Vec::new(),
twist: 0.0,
};
s.doc_mut().unwrap().add(&Space::Paper("Layout1".into()), Default::default(), EntityKind::Viewport(vp)).unwrap();
@@ -48,6 +48,7 @@ pub(crate) fn line_box(t: &cadcraft_doc::Text) -> cadcraft_doc::MText {
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}
}
@@ -95,6 +96,7 @@ pub(crate) fn editor_for(s: &Session, h: Handle) -> Option<crate::TextEditor> {
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
};
Some(TextEditor { mtext, kind: EditorKind::Dimension { measured }, key, extents: None })
}
+1
View File
@@ -89,6 +89,7 @@ impl MTextOpts {
line_spacing: self.spacing,
line_spacing_exact: self.exact,
columns: self.columns.clone().filter(|_| width > 0.0),
background: None,
}
}
}
+8 -2
View File
@@ -7,6 +7,7 @@ mod dash_units;
mod matchprop;
mod rename;
mod set;
pub(crate) mod xdata;
pub use matchprop::MatchProps;
use set::run_set;
@@ -24,10 +25,11 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("properties", "Properties", run_get).menu(&["Modify", "Properties"]).alias(&["pr", "props", "ch"]).params("{handles?} → properties of the selection").noundo(),
CommandSpec::new("properties.set", "Set Properties", run_set).params(
"{handles?, layer?, color?, linetype?, lineweight?, ltscale?, thickness?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, annotative?, \
<geometry fields: radius, center, start, end, text, height, rotation…>, text: style?, justify?, oblique?, positionX/Y/Z?, alignmentX/Y?, \
<geometry fields: radius, center, start, end, text, height, rotation…>, text: style?, justify?, oblique?, backwards?, upsideDown?, positionX/Y/Z?, alignmentX/Y?, \
mtext: style?, justify?, lineSpacing?, lineSpacingDistance?, lineSpacingStyle?: atLeast | exactly, positionX/Y/Z?, \
dimension: dimStyle?, textOverride?, textRotation?, textPositionX/Y?, prefix?, suffix?, altPrefix?, altSuffix?, dimScale?, precision?, \
<dimension style variables (field or DIM* name, e.g. textHeight / DIMTXT) set as overrides of each dimension>, clearOverrides?, clear?: [variable]} \
<dimension style variables (field or DIM* name, e.g. textHeight / DIMTXT) set as overrides of each dimension>, clearOverrides?, clear?: [variable], \
xdata?: {\"APP\": [[code, value], …] | null} (replaces or removes that application's extended data; codes 1000–1071, points as [1010, [x, y, z]])} \
→ {changed, locked, message?, ignored: keys no selected object took} (the keys are those of `properties.describe` rows): objects on locked layers \
(and, during REFEDIT, outside the working set) are left out, and `message` says how many",
),
@@ -125,6 +127,9 @@ pub(super) fn entity_props(d: &cadcraft_doc::Drawing, e: &cadcraft_doc::Entity)
o.insert("annotative".into(), json!(cadcraft_doc::is_annotative(e)));
o.insert("annotativeScales".into(), json!(e.common.anno_scales.iter().map(|s| s.name.clone()).collect::<Vec<_>>()));
}
if let (Some(x), Some(o)) = (xdata::xdata_json(&e.common.xdata), v.as_object_mut()) {
o.insert("xdata".into(), x);
}
let geo = serde_json::to_value(&e.kind).unwrap_or(Value::Null);
if let (Some(o), Some(g)) = (v.as_object_mut(), geo.as_object()) {
o.insert("geometry".into(), Value::Object(g.clone()));
@@ -1047,6 +1052,7 @@ fn run_rename(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
d.rename_proxy_linetype(&from, &to);
}
_ => return Err(bad("rename", "unsupported table")),
}
+39
View File
@@ -48,6 +48,7 @@ const SET_KEYS: &[&str] = &[
"suffix",
"altPrefix",
"altSuffix",
"xdata",
// An insert's or hatch's scale; a dimension's overall scale is `dimScale` (or DIMSCALE).
"scale",
];
@@ -324,6 +325,32 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
.map(|n| d.text_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("text style `{n}` not found"))))
.transpose()?;
let dim_vars = DimVars::new(d, p)?;
// xdata is checked before anything changes (`ensure_layer` below adds a layer the drawing
// keeps even when the command then fails): no object may end up with more xdata than a
// file holds for one.
let xd = p.get("xdata").filter(|v| !v.is_null()).map(super::xdata::xdata_from_json).transpose().map_err(|m| bad("properties.set", m))?;
if let Some(changes) = &xd {
for h in &hs {
let Some(e) = d.entity(*h) else { continue };
// A dimension's `ACAD` run is written from its overrides (textHeight, arrowSize…) and
// read back into them: raw groups under that name would be lost on save.
if let Some((app, _)) = changes.iter().find(|(app, _)| cadcraft_doc::is_model_xdata_app(app, &e.kind)) {
return Err(bad(
"properties.set",
format!(
"{}: xdata application {app} of a {} is written from its own properties and can't be set as raw data",
h.hex(),
e.kind.dxf_name()
),
));
}
let mut after = e.common.xdata.clone();
super::xdata::apply(&mut after, changes);
if after.len() > cadcraft_doc::MAX_XDATA_GROUPS {
return Err(bad("properties.set", format!("{}: xdata would exceed {} groups", h.hex(), cadcraft_doc::MAX_XDATA_GROUPS)));
}
}
}
// A pattern must be one each hatch can take, as HATCHEDIT refuses others.
if let Some(v) = str_param(p, "pattern").filter(|v| !v.trim().is_empty())
&& hs.iter().any(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Hatch(x)) if !crate::cmd::hatch::takes_pattern(x, v)))
@@ -373,6 +400,10 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
EntityKind::Hatch(ha) => hatch(ha, &c, &mut used),
_ => {}
}
if let Some(changes) = &xd {
super::xdata::apply(&mut e.common.xdata, changes);
used.insert("xdata");
}
})?;
}
let ignored: Vec<&str> = p
@@ -548,6 +579,14 @@ fn text(t: &mut Text, c: &Call<'_>, h: Handle, used: &mut Used<'_>) {
t.oblique = x.to_radians();
used.insert("oblique");
}
if let Some(b) = p.get("backwards").and_then(Value::as_bool) {
t.backwards = b;
used.insert("backwards");
}
if let Some(b) = p.get("upsideDown").and_then(Value::as_bool) {
t.upside_down = b;
used.insert("upsideDown");
}
if let Some((ha, va)) = str_param(p, "justify").and_then(crate::cmd::draw::justify) {
set_justify(t, ha, va, c.prep.ends.get(&h).copied());
used.insert("justify");
+293
View File
@@ -0,0 +1,293 @@
//! Xdata as JSON, for `entities`, `properties` and `properties.set`: an object by application,
//! `{"APP": [[code, value], …]}`, with each group's value typed by its code: strings for 1000,
//! 1002 (`{` / `}`), 1003 (a layer name), 1004 (hex) and 1005 (a handle), a point `[x, y, z]`
//! for 1010–1013 (its 1020 and 1030 groups folded in), numbers for 1040–1042, integers for
//! 1070 and 1071. Setting takes the same form; `null` for an application removes its data.
use cadcraft_doc::{MAX_XDATA_GROUPS, RawTag, check_xdata_app_name, check_xdata_groups, is_reserved_xdata_app, set_xdata_app, xdata_apps};
use serde_json::{Map, Value, json};
/// Most applications one `properties.set` call may set.
const MAX_APPS_PER_CALL: usize = 256;
/// Which applications' xdata a query returns.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) enum XdataSelect {
/// None (the default).
#[default]
None,
/// Every application's.
All,
/// These applications' (any case); an entity without any of them doesn't match the query.
Apps(Vec<String>),
}
impl XdataSelect {
/// The `xdata` parameter of a query: `true`, `false`, an application name or a list of names.
pub(crate) fn parse(v: Option<&Value>) -> Result<Self, String> {
const MSG: &str = "`xdata` must be true, false, an application name or a list of names";
match v {
None | Some(Value::Null) => Ok(Self::None),
Some(Value::Bool(b)) => Ok(if *b { Self::All } else { Self::None }),
Some(Value::String(s)) => Ok(Self::Apps(vec![s.clone()])),
Some(Value::Array(a)) if !a.is_empty() && a.len() <= MAX_APPS_PER_CALL => {
a.iter().map(|x| x.as_str().map(str::to_string).ok_or_else(|| MSG.to_string())).collect::<Result<Vec<_>, _>>().map(Self::Apps)
}
Some(_) => Err(MSG.into()),
}
}
/// Whether the selection narrows a query to entities carrying the named applications' data.
pub(crate) fn filters(&self) -> bool {
matches!(self, Self::Apps(_))
}
/// Whether an entity with this xdata passes the filter.
pub(crate) fn matches(&self, xdata: &[RawTag]) -> bool {
match self {
Self::None | Self::All => true,
Self::Apps(apps) => xdata_apps(xdata).iter().any(|(name, _)| apps.iter().any(|a| a.trim().eq_ignore_ascii_case(name))),
}
}
/// The selected applications' data of an entity as JSON; `None` when there is none to show.
pub(crate) fn json(&self, xdata: &[RawTag]) -> Option<Value> {
let apps = match self {
Self::None => return None,
Self::All => None,
Self::Apps(apps) => Some(apps),
};
let mut out = Map::new();
for (name, groups) in xdata_apps(xdata) {
if apps.is_some_and(|apps| !apps.iter().any(|a| a.trim().eq_ignore_ascii_case(name))) {
continue;
}
// A second run of the same application (not something AutoCAD writes; `ACME` and
// `acme` are one application, as `set_xdata_app` treats them) joins the first.
let key = out.keys().find(|k| k.eq_ignore_ascii_case(name)).cloned();
match key.and_then(|k| out.get_mut(&k)) {
Some(Value::Array(v)) => v.extend(groups_json(groups)),
_ => {
out.insert(name.to_string(), Value::Array(groups_json(groups)));
}
}
}
(!out.is_empty()).then_some(Value::Object(out))
}
}
/// Every application's data of an entity as JSON; `None` when it has none.
pub(crate) fn xdata_json(xdata: &[RawTag]) -> Option<Value> {
XdataSelect::All.json(xdata)
}
fn number(t: &RawTag) -> Value {
t.value.trim().parse::<f64>().ok().filter(|v| v.is_finite()).map_or_else(|| json!(t.value), |v| json!(v))
}
fn integer(t: &RawTag) -> Value {
t.value.trim().parse::<i64>().map_or_else(|_| json!(t.value), |v| json!(v))
}
/// One application's groups as `[code, value]` pairs, points folded.
fn groups_json(groups: &[RawTag]) -> Vec<Value> {
let mut out = Vec::with_capacity(groups.len());
let mut i = 0;
while let Some(t) = groups.get(i) {
let v = match t.code {
1010..=1013 => {
let y = groups.get(i + 1).filter(|y| y.code == t.code + 10);
let z = groups.get(i + 2).filter(|z| z.code == t.code + 20);
if let (Some(y), Some(z)) = (y, z) {
i += 3;
out.push(json!([t.code, [number(t), number(y), number(z)]]));
continue;
}
number(t)
}
1020..=1033 | 1040..=1042 => number(t),
1070 | 1071 => integer(t),
_ => json!(t.value),
};
out.push(json!([t.code, v]));
i += 1;
}
out
}
/// What `properties.set`'s `xdata` parameter asks for: per application, its new groups (with
/// their `1001` left out) or `None` to remove it. Everything is checked here: names, codes, value
/// types and ranges, braces, sizes; reserved applications are refused.
pub(crate) fn xdata_from_json(v: &Value) -> Result<Vec<(String, Option<Vec<RawTag>>)>, String> {
let Some(obj) = v.as_object() else { return Err("`xdata` must be an object {\"APP\": [[code, value], …] | null}".into()) };
if obj.len() > MAX_APPS_PER_CALL {
return Err(format!("`xdata` may name at most {MAX_APPS_PER_CALL} applications"));
}
let mut out = Vec::with_capacity(obj.len());
for (app, groups) in obj {
check_xdata_app_name(app).map_err(|e| e.to_string())?;
if is_reserved_xdata_app(app) {
return Err(format!("xdata application `{app}` is reserved: CADCraft writes its data itself"));
}
let groups = match groups {
Value::Null => None,
Value::Array(a) => Some(groups_from_json(app, a)?),
_ => return Err(format!("xdata of `{app}` must be a list of [code, value] pairs, or null to remove it")),
};
out.push((app.trim().to_string(), groups));
}
Ok(out)
}
/// `[[code, value], …]` of one application as groups, each value checked for its code.
fn groups_from_json(app: &str, pairs: &[Value]) -> Result<Vec<RawTag>, String> {
if pairs.len() > MAX_XDATA_GROUPS {
return Err(format!("xdata of `{app}`: at most {MAX_XDATA_GROUPS} groups"));
}
let mut out = Vec::with_capacity(pairs.len());
for (n, pair) in pairs.iter().enumerate() {
let at = || format!("xdata of `{app}`, group {}", n + 1);
let (code, value) = match pair.as_array().map(Vec::as_slice) {
Some([c, v]) => (c.as_i64().and_then(|c| i32::try_from(c).ok()).ok_or_else(|| format!("{}: the code must be an integer", at()))?, v),
_ => return Err(format!("{}: each group is a [code, value] pair", at())),
};
let real = |x: &Value| x.as_f64().filter(|x| x.is_finite()).map(craft_dxf::format_real);
match code {
1000 | 1003 => {
let s = value.as_str().ok_or_else(|| format!("{}: group {code} takes a string", at()))?;
out.push(RawTag { code, value: s.to_string() });
}
1002 => match value.as_str() {
Some(b @ ("{" | "}")) => out.push(RawTag { code, value: b.to_string() }),
_ => return Err(format!("{}: group 1002 takes \"{{\" or \"}}\"", at())),
},
1004 => {
let s = value.as_str().ok_or_else(|| format!("{}: group 1004 takes hex text", at()))?;
out.push(RawTag { code, value: s.trim().to_ascii_uppercase() });
}
1005 => {
let s = value.as_str().ok_or_else(|| format!("{}: group 1005 takes a hex handle", at()))?;
out.push(RawTag { code, value: s.trim().to_ascii_uppercase() });
}
1010..=1013 => {
let p = value.as_array().filter(|a| a.len() == 2 || a.len() == 3).and_then(|a| a.iter().map(real).collect::<Option<Vec<_>>>());
let Some(p) = p else { return Err(format!("{}: group {code} takes a point [x, y, z] of finite numbers", at())) };
out.push(RawTag { code, value: p.first().cloned().unwrap_or_default() });
out.push(RawTag { code: code + 10, value: p.get(1).cloned().unwrap_or_default() });
out.push(RawTag { code: code + 20, value: p.get(2).cloned().unwrap_or_else(|| "0.0".into()) });
}
1020..=1023 | 1030..=1033 => return Err(format!("{}: give the point as [{}, [x, y, z]]", at(), 1010 + (code % 10))),
1040..=1042 => {
let x = real(value).ok_or_else(|| format!("{}: group {code} takes a finite number", at()))?;
out.push(RawTag { code, value: x });
}
1070 | 1071 => {
let i = value.as_i64().ok_or_else(|| format!("{}: group {code} takes an integer", at()))?;
out.push(RawTag { code, value: i.to_string() });
}
_ => return Err(format!("{}: {code} is not an xdata group code (1000–1071)", at())),
}
}
check_xdata_groups(&out).map_err(|e| format!("xdata of `{app}`: {e}"))?;
Ok(out)
}
/// Apply a parsed `xdata` parameter to an entity's xdata.
pub(crate) fn apply(xdata: &mut Vec<RawTag>, changes: &[(String, Option<Vec<RawTag>>)]) {
for (app, groups) in changes {
set_xdata_app(xdata, app, groups.as_deref());
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
fn t(code: i32, value: &str) -> RawTag {
RawTag { code, value: value.into() }
}
#[test]
fn json_round_trip_types_every_kind() {
let x = vec![
t(1001, "ACME"),
t(1000, "D-07"),
t(1002, "{"),
t(1003, "Walls"),
t(1004, "0AFF"),
t(1005, "2A"),
t(1010, "1.5"),
t(1020, "2.0"),
t(1030, "0.0"),
t(1040, "2.5"),
t(1070, "3"),
t(1071, "70000"),
t(1002, "}"),
t(1001, "PE_URL"),
t(1000, "https://example.com"),
];
let j = xdata_json(&x).unwrap();
assert_eq!(
j["ACME"],
json!([
[1000, "D-07"],
[1002, "{"],
[1003, "Walls"],
[1004, "0AFF"],
[1005, "2A"],
[1010, [1.5, 2.0, 0.0]],
[1040, 2.5],
[1070, 3],
[1071, 70000],
[1002, "}"]
])
);
assert_eq!(j["PE_URL"], json!([[1000, "https://example.com"]]));
let back = xdata_from_json(&j).unwrap();
let mut y = Vec::new();
apply(&mut y, &back);
assert_eq!(y, x);
assert_eq!(xdata_json(&[]), None);
assert_eq!(XdataSelect::Apps(vec!["pe_url".into()]).json(&x).unwrap().as_object().unwrap().len(), 1);
assert!(XdataSelect::Apps(vec!["nope".into()]).json(&x).is_none());
assert!(!XdataSelect::Apps(vec!["nope".into()]).matches(&x) && XdataSelect::Apps(vec!["acme".into()]).matches(&x));
}
#[test]
fn bad_input_is_refused() {
for bad in [
json!([]),
json!({"": [[1000, "x"]]}),
json!({"CADCRAFT": [[1000, "x"]]}),
json!({"A": [[1000, 5]]}),
json!({"A": [[1001, "B"]]}),
json!({"A": [[8, "layer"]]}),
json!({"A": [[1002, "("]]}),
json!({"A": [[1002, "{"]]}),
json!({"A": [[1010, [1, 2, 3, 4]]]}),
json!({"A": [[1010, [1, "x"]]]}),
json!({"A": [[1010, 1]]}),
json!({"A": [[1020, 1]]}),
json!({"A": [[1040, "1"]]}),
json!({"A": [[1070, 1.5]]}),
json!({"A": [[1070, 70000]]}),
json!({"A": [[1071, 1e12]]}),
json!({"A": [[1004, "ABC"]]}),
json!({"A": [[1005, "xyz"]]}),
json!({"A": [1000, "x"]}),
json!({"A": "x"}),
json!({"A": [[1000, "x".repeat(300)]]}),
] {
assert!(xdata_from_json(&bad).is_err(), "{bad}");
}
assert_eq!(xdata_from_json(&json!({"A": null})).unwrap(), vec![("A".to_string(), None)]);
assert_eq!(xdata_from_json(&json!({"A": []})).unwrap(), vec![("A".to_string(), Some(Vec::new()))]);
assert!(XdataSelect::parse(Some(&json!(1))).is_err());
assert!(XdataSelect::parse(Some(&json!([]))).is_err());
assert!(XdataSelect::parse(Some(&json!([1]))).is_err());
assert_eq!(XdataSelect::parse(Some(&json!(true))).unwrap(), XdataSelect::All);
assert_eq!(XdataSelect::parse(Some(&json!("A"))).unwrap(), XdataSelect::Apps(vec!["A".into()]));
assert_eq!(XdataSelect::parse(None).unwrap(), XdataSelect::None);
}
}
+186 -12
View File
@@ -1,6 +1,6 @@
//! Paste tabular clipboard data (TSV from Excel or other spreadsheets) as a native `ACAD_TABLE`.
use cadcraft_doc::{EntityKind, Table, TableCell, TableStyle};
use cadcraft_doc::{CellStyle, EntityKind, Table, TableCell, TableStyle};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
@@ -85,33 +85,54 @@ pub fn is_tsv_table(text: &str) -> bool {
}
/// Build an `ACAD_TABLE` entity from parsed cell strings, sizing columns and rows cleanly.
fn build_table(st: &TableStyle, at: Vec2, data: &[Vec<String>], text_height: Option<f64>) -> Table {
fn build_table(doc: &cadcraft_doc::Drawing, st: &TableStyle, at: Vec2, data: &[Vec<String>], text_height: Option<f64>) -> Table {
let cols = data.first().map_or(1, Vec::len).max(1);
let th = text_height.unwrap_or_else(|| if st.text_height.is_finite() && st.text_height > 0.0 { st.text_height } else { 2.5 });
let margin = if st.text_height.is_finite() && st.text_height > 0.0 { st.margin * (th / st.text_height) } else { th * 0.5 };
// Why: `cadcraft_render::table::layout` scales the resolved `Data` cell style's text height
// and horizontal/vertical margins by `th / st.text_height`, so sizing widths, wrap width, and
// row heights with the same scaled `Data` metrics keeps wrapped text inside custom-styled cells.
let scale = if st.text_height.is_finite() && st.text_height > 0.0 { th / st.text_height } else { 1.0 };
let data_cs = st.cell_style(CellStyle::DATA);
let cell_th = Some(data_cs.text_height * scale).filter(|v| v.is_finite() && *v > 0.0).unwrap_or(th);
let margin_h = Some(data_cs.margin_h * scale).filter(|v| v.is_finite() && *v >= 0.0).unwrap_or(th * 0.5);
let margin_v = Some(data_cs.margin_v * scale).filter(|v| v.is_finite() && *v >= 0.0).unwrap_or(th * 0.5);
let mut col_chars = vec![1usize; cols];
let mut row_heights = Vec::with_capacity(data.len());
let mut cells = Vec::with_capacity(data.len());
for row in data {
let mut max_lines = 1usize;
let mut table_row = Vec::with_capacity(cols);
for (c, raw) in row.iter().enumerate() {
let line_count = raw.split('\n').count().clamp(1, 50);
max_lines = max_lines.max(line_count);
let max_chars = raw.split('\n').map(|line| line.chars().count()).max().unwrap_or(0).clamp(1, 60);
if let Some(slot) = col_chars.get_mut(c) {
*slot = (*slot).max(max_chars);
}
table_row.push(TableCell { text: cadcraft_doc::mtext_literal(raw), ..TableCell::default() });
}
row_heights.push(th * (max_lines as f64 * 5.0 / 3.0) + 2.0 * margin);
cells.push(table_row);
}
let min_col_w = (th * 4.0 + 2.0 * margin).max(th * 5.0);
let col_widths: Vec<f64> = col_chars.into_iter().map(|chars| (0.75 * th * chars as f64 + 2.0 * margin + 0.5 * th).max(min_col_w)).collect();
let min_col_w = (cell_th * 4.0 + 2.0 * margin_h).max(cell_th * 5.0);
let col_widths: Vec<f64> =
col_chars.into_iter().map(|chars| (0.95 * cell_th * chars as f64 + 2.0 * margin_h + 0.5 * cell_th).max(min_col_w)).collect();
let mut row_heights = Vec::with_capacity(cells.len());
for row in &cells {
let mut max_lines = 1usize;
for (c, cell) in row.iter().enumerate() {
if cell.text.is_empty() {
continue;
}
// Why: share the renderer's resolved MTEXT sizing inputs (named font, width_factor,
// oblique) so pasted row heights match how `cadcraft_render::table::draw` wraps cells.
let inner_w = col_widths.get(c).copied().unwrap_or(0.0) - 2.0 * margin_h;
let wrap_w = if inner_w.is_finite() && inner_w > 0.0 { inner_w } else { 0.0 };
let mp = cadcraft_render::table_text_mtext_params(doc, &data_cs.text_style, Vec2::ZERO, cell_th, data_cs.align.clamp(1, 9), wrap_w);
let line_count = cadcraft_fonts::layout_mtext_with(&cell.text, &mp).lines.len().max(1);
max_lines = max_lines.max(line_count);
}
row_heights.push(cell_th * (max_lines as f64 * 5.0 / 3.0) + 2.0 * margin_v);
}
Table { insert: v3(at), col_widths, row_heights, cells, style: st.name.clone(), text_height: th, title: false, header: false, ..Table::default() }
}
@@ -142,7 +163,7 @@ pub(super) fn run_pastetable(s: &mut Session, p: &Value) -> Result<Value> {
let rows = data.len();
let cols = data.first().map_or(0, Vec::len);
let st = style_of(s);
let table = build_table(&st, at, &data, th);
let table = build_table(s.doc()?, &st, at, &data, th);
let h = s.add_entity(EntityKind::Table(table))?;
s.set_selection(vec![h]);
Ok(json!({ "handle": h.hex(), "rows": rows, "cols": cols }))
@@ -207,7 +228,16 @@ impl Session {
let rows = data.len();
let cols = data.first().map_or(0, Vec::len);
let st = style_of(self);
let table = build_table(&st, Vec2::ZERO, &data, text_height);
let fallback;
let doc = match self.doc() {
Ok(d) => d,
Err(_) => {
fallback = cadcraft_doc::Drawing::default();
&fallback
}
};
let table = build_table(doc, &st, Vec2::ZERO, &data, text_height);
self.last_paste_table = Some((tsv.to_string(), text_height));
let enabled = crate::find_command("pastetable").map_or((|_| Ok(())) as fn(&Session) -> std::result::Result<(), String>, |c| c.enabled);
self.launch_interactive("pastetable", enabled, Box::new(PasteTableM { table, rows, cols }))
}
@@ -301,4 +331,148 @@ mod tests {
assert_eq!(s.commands_started, before_started + 1);
assert_eq!(s.last_command.as_deref(), Some("pastetable"));
}
#[test]
fn long_wrapped_cells_cap_col_width_and_grow_row_height() {
let mut s = Session::new();
let long_cell = "Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega";
assert!(long_cell.chars().count() > 60);
let tsv = format!("Short\t{long_cell}\n\"First line\n{long_cell}\"\t\nA\tB",);
let res = s.execute("pastetable", &json!({ "tsv": tsv, "at": [0, 0], "text_height": 2.0 })).unwrap();
let h = cadcraft_doc::Handle::parse_hex(res["handle"].as_str().unwrap()).unwrap();
let e = s.doc().unwrap().entity(h).unwrap();
let EntityKind::Table(t) = &e.kind else { panic!("expected table") };
// Column 1 width is capped at 60 characters rather than growing unboundedly.
let st = style_of(&s);
let expected_cap_w = 0.95 * 2.0 * 60.0 + 2.0 * (st.margin * (2.0 / st.text_height)) + 0.5 * 2.0;
assert!((t.col_widths[1] - expected_cap_w).abs() < 1e-9);
// Row 0 wraps into multiple lines and is taller than single-line Row 2.
assert!(t.row_heights[0] > t.row_heights[2]);
// Row 1 combines a hard newline and a long wrapped line, making it taller than Row 0.
assert!(t.row_heights[1] > t.row_heights[0]);
}
#[test]
fn custom_data_cell_style_sizes_wrapped_rows_and_columns() {
let long_cell = "Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega";
let tsv = format!("Short\t{long_cell}\nA\tB");
let mut base = Session::new();
let r_base = base.execute("pastetable", &json!({ "tsv": tsv, "at": [0, 0] })).unwrap();
let h_base = cadcraft_doc::Handle::parse_hex(r_base["handle"].as_str().unwrap()).unwrap();
let EntityKind::Table(t_base) = &base.doc().unwrap().entity(h_base).unwrap().kind else { panic!("expected table") };
let mut custom = Session::new();
{
let doc = custom.doc_mut().unwrap();
doc.text_styles.push(cadcraft_doc::TextStyle { name: "WideNotes".into(), width_factor: 1.8, ..cadcraft_doc::TextStyle::default() });
doc.table_styles.iter_mut().find(|ts| ts.name.eq_ignore_ascii_case("Standard")).unwrap().set_cell_style(CellStyle {
name: CellStyle::DATA.into(),
text_style: "WideNotes".into(),
text_height: 5.0,
margin_h: 4.0,
margin_v: 3.0,
..CellStyle::default()
});
}
let r_custom = custom.execute("pastetable", &json!({ "tsv": tsv, "at": [0, 0] })).unwrap();
let h_custom = cadcraft_doc::Handle::parse_hex(r_custom["handle"].as_str().unwrap()).unwrap();
let doc = custom.doc().unwrap();
let EntityKind::Table(t_custom) = &doc.entity(h_custom).unwrap().kind else { panic!("expected table") };
assert!(t_custom.col_widths[1] > t_base.col_widths[1]);
assert!(t_custom.row_heights[0] > t_base.row_heights[0]);
assert!(t_custom.row_heights[0] > t_custom.row_heights[1]);
let g = cadcraft_render::table_geometry(doc, t_custom);
let tx = g.texts.iter().find(|tx| tx.row == 0 && tx.col == 1).unwrap();
assert_eq!(tx.style, "WideNotes");
let laid = cadcraft_render::layout_table_text(doc, tx);
let default_laid = cadcraft_fonts::layout_mtext_with(
&tx.text,
&cadcraft_fonts::MTextParams { attach: tx.attach, width: tx.wrap_width, ..cadcraft_fonts::MTextParams::new(tx.at, tx.height) },
);
assert!(laid.lines.len() > default_laid.lines.len(), "wider text style must wrap into more lines");
assert!(t_custom.row_heights[0] >= laid.lines.len() as f64 * tx.height * 5.0 / 3.0 + 2.0 * 3.0 - 1e-6);
assert!(!laid.strokes.is_empty());
for s in &laid.strokes {
for p in s {
assert!(
p.y <= t_custom.insert.y + 1e-6 && p.y >= t_custom.insert.y - t_custom.row_heights[0] - 1e-6,
"rendered stroke spilled outside row 0 [{}..={}]: y={}",
t_custom.insert.y - t_custom.row_heights[0],
t_custom.insert.y,
p.y
);
}
}
}
#[test]
fn cell_wrapping_past_fifty_lines_is_not_clamped() {
let mut s = Session::new();
let long_cell = vec!["word"; 800].join(" ");
let res = s.execute("pastetable", &json!({ "tsv": format!("A\t{long_cell}\n1\t2"), "at": [0, 0], "text_height": 2.0 })).unwrap();
let h = cadcraft_doc::Handle::parse_hex(res["handle"].as_str().unwrap()).unwrap();
let doc = s.doc().unwrap();
let EntityKind::Table(t) = &doc.entity(h).unwrap().kind else { panic!("expected table") };
let g = cadcraft_render::table_geometry(doc, t);
let tx = g.texts.iter().find(|tx| tx.row == 0 && tx.col == 1).unwrap();
let laid = cadcraft_render::layout_table_text(doc, tx);
assert!(laid.lines.len() > 50, "expected >50 wrapped lines, got {}", laid.lines.len());
let st = style_of(&s);
let margin_v = st.margin * (2.0 / st.text_height);
let fifty_line_h = 2.0 * (50.0 * 5.0 / 3.0) + 2.0 * margin_v;
assert!(t.row_heights[0] > fifty_line_h);
assert!((t.row_heights[0] - (2.0 * (laid.lines.len() as f64 * 5.0 / 3.0) + 2.0 * margin_v)).abs() < 1e-9);
}
#[test]
fn enter_repeats_pastetable_with_last_payload() {
let mut s = Session::new();
s.start_paste_table("A\tB\n1\t2\n", Some(3.0)).unwrap();
s.input(Input::Point(Vec2::ZERO)).unwrap();
assert!(s.running.is_none());
s.input(Input::Enter).unwrap();
assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("pastetable"));
s.input(Input::Point(Vec2::new(50.0, 0.0))).unwrap();
assert!(s.running.is_none());
let tables: Vec<_> = s
.doc()
.unwrap()
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Table(t) => Some(t),
_ => None,
})
.collect();
assert_eq!(tables.len(), 2);
assert_eq!(tables[0].cells, tables[1].cells);
assert_eq!(tables[0].text_height, 3.0);
assert_eq!(tables[1].text_height, 3.0);
assert_eq!(tables[0].insert.xy(), Vec2::ZERO);
assert_eq!(tables[1].insert.xy(), Vec2::new(50.0, 0.0));
}
#[test]
fn execute_pastetable_without_tsv_still_errors_and_other_command_overrides_repeat() {
let mut s = Session::new();
let err = s.execute("pastetable", &Value::Null).unwrap_err().to_string();
assert!(err.contains("`tsv` string is required"), "{err}");
s.start_paste_table("A\tB\n1\t2\n", None).unwrap();
s.input(Input::Point(Vec2::ZERO)).unwrap();
for t in ["line", "0,0", "10,0", ""] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none());
s.input(Input::Enter).unwrap();
assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("line"));
}
}
+2
View File
@@ -307,6 +307,8 @@ pub(crate) fn explode(d: &Drawing, e: &Entity, t: &Tolerance) -> Vec<Entity> {
style: st.text_style.clone(),
halign: Default::default(),
valign: Default::default(),
backwards: false,
upside_down: false,
})));
}
v
+27 -10
View File
@@ -397,7 +397,8 @@ impl TrimM {
let e = d.entity(h)?;
// Half a pixel: finer than the eye can tell apart, coarse enough to stay quick.
let tol = (s.pixel_size() / 2.0).max(1e-9);
let part = if self.extend {
let extending = self.extend ^ s.shift_down;
let part = if extending {
let grown = Entity { kind: extended(s, h, cursor, cut).ok()?, ..(**e).clone() };
uncovered(d, &grown, std::slice::from_ref(&e.kind), tol)
} else {
@@ -414,7 +415,8 @@ impl TrimM {
Edges { only: self.edges.as_deref(), implied: !quick && implied }
}
fn select_edges(&mut self, s: &mut Session) {
s.echo(if self.extend { "Select boundary edges ..." } else { "Select cutting edges ..." });
let extending = self.extend ^ s.shift_down;
s.echo(if extending { "Select boundary edges ..." } else { "Select cutting edges ..." });
s.set_selection(Vec::new());
self.stage = Stage::Edges(Vec::new());
}
@@ -503,16 +505,27 @@ impl Interactive for TrimM {
fn prompt(&self, s: &Session) -> Prompt {
match &self.stage {
Stage::Pick => {
let (msg, first) = if self.extend {
("Select object to extend or shift-select to trim", "Boundary edges")
let extending = self.extend ^ s.shift_down;
let (msg, first) = if extending {
let msg = if s.shift_down {
"Select object to extend or release Shift to trim"
} else {
"Select object to extend or shift-select to trim"
};
(msg, "Boundary edges")
} else {
("Select object to trim or shift-select to extend", "cuTting edges")
let msg = if s.shift_down {
"Select object to trim or release Shift to extend"
} else {
"Select object to trim or shift-select to extend"
};
(msg, "cuTting edges")
};
let mut kw = vec![first, "Fence", "Crossing", "mOde", "Project"];
if !quick_mode(s) {
kw.push("Edge");
}
if !self.extend {
if !extending {
kw.push("eRase");
}
kw.push("Undo");
@@ -528,7 +541,8 @@ impl Interactive for TrimM {
Stage::Crossing(None) => Prompt::new("Specify first corner", Accept::POINT),
Stage::Crossing(Some(_)) => Prompt::new("Specify opposite corner", Accept::POINT),
Stage::Mode => {
let msg = if self.extend { "Enter an extend mode option" } else { "Enter a trim mode option" };
let extending = self.extend ^ s.shift_down;
let msg = if extending { "Enter an extend mode option" } else { "Enter a trim mode option" };
Prompt::new(msg, KW).kw(&["Quick", "Standard"]).default(if quick_mode(s) { "Quick" } else { "Standard" })
}
Stage::Project => {
@@ -551,7 +565,7 @@ impl Interactive for TrimM {
self.cut.take();
let quick = quick_mode(s);
let implied = edge_mode(s);
let extending = self.extend;
let extending = self.extend ^ s.shift_down;
match self.stage.clone() {
Stage::Mode | Stage::Project | Stage::Edge => self.option(s, i),
Stage::Edges(mut picked) => {
@@ -719,7 +733,8 @@ impl Interactive for TrimM {
return None;
}
let px = (s.pixel_size() / 2.0).max(1e-9);
Some(picks_preview(s, &work, self.extend, self.edges(quick, implied), quick, tol, px))
let extending = self.extend ^ s.shift_down;
Some(picks_preview(s, &work, extending, self.edges(quick, implied), quick, tol, px))
}
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
match &self.stage {
@@ -791,7 +806,9 @@ fn uncovered(d: &Drawing, e: &Entity, others: &[EntityKind], tol: f64) -> Vec<En
let mut ts: Vec<f64> = ends.iter().filter(|p| ab.closest(**p).dist(**p) <= near).map(|p| ab.param_of(*p).clamp(0.0, 1.0)).collect();
ts.extend([0.0, 1.0]);
ts.sort_by(f64::total_cmp);
ts.dedup_by(|x, y| (*x - *y).abs() * len <= 1e-9 * (1.0 + a.len()));
// Only cuts that are one point as far as f64 can tell: a tolerance in drawing units
// that grew with the distance from the origin merged real cuts far from it.
ts.dedup_by(|x, y| (*x - *y).abs() * len <= 64.0 * f64::EPSILON * (1.0 + a.len()));
for t in ts.windows(2) {
let (Some(&t0), Some(&t1)) = (t.first(), t.get(1)) else { continue };
let (p, q) = (ab.at(t0), ab.at(t1));
+2
View File
@@ -107,6 +107,7 @@ fn convert(s: &mut Session, hs: &[Handle], o: &Txt2MtxtOptions) -> Result<(Vec<H
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
};
let first = *first;
let rest: Vec<Handle> = items.iter().skip(1).map(|(h, ..)| *h).collect();
@@ -196,6 +197,7 @@ fn single(t: &Text) -> MText {
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}
}
+33 -6
View File
@@ -1,7 +1,7 @@
//! View menu: ZOOM (with Realtime and Dynamic), PAN, REGEN, REDRAW, named views (VIEW), the view
//! twist (DVIEW TWist), layout switching.
use cadcraft_doc::{Space, entity_bounds};
use cadcraft_doc::{BlockBoundsCache, Drawing, Space, entity_bounds, entity_bounds_cached};
use cadcraft_geom::{Bounds2, Vec2};
use serde_json::{Value, json};
@@ -311,6 +311,21 @@ fn run_view_set(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// Bounds of the currently visible entities in `space`, excluding entities and block contents
/// on layers that are turned off or frozen.
fn visible_extents(doc: &Drawing, space: &Space) -> Bounds2 {
let mut b = Bounds2::EMPTY;
let mut cache = BlockBoundsCache::default();
if let Some(store) = doc.space(space) {
for e in store.iter() {
if doc.is_visible(e) {
b = b.union(&entity_bounds_cached(doc, e, 0, &mut cache));
}
}
}
b
}
fn run_layout_set(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").unwrap_or("Model");
let space = if name.eq_ignore_ascii_case("model") {
@@ -320,6 +335,7 @@ fn run_layout_set(s: &mut Session, p: &Value) -> Result<Value> {
Space::Paper(l.name.clone())
};
s.pending_window = None;
let (vw, vh) = s.viewport_px;
let st = s.state_mut()?;
st.space = space.clone();
st.mspace = None;
@@ -327,11 +343,22 @@ fn run_layout_set(s: &mut Session, p: &Value) -> Result<Value> {
if let Space::Paper(n) = &space
&& !st.views.iter().any(|(sp, _)| sp == &space)
{
// Default paper view: the sheet.
let page = st.doc.layout(n).map(|l| l.page.clone()).unwrap_or_default();
let (w, h) = if page.landscape { (page.height_mm, page.width_mm) } else { (page.width_mm, page.height_mm) };
let unit = if st.doc.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 1.0 / 25.4 };
st.set_view_quiet(View { center: Vec2::new(w * unit / 2.0, h * unit / 2.0), height: h * unit * 1.15, twist: 0.0 });
// Why: fit only visible content on the automatic initial switch so far-away geometry on
// turned-off layers does not push the visible title block out of sight; explicit
// ZOOM Extents continues to use `Drawing::extents` (which includes turned-off layers).
let ext = visible_extents(&st.doc, &space);
if !ext.is_empty() && ext.width().is_finite() && ext.height().is_finite() {
let aspect = st.zoom_aspect(vw / vh.max(1.0));
let (center, bw, bh) = View::twisted_box(ext, 0.0);
let height = bh.max(bw / aspect.max(1e-6)).max(1e-6) * 1.15;
st.set_view_quiet(View { center, height, twist: 0.0 });
} else {
// Default paper view: the sheet.
let page = st.doc.layout(n).map(|l| l.page.clone()).unwrap_or_default();
let (w, h) = if page.landscape { (page.height_mm, page.width_mm) } else { (page.width_mm, page.height_mm) };
let unit = if st.doc.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 1.0 / 25.4 };
st.set_view_quiet(View { center: Vec2::new(w * unit / 2.0, h * unit / 2.0), height: h * unit * 1.15, twist: 0.0 });
}
}
s.touch();
ok()
+7 -5
View File
@@ -7,6 +7,7 @@
/// Commands that read or write files, each path held to the roots where the file is touched.
pub const FILES: &[&str] = &[
"-hatch",
"-linetype",
"-plottermanager",
"-wblock",
@@ -49,6 +50,8 @@ pub const FILES: &[&str] = &[
"publish",
"qsave",
"recover",
"refclose",
"refedit",
"reinit",
"saveas",
"script",
@@ -265,9 +268,8 @@ pub const NO_FILES: &[&str] = &[
"attdisp.normal",
"attdisp.on",
"attdisp.off",
"refedit",
"refedit.levels",
"refset",
"refclose",
"bedit",
"bsave",
"bsaveas",
@@ -521,9 +523,9 @@ mod tests {
use std::collections::BTreeSet;
/// Words in a command's parameter doc that usually name a file. In these commands they don't:
/// `array` and `arraypath` follow a path of objects, and `blocks.reference.grips` reports a
/// direction.
const NOT_FILES: &[&str] = &["array", "arraypath", "blocks.reference.grips"];
/// `array` and `arraypath` follow a path of objects, `refedit.levels` reports paths of nested
/// references, and `blocks.reference.grips` reports a direction.
const NOT_FILES: &[&str] = &["array", "arraypath", "refedit.levels", "blocks.reference.grips"];
/// The words of a command's documentation, lower case.
fn words(doc: &str) -> BTreeSet<String> {
+8 -1
View File
@@ -136,7 +136,14 @@ pub fn stretch_grip(kind: &EntityKind, index: usize, to: Vec2) -> Option<EntityK
EntityKind::Polyline3d(p) => set_xy(p.points.get_mut(index)?, to),
EntityKind::Spline(sp) => {
if sp.fit.is_empty() {
*sp.control.get_mut(index)? = to;
// A closed spline's repeats of the control vertex move with it (#3566).
let copies = sp.control_copies(index);
if copies.is_empty() {
return None;
}
for i in copies {
*sp.control.get_mut(i)? = to;
}
} else {
let mut fit = sp.fit.clone();
*fit.get_mut(index)? = to;
+29
View File
@@ -249,3 +249,32 @@ fn grips_on_locked_layers_and_hostile_values() {
}
}
}
/// #3566: a closed spline keeps some control vertices twice: SPLINE CV's Close repeats the first
/// at the end, and control vertices that wrap round repeat the first `degree`. Each control
/// vertex has one grip, and dragging it moves its copies, so the spline stays closed.
#[test]
fn a_closed_spline_has_one_grip_per_control_vertex_and_stays_closed() {
let mut s = Session::new();
let square = [v(0.0, 0.0), v(10.0, 0.0), v(10.0, 10.0), v(0.0, 10.0)];
let clamped = h(&s.execute("spline.cv", &json!({"control": [[0, 0], [10, 0], [10, 10], [0, 10]], "closed": true})).unwrap());
let wraps = cadcraft_geom::Spline {
degree: 3,
knots: (0..11).map(f64::from).collect(),
control: square.iter().chain(&square[..3]).copied().collect(),
closed: true,
..Default::default()
};
assert!(wraps.wraps());
let wrapped = s.add_entity(EntityKind::Spline(wraps)).unwrap();
for sp in [clamped, wrapped] {
let g = s.grips_of(sp).unwrap();
let coincide = g.iter().enumerate().any(|(i, a)| g.iter().skip(i + 1).any(|b| a.near(*b, 1e-9)));
assert!(!coincide, "no grip lies on another: {g:?}");
s.grip_edit(sp, 0, v(-3.0, -3.0), GripMode::Stretch).unwrap();
let EntityKind::Spline(x) = kind(&s, sp) else { panic!() };
assert!(!x.control.iter().any(|c| near(*c, 0.0, 0.0)), "every copy moved: {:?}", x.control);
let (lo, hi) = x.domain();
assert!(x.eval(lo).near(x.eval(hi), 1e-9), "still closed: {:?} {:?}", x.eval(lo), x.eval(hi));
}
}
+7 -2
View File
@@ -3,12 +3,15 @@ use super::cmd;
/// Options and values the interactive commands remember for the rest of the session, offered as
/// the `<default>` the next time they ask (as AutoCAD does). Values AutoCAD keeps in a drawing
/// system variable (HPNAME, OFFSETDIST, FILLETRAD, CHAMFERA, POLYSIDES…) live in the drawing
/// header instead. JSON calls never read these: their explicit parameters and documented defaults
/// stay authoritative.
/// header instead. Drawing commands called with JSON use their own parameter defaults.
#[derive(Clone, Debug, PartialEq)]
pub struct LastUsed {
/// HATCH/GRADIENT starts at "Select objects" instead of "Pick internal point".
pub hatch_select: bool,
/// HPSPACE: line spacing for user-defined hatches.
pub hatch_spacing: f64,
/// HPDOUBLE: whether user-defined hatches have a second family of lines.
pub hatch_double: bool,
/// POLYGON: circumscribed about the circle (the `C` option) instead of inscribed.
pub polygon_circumscribed: bool,
/// ROTATE angle (radians).
@@ -35,6 +38,8 @@ impl Default for LastUsed {
fn default() -> Self {
LastUsed {
hatch_select: false,
hatch_spacing: 1.0,
hatch_double: false,
polygon_circumscribed: false,
rotate_angle: 0.0,
scale_factor: 1.0,
+28
View File
@@ -56,6 +56,7 @@ pub use cadcraft_fonts as fonts;
pub use cadcraft_geom as geom;
pub use cadcraft_render as render;
pub use cmd::blocks::WblockPicks;
pub use cmd::blocks::attedit::{AttributeRow, attributes};
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices};
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use prompt::{Accept, AttribAsk, AttribEntry, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
@@ -126,8 +127,15 @@ pub struct Session {
/// 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>,
/// The command history. It is trimmed from the front when it grows long, so to find the lines
/// echoed since some moment keep a [`Session::log_mark`], not an index into it.
pub log: Vec<String>,
/// Lines [`Session::echo`] has added to `log`, trimmed and cleared ones included.
echoed: u64,
pub last_command: Option<String>,
/// Last TSV payload and optional text height passed to [`Session::start_paste_table`], so
/// pressing Enter to repeat `pastetable` restarts interactive placement.
pub(crate) last_paste_table: Option<(String, Option<f64>)>,
/// LASTPOINT.
pub last_point: Vec2,
/// AREA and PERIMETER: the last area AREA or MEASUREGEOM measured (in their Add and Subtract
@@ -155,6 +163,9 @@ pub struct Session {
/// change behavior on Ctrl — currently only ARC's "hold Ctrl to switch direction" — read
/// this instead of receiving modifiers through `Input`, which stays free of UI state.
pub ctrl_down: bool,
/// Whether Shift is held right now (from the UI, overwritten every frame). TRIM/EXTEND read
/// this to temporarily toggle the active mode, as in AutoCAD.
pub shift_down: bool,
/// Origin of the point currently being fed by `input_snapped`; never reused by typed points.
picked_viewport: Option<snap::ViewportPoint>,
/// The last drawing comparison (COMPARE), drawn over the drawing it was made for.
@@ -226,7 +237,9 @@ impl Session {
program_input: false,
suspended: None,
log: Vec::new(),
echoed: 0,
last_command: None,
last_paste_table: None,
last_point: Vec2::ZERO,
area: 0.0,
perimeter: 0.0,
@@ -237,6 +250,7 @@ impl Session {
cursor: Vec2::ZERO,
cursor_deferred: None,
ctrl_down: false,
shift_down: false,
picked_viewport: None,
compare: None,
tracking: snap::tracking::Tracker::default(),
@@ -322,11 +336,25 @@ impl Session {
let m = msg.into();
log::debug!("{m}");
self.log.push(m);
self.echoed = self.echoed.saturating_add(1);
if self.log.len() > 5000 {
self.log.drain(..1000);
}
}
/// A mark in the command history: the number of lines echoed so far. Unlike an index into
/// `log`, it stays valid when the history is trimmed from the front or cleared.
pub fn log_mark(&self) -> u64 {
self.echoed
}
/// The lines echoed since `mark` ([`Session::log_mark`]) that the history still holds: all of
/// them, or the last ones when the history was trimmed past the first.
pub fn log_since(&self, mark: u64) -> &[String] {
let new = usize::try_from(self.echoed.saturating_sub(mark)).unwrap_or(usize::MAX);
self.log.get(self.log.len().saturating_sub(new)..).unwrap_or_default()
}
/// Common properties for new objects (CLAYER, CECOLOR, CELTYPE, CELWEIGHT, CELTSCALE).
pub fn current_common(&self) -> Common {
let Ok(d) = self.doc() else { return Common::default() };
+41 -3
View File
@@ -75,6 +75,10 @@ pub struct Env {
/// The command history's length after LISP last printed a line: when something else wrote since
/// (a prompt, a command's echo), a leading newline only ends that line.
pub printed_at: Option<usize>,
/// Application names `regapp` registered (upper case). A drawing's APPID table is written
/// from the xdata its objects carry, so this only makes `regapp` answer like AutoCAD's and
/// shows the names in the APPID table `tblsearch` lists.
pub regapps: std::collections::BTreeSet<String>,
}
impl Default for Env {
@@ -93,6 +97,7 @@ impl Default for Env {
pending_block: None,
objects: objects::Names::default(),
printed_at: None,
regapps: std::collections::BTreeSet::new(),
};
builtins::install(&mut e);
e
@@ -170,12 +175,14 @@ pub(crate) struct Limits {
pub string_bytes: u64,
/// Maximum interpreter steps per synchronous callback.
pub callback_steps: u64,
/// Steps a routine run on without frames ([`Session::lisp_run_until_input`]) may take in all.
pub frameless_steps: u64,
}
impl Default for Limits {
/// Provide finite cons-cell, string-byte, and synchronous-callback limits for a LISP run.
/// Provide finite cons-cell, string-byte, synchronous-callback and step limits for a LISP run.
fn default() -> Self {
Limits { cells: value::MAX_CELLS, string_bytes: value::STRING_BUDGET, callback_steps: 500_000_000 }
Limits { cells: value::MAX_CELLS, string_bytes: value::STRING_BUDGET, callback_steps: 500_000_000, frameless_steps: BLOCKING_CAP }
}
}
@@ -204,7 +211,7 @@ struct Run {
/// An expression typed at a command's prompt ([`Session::lisp_eval_answer`]): blocking, with
/// [`ANSWER_CAP`] steps instead of [`BLOCKING_CAP`].
answer: bool,
/// Steps taken, for the cap on blocking runs.
/// Steps taken, for the caps on blocking runs and on routines run on without frames.
steps: u64,
/// The `*error*` handler is the one running.
handler: bool,
@@ -363,6 +370,28 @@ impl Session {
self.lisp.run.as_ref().is_some_and(|r| matches!(r.waiting, Some(Need::Yield)))
}
/// Carry on a routine that gave the interface a frame ([`Session::lisp_busy`]) until it ends or
/// waits for input, where nothing else would: a script calls this before each input it gives,
/// which belongs to what the routine waits for or comes after it, and once it ends; a host
/// with no window calls it after each line it types. No one can stop the routine by hand
/// meanwhile, so past `limits.frameless_steps` steps, as many as a programmatic call may take,
/// it stops with the error such a call gets.
pub fn lisp_run_until_input(&mut self) {
while self.lisp_busy() {
let cap = self.lisp.limits.frameless_steps;
if self.lisp.run.as_ref().is_some_and(|r| r.steps > cap) {
// `*error*` gets the message and runs on the same count: an endless one stops at
// the next pass.
self.lisp_error(LispError::quit(format!("routine stopped after {cap} steps")));
continue;
}
if let Some(r) = self.lisp.run.as_mut() {
r.waiting = None;
}
self.lisp_drive();
}
}
/// Run the machine until it finishes or waits.
fn lisp_drive(&mut self) {
loop {
@@ -720,6 +749,15 @@ impl Session {
Some(label)
}
/// Why U may not take back the running routine's last step: it would undo a REFCLOSE Save
/// that already wrote an xref's file ([`crate::cmd::blocks::refedit::undo_barrier`]).
pub(crate) fn lisp_undo_barrier(&self) -> Option<String> {
let uid = self.routine_steps()?;
let st = self.docs.iter().find(|d| d.uid == uid)?;
let snap = self.lisp.steps.undo.back()?;
crate::cmd::blocks::refedit::undo_barrier(&st.doc, &snap.doc)
}
/// U or REDO inside the running routine went on to the drawing's steps before it: the
/// routine's own undo step starts from the drawing as that left it, and REDO brings back that
/// step before what U took back of the routine's.
+1
View File
@@ -252,6 +252,7 @@ static BUILTINS: &[Builtin] = &[
ctx!("ENTNEXT", drawing::entnext),
ctx!("ENTUPD", drawing::entupd),
ctx!("HANDENT", drawing::handent),
ctx!("REGAPP", drawing::regapp),
ctx!("SSGET", drawing::ssget),
ctx!("SSADD", drawing::ssadd),
ctx!("SSDEL", drawing::ssdel),
+209 -11
View File
@@ -6,13 +6,16 @@
//!
//! Entity lists use the DXF groups the file reader and writer use (through
//! [`crate::cmd::file::entity_codec`]), so what `entget` shows is what a DXF file holds, except
//! for angles, which are radians in a list and degrees in a file.
//! for angles, which are radians in a list and degrees in a file. Extended data (xdata) is the
//! `-3` group, as in AutoCAD: `(entget ename '("APP" …))` adds `(-3 ("APP" (1000 . "…") …))` for
//! the applications named (wildcards allowed), `entmake` and `entmod` take it, and `regapp`
//! registers an application name.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use cadcraft_doc::{Entity, Handle, Space};
use cadcraft_doc::{Entity, Handle, RawTag, Space};
use cadcraft_geom::Vec2;
use craft_dxf::Tag;
@@ -340,7 +343,7 @@ fn list_to_groups(list: &Value) -> Result<(String, Vec<Tag>), LispError> {
other => return Err(LispError::bad_arg("stringp", other)),
})
}
-1 | 5 | 330 | 360 | 410 | 102 => {}
-1 | -3 | 5 | 330 | 360 | 410 | 102 => {}
_ if point_group(code) && matches!(v, Value::Cons(_)) => {
let p = v.as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", &v))?;
tags.push(Tag::f(code, p[0]));
@@ -374,6 +377,12 @@ fn space_of(d: &cadcraft_doc::Drawing, h: Handle) -> Option<Space> {
pub fn entget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 1, 2)?;
let h = ename(&a[0])?;
// The applications whose xdata to list: names or wildcard patterns ("*": every application).
let apps: Option<Vec<String>> = match a.get(1) {
None | Some(Value::Nil) => None,
Some(v) if v.is_list() => Some(v.iter().map(|x| string(&x)).collect::<Result<_, _>>()?),
Some(other) => return Err(LispError::bad_arg("listp", other)),
};
let drawn = ctx.s.doc().is_ok_and(|d| d.entity(h).is_some());
let from_block = if drawn { None } else { block_entity(ctx, h) };
let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) };
@@ -385,6 +394,7 @@ pub fn entget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
(None, None) => return Ok(Flow::Value(super::objects::entget(ctx, h))),
};
let (kind, mut tags) = (codec()?.groups)(d, e);
let xdata = apps.map(|apps| xdata_to_list(&e.common.xdata, &apps)).filter(|v| !v.is_nil());
convert_angles(&kind, &mut tags, f64::to_radians);
let layout = match space_of(d, h) {
Some(Space::Paper(name)) => name,
@@ -401,12 +411,157 @@ pub fn entget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
placed_layout = true;
}
}
if let Some(x) = xdata {
items.push(Value::cons(Value::Int(-3), x));
}
Ok(Flow::Value(Value::list(items)))
}
/// The entity a list describes, as the reader makes it; a missing layer (8) is the current one.
fn entity_from_list(ctx: &Ctx<'_>, list: &Value) -> Result<(String, cadcraft_doc::Common, cadcraft_doc::EntityKind), LispError> {
/// A group kept raw, typed by its code (so a 1070 lists as an integer, a 1040 as a real, and a
/// 1071 as a real per AutoLISP's `entget`, though the file holds a 32-bit integer).
fn typed_tag(r: &RawTag) -> Tag {
use craft_dxf::{Kind, Value as V, kind_of};
let v = r.value.trim();
let value = if r.code == 1071 {
v.parse::<i64>().ok().map(|n| V::Real(n as f64))
} else {
match kind_of(r.code) {
Kind::Real => v.parse::<f64>().ok().filter(|x| x.is_finite()).map(V::Real),
Kind::Int16 | Kind::Int32 | Kind::Int64 => v.parse::<i64>().ok().map(V::Int),
Kind::Bool => v.parse::<i64>().ok().map(|x| V::Bool(x != 0)),
Kind::Hex => Some(V::Hex(v.to_string())),
Kind::Str => None,
}
};
Tag::new(r.code, value.unwrap_or_else(|| V::Str(r.value.clone())))
}
/// The `-3` group's value: `(("APP" (1000 . "…") (1070 . 3) (1010 x y z) …) …)` for the
/// applications of `xdata` matching one of `patterns` (any case; `wcmatch` wildcards).
fn xdata_to_list(xdata: &[RawTag], patterns: &[String]) -> Value {
let patterns: Vec<String> = patterns.iter().map(|p| p.trim().to_ascii_uppercase()).collect();
// A file may hold several runs of one application, `ACME` and `acme` among them; they are
// one application to `set_xdata_app`, so they are one list here (first spelling, all the
// groups), or `(entmod (entget e '("*")))` would keep only the last run.
let mut apps: Vec<(&str, Vec<RawTag>)> = Vec::new();
for (name, groups) in cadcraft_doc::xdata_apps(xdata) {
let up = name.to_ascii_uppercase();
if !patterns.iter().any(|p| super::builtins::wild_match(&up, p)) {
continue;
}
match apps.iter_mut().find(|(app, _)| app.eq_ignore_ascii_case(name)) {
Some((_, all)) => all.extend_from_slice(groups),
None => apps.push((name, groups.to_vec())),
}
}
let lists: Vec<Value> = apps
.into_iter()
.map(|(name, groups)| {
let tags: Vec<Tag> = groups.iter().map(typed_tag).collect();
Value::list_with_tail(vec![Value::str(name)], Value::list(groups_to_list(&tags)))
})
.collect();
Value::list(lists)
}
/// The applications of a list's `-3` group, each with its groups (checked as xdata): `None`
/// when the list has no `-3`. An application with no groups removes its data in `entmod`.
fn xdata_from_list(list: &Value) -> Result<Option<Vec<(String, Vec<RawTag>)>>, LispError> {
let Some(x) = list.iter().find(|v| v.car().as_number() == Some(-3.0)).map(|v| v.cdr()) else { return Ok(None) };
// `(-3 . 7)` is not a list of applications: refused, not read as "no applications".
if !x.is_list() {
return Err(LispError::bad_arg("listp", &x));
}
let bad = |what: &str| LispError::new(format!("bad DXF group: {what}"));
let mut out = Vec::new();
for app in x.iter() {
let name = match app.car() {
Value::Str(s) => s.to_string(),
other => return Err(LispError::bad_arg("stringp", &other)),
};
cadcraft_doc::check_xdata_app_name(&name).map_err(|e| bad(&e.to_string()))?;
if cadcraft_doc::is_reserved_xdata_app(&name) {
return Err(bad(&format!("xdata application {name} is reserved")));
}
// The application's groups must be a proper list too: `("ACME" . 7)` would otherwise
// read as "no groups" and remove the data in `entmod`, and a dotted tail after real
// groups would be dropped.
let tail = app.cdr();
if !tail.is_list() {
return Err(LispError::bad_arg("listp", &tail));
}
let mut groups: Vec<RawTag> = Vec::new();
for g in tail.iter() {
if groups.len() >= cadcraft_doc::MAX_XDATA_GROUPS {
return Err(bad("too many xdata groups"));
}
let Value::Cons(c) = &g else { return Err(LispError::bad_arg("consp", &g)) };
let Value::Int(code) = c.car else { return Err(LispError::bad_arg("fixnump", &c.car)) };
match &c.cdr {
Value::Cons(_) if (1010..=1013).contains(&code) => {
let p = c.cdr.as_point().ok_or_else(|| LispError::bad_arg("3D point", &c.cdr))?;
if p.iter().any(|v| !v.is_finite()) {
return Err(bad("xdata point must be finite"));
}
groups.push(RawTag { code, value: craft_dxf::format_real(p[0]) });
groups.push(RawTag { code: code + 10, value: craft_dxf::format_real(p[1]) });
groups.push(RawTag { code: code + 20, value: craft_dxf::format_real(p[2]) });
}
Value::Int(i) => groups.push(RawTag { code, value: i.to_string() }),
Value::Real(r) if code == 1071 => {
if r.is_finite() && r.fract() == 0.0 && *r >= f64::from(i32::MIN) && *r <= f64::from(i32::MAX) {
groups.push(RawTag { code, value: (*r as i32).to_string() });
} else {
return Err(bad("group 1071 must be a 32-bit integer"));
}
}
Value::Real(r) => groups.push(RawTag { code, value: craft_dxf::format_real(*r) }),
Value::Str(s) => groups.push(RawTag { code, value: s.to_string() }),
Value::Ename(h) => groups.push(RawTag { code, value: h.hex() }),
other => return Err(LispError::bad_arg("DXF group value", other)),
}
}
cadcraft_doc::check_xdata_groups(&groups).map_err(|e| bad(&e.to_string()))?;
out.push((name, groups));
}
Ok(Some(out))
}
/// `(regapp "name")`: register an application for xdata. The name when it is new, nil when it
/// is already registered (by `regapp` or by xdata an object carries) or invalid. Saving writes
/// an APPID record for every application with xdata, so nothing else is needed.
pub fn regapp(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 1, 1)?;
let name = string(&a[0])?;
if cadcraft_doc::check_xdata_app_name(&name).is_err() {
return Ok(Flow::Value(Value::Nil));
}
let up = name.trim().to_ascii_uppercase();
let known = ctx.env.regapps.contains(&up) || ctx.s.doc().is_ok_and(|d| xdata_app_names(d).contains(&up));
if known {
return Ok(Flow::Value(Value::Nil));
}
ctx.env.regapps.insert(up);
Ok(Flow::Value(Value::str(name.trim())))
}
/// The upper-case names of every application registered in the drawing or carrying xdata on an object.
fn xdata_app_names(d: &cadcraft_doc::Drawing) -> std::collections::BTreeSet<String> {
std::iter::once(&d.model)
.chain(d.layouts.iter().map(|l| &l.entities))
.chain(d.blocks.values().map(|b| &b.entities))
.flat_map(|s| s.iter())
.flat_map(|e| cadcraft_doc::xdata_apps(&e.common.xdata).into_iter().map(|(n, _)| n.to_ascii_uppercase()).collect::<Vec<_>>())
.chain(d.foreign.appids.iter().map(|n| n.to_ascii_uppercase()))
.collect()
}
/// The entity a list describes, as the reader makes it, with the applications of its `-3`
/// group (their xdata is on the entity); a missing layer (8) is the current one.
type ListedEntity = (String, cadcraft_doc::Common, cadcraft_doc::EntityKind, Option<Vec<(String, Vec<RawTag>)>>);
fn entity_from_list(ctx: &Ctx<'_>, list: &Value) -> Result<ListedEntity, LispError> {
let (kind, mut tags) = list_to_groups(list)?;
let xdata = xdata_from_list(list)?;
convert_angles(&kind, &mut tags, f64::to_degrees);
if !tags.iter().any(|t| t.code == 8) {
let layer = crate::sysvars::get(ctx.s, "CLAYER").and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "0".into());
@@ -415,7 +570,23 @@ fn entity_from_list(ctx: &Ctx<'_>, list: &Value) -> Result<(String, cadcraft_doc
match (codec()?.entity)(&kind, &tags) {
// A type the reader only carries through (an unknown or invalid name) isn't made.
Some((_, cadcraft_doc::EntityKind::Unknown(_))) | None => Err(LispError::new(format!("bad DXF group: {kind} can't be made from this list"))),
Some((common, k)) => Ok((kind, common, k)),
Some((mut common, k)) => {
if let Some(apps) = &xdata {
for (app, groups) in apps {
// `ACAD` on a dimension holds its overrides (DSTYLE), written from the model.
if cadcraft_doc::is_model_xdata_app(app, &k) {
return Err(LispError::new(format!("bad DXF group: xdata application {app} of a {kind} is written from its own properties")));
}
cadcraft_doc::set_xdata_app(&mut common.xdata, app, Some(groups));
}
// Each application's groups are checked one by one above; together they must
// still fit what a file holds for one object.
if common.xdata.len() > cadcraft_doc::MAX_XDATA_GROUPS {
return Err(LispError::new("bad DXF group: too many xdata groups"));
}
}
Ok((kind, common, k, xdata))
}
}
}
@@ -428,7 +599,7 @@ pub fn entmake(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
Ok((k, _)) if k == "ENDBLK" => return Ok(Flow::Value(end_block(ctx))),
_ => {}
}
let (_, common, kind) = match entity_from_list(ctx, list) {
let (_, common, kind, _) = match entity_from_list(ctx, list) {
Ok(x) => x,
Err(_) => return Ok(Flow::Value(Value::Nil)),
};
@@ -531,7 +702,7 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
return Err(LispError::bad_arg("lentityp", &Value::Nil));
};
let Some(old) = ctx.s.doc().ok().and_then(|d| d.entity(h)).cloned() else { return Ok(Flow::Value(Value::Nil)) };
let (kind_name, common, mut kind) = match entity_from_list(ctx, list) {
let (kind_name, mut common, mut kind, xdata) = match entity_from_list(ctx, list) {
Ok(x) => x,
Err(_) => return Ok(Flow::Value(Value::Nil)),
};
@@ -539,6 +710,17 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
if !kind_name.eq_ignore_ascii_case(old.kind.dxf_name()) {
return Ok(Flow::Value(Value::Nil));
}
// Xdata stays unless the list has a -3 group, which replaces the data of the applications it
// names (one with no groups removes it) and leaves the others alone, as in AutoCAD.
common.xdata = old.common.xdata.clone();
if let Some(apps) = &xdata {
for (app, groups) in apps {
cadcraft_doc::set_xdata_app(&mut common.xdata, app, Some(groups));
}
if common.xdata.len() > cadcraft_doc::MAX_XDATA_GROUPS {
return Ok(Flow::Value(Value::Nil));
}
}
// A block reference's attributes are entities of their own in AutoCAD, which entmod of the
// INSERT leaves alone; its list doesn't hold them, so they are kept from the reference.
if let (cadcraft_doc::EntityKind::Insert(new), cadcraft_doc::EntityKind::Insert(was)) = (&mut kind, &old.kind)
@@ -1116,11 +1298,27 @@ fn table_records(d: &cadcraft_doc::Drawing, table: &str) -> Vec<Value> {
.iter()
.map(|s| Value::list(vec![pair(0, Value::str("DIMSTYLE")), pair(2, Value::str(&s.name)), pair(70, Value::Int(0))]))
.collect(),
"APPID" => vec![Value::list(vec![pair(0, Value::str("APPID")), pair(2, Value::str("ACAD")), pair(70, Value::Int(0))])],
"APPID" => std::iter::once("ACAD".to_string())
.chain(xdata_app_names(d).into_iter().filter(|n| n != "ACAD"))
.map(|n| Value::list(vec![pair(0, Value::str("APPID")), pair(2, Value::str(&n)), pair(70, Value::Int(0))]))
.collect(),
_ => Vec::new(),
}
}
/// [`table_records`] plus, for APPID, the applications `regapp` registered in this session.
fn table_records_with(ctx: &Ctx<'_>, d: &cadcraft_doc::Drawing, table: &str) -> Vec<Value> {
let mut records = table_records(d, table);
if table == "APPID" {
let have: Vec<String> = records.iter().map(record_name).map(|n| n.to_ascii_uppercase()).collect();
for app in ctx.env.regapps.iter().filter(|a| !have.contains(a)) {
let pair = |c: i32, v: Value| Value::cons(Value::Int(c), v);
records.push(Value::list(vec![pair(0, Value::str("APPID")), pair(2, Value::str(app)), pair(70, Value::Int(0))]));
}
}
records
}
fn record_name(r: &Value) -> String {
r.iter().find(|p| p.car().as_number() == Some(2.0)).map(|p| to_text(&p.cdr(), false)).unwrap_or_default()
}
@@ -1130,7 +1328,7 @@ pub fn tblsearch(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
let table = string(&a[0])?.to_ascii_uppercase();
let name = string(&a[1])?;
let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) };
let records = table_records(d, &table);
let records = table_records_with(ctx, d, &table);
let found = records.iter().position(|r| record_name(r).eq_ignore_ascii_case(&name));
if let Some(i) = found
&& a.get(2).is_some_and(|v| !v.is_nil())
@@ -1145,7 +1343,7 @@ pub fn tblnext(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
let table = string(&a[0])?.to_ascii_uppercase();
let rewind = a.get(1).is_some_and(|v| !v.is_nil());
let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) };
let records = table_records(d, &table);
let records = table_records_with(ctx, d, &table);
let i = if rewind { 0 } else { ctx.env.tblnext.get(&table).copied().unwrap_or(0) };
ctx.env.tblnext.insert(table, i + 1);
Ok(Flow::Value(records.get(i).cloned().unwrap_or_default()))
+238
View File
@@ -666,6 +666,154 @@ fn handseed_follows_new_objects() {
assert_eq!(ok(&mut s, "(cdr (assoc 5 (entget (entlast))))"), format!("\"{:X}\"", held + 1));
}
#[test]
fn entity_lists_carry_xdata_in_group_minus_3() {
let mut s = session();
// entmake with a -3 group puts the xdata on the new entity; entget shows it only when asked.
let made = ok(
&mut s,
"(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0) (-3 (\"ACME\" (1000 . \"D-07\") (1070 . 3) (1040 . 2.5) (1010 1.0 2.0 0.0) (1005 . \"2A\") (1071 . 100000)) (\"PE_URL\" (1000 . \"https://example.com\")))))",
);
assert!(made.contains("LINE"));
assert_eq!(ok(&mut s, "(assoc -3 (entget (entlast)))"), "nil");
assert_eq!(
ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"acme\"))))"),
"((\"ACME\" (1000 . \"D-07\") (1070 . 3) (1040 . 2.5) (1010 1.0 2.0 0.0) (1005 . \"2A\") (1071 . 100000.0)))"
);
// Group 1070 is INT, whereas group 1071 is REAL in AutoLISP's entget while remaining a 32-bit
// integer in the drawing/API and when written back with entmod.
assert_eq!(
ok(
&mut s,
"(setq g (cdr (car (cdr (assoc -3 (entget (entlast) '(\"ACME\"))))))) (list (type (cdr (assoc 1070 g))) (type (cdr (assoc 1071 g))))"
),
"(INT REAL)"
);
assert!(ok(&mut s, "(entmod (entget (entlast) '(\"ACME\")))").contains("LINE"));
assert_eq!(ok(&mut s, "(length (cdr (assoc -3 (entget (entlast) '(\"*\")))))"), "2");
assert_eq!(ok(&mut s, "(length (cdr (assoc -3 (entget (entlast) '(\"PE_*\" \"nope\")))))"), "1");
assert_eq!(ok(&mut s, "(assoc -3 (entget (entlast) '(\"nope\")))"), "nil");
// The xdata is what the drawing holds (the API sees 1070 and 1071 as integers too).
let x = s.execute("entities", &serde_json::json!({"xdata": "ACME"})).unwrap();
assert_eq!(x["entities"][0]["xdata"]["ACME"][1], serde_json::json!([1070, 3]));
assert_eq!(x["entities"][0]["xdata"]["ACME"][5], serde_json::json!([1071, 100000]));
// entmod without -3 keeps the xdata; with -3 it replaces the named applications' data and
// removes one listed without groups; the others stay.
ok(&mut s, "(setq d (entget (entlast))) (entmod (subst (cons 8 \"WALLS\") (assoc 8 d) d))");
assert_eq!(ok(&mut s, "(length (cdr (assoc -3 (entget (entlast) '(\"*\")))))"), "2");
ok(&mut s, "(entmod (append (entget (entlast)) (list (list -3 (list \"ACME\" (cons 1070 9))))))");
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"ACME\"))))"), "((\"ACME\" (1070 . 9)))");
assert_eq!(ok(&mut s, "(length (cdr (assoc -3 (entget (entlast) '(\"*\")))))"), "2");
ok(&mut s, "(entmod (append (entget (entlast)) '((-3 (\"PE_URL\")))))");
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), "((\"ACME\" (1070 . 9)))");
// Bad xdata is refused as a bad list (nil), and nothing changes.
for bad in [
"(-3 (\"ACME\" (1002 . \"{\")))",
"(-3 (\"ACME\" (8 . \"0\")))",
"(-3 (\"ACME\" (1070 . 70000)))",
"(-3 (\"ACME\" (1071 . 1.5)))",
"(-3 (\"ACME\" (1071 . 2147483648.0)))",
"(-3 (\"ACME\" (1071 . -2147483649.0)))",
"(-3 (\"ACME\" (1010 1.0)))",
"(-3 (\"CADCRAFT\" (1000 . \"x\")))",
"(-3 (\"\" (1000 . \"x\")))",
"(-3 (7 (1000 . \"x\")))",
"(-3 (\"ACME\" 5))",
] {
assert_eq!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '({bad})))")), "nil", "{bad}");
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), "((\"ACME\" (1070 . 9)))", "{bad}");
}
assert!(eval(&mut s, "(entget (entlast) \"ACME\")").is_err(), "the second argument is a list");
// regapp: the name when new, nil once registered (by regapp or by xdata an object carries);
// the APPID table lists both.
assert_eq!(ok(&mut s, "(regapp \"ACME\")"), "nil");
assert_eq!(ok(&mut s, "(regapp \"MYAPP\")"), "\"MYAPP\"");
assert_eq!(ok(&mut s, "(regapp \"myapp\")"), "nil");
assert_eq!(ok(&mut s, "(regapp \"bad*name\")"), "nil");
assert_eq!(ok(&mut s, "(cdr (assoc 2 (tblsearch \"APPID\" \"acme\")))"), "\"ACME\"");
assert_eq!(ok(&mut s, "(cdr (assoc 2 (tblsearch \"APPID\" \"MYAPP\")))"), "\"MYAPP\"");
assert_eq!(ok(&mut s, "(tblsearch \"APPID\" \"PE_URL\")"), "nil");
}
#[test]
fn group_1071_boundary_reals_round_trip_as_32bit_integers() {
let mut s = session();
let made =
ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0) (-3 (\"LIMITS\" (1071 . 2147483647.0) (1071 . -2147483648.0) (1071 . -0.0)))))");
assert!(made.contains("LINE"));
assert_eq!(ok(&mut s, "(type (cdr (assoc 1071 (cdr (car (cdr (assoc -3 (entget (entlast) '(\"LIMITS\")))))))))"), "REAL");
assert!(ok(&mut s, "(entmod (entget (entlast) '(\"LIMITS\")))").contains("LINE"));
let lim = s.execute("entities", &serde_json::json!({"xdata": "LIMITS"})).unwrap();
assert_eq!(lim["entities"][0]["xdata"]["LIMITS"], serde_json::json!([[1071, 2147483647], [1071, -2147483648], [1071, 0]]));
}
#[test]
fn entmake_refuses_xdata_over_the_object_limit_across_applications() {
// Each application's groups fit the per-application cap; together they exceed what an object
// may hold, so the list is refused (nil) and nothing is made.
let mut s = session();
ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0)))");
let last = ok(&mut s, "(entlast)");
let groups = "(1000 . \"x\") ".repeat(cadcraft_doc::MAX_XDATA_GROUPS / 2 + 8);
let code = format!("(entmake '((0 . \"LINE\") (10 0 0 0) (11 9 0 0) (-3 (\"A1\" {groups}) (\"A2\" {groups}))))");
assert_eq!(ok(&mut s, &code), "nil");
assert_eq!(ok(&mut s, "(entlast)"), last, "nothing was made");
// Half of that on one application is within the limit and is made.
let code = format!("(entmake '((0 . \"LINE\") (10 0 0 0) (11 9 0 0) (-3 (\"A1\" {groups}))))");
assert!(ok(&mut s, &code).contains("LINE"));
assert_ne!(ok(&mut s, "(entlast)"), last);
}
#[test]
fn a_dotted_minus_3_group_is_refused() {
// `(-3 . 7)` names no applications; it is a bad list (nil), not an empty one.
let mut s = session();
ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0) (-3 (\"ACME\" (1070 . 9)))))");
let last = ok(&mut s, "(entlast)");
assert_eq!(ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 9 0 0) (-3 . 7)))"), "nil");
assert_eq!(ok(&mut s, "(entlast)"), last, "nothing was made");
assert_eq!(ok(&mut s, "(entmod (append (entget (entlast)) '((-3 . 7))))"), "nil");
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), "((\"ACME\" (1070 . 9)))");
// The same one level down: an application whose groups are not a proper list is refused,
// not read as "no groups" (which would remove its data), and a dotted tail after real
// groups is not dropped.
for bad in ["(\"ACME\" . 7)", "(\"ACME\" (1070 . 1) . 5)", "(\"NEW\" . \"x\")"] {
assert_eq!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '((-3 {bad}))))")), "nil", "{bad}");
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), "((\"ACME\" (1070 . 9)))", "{bad}");
assert_eq!(ok(&mut s, &format!("(entmake '((0 . \"LINE\") (10 0 0 0) (11 9 0 0) (-3 {bad})))")), "nil", "{bad}");
assert_eq!(ok(&mut s, "(entlast)"), last, "{bad}");
}
}
#[test]
fn runs_of_one_application_in_any_case_are_one_list() {
// A file with `ACME` and `acme` runs on one entity: entget shows one application with every
// group, and writing that list back with entmod keeps them all.
let dxf = "0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n2A\n8\n0\n10\n0\n20\n0\n30\n0\n11\n10\n21\n0\n31\n0\n\
1001\nACME\n1070\n1\n1001\nacme\n1070\n2\n1001\nOTHER\n1000\nx\n0\nENDSEC\n0\nEOF\n";
let mut s = session();
s.open_drawing(cadcraft_io::read_dxf(dxf.as_bytes()).unwrap(), "runs", None);
let want = "((\"ACME\" (1070 . 1) (1070 . 2)) (\"OTHER\" (1000 . \"x\")))";
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), want);
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"acme\"))))"), "((\"ACME\" (1070 . 1) (1070 . 2)))");
assert!(ok(&mut s, "(entmod (entget (entlast) '(\"*\")))").contains("LINE"));
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), want);
}
#[test]
fn acad_xdata_of_a_dimension_is_refused_but_kept_on_other_entities() {
// A dimension's ACAD run is its DSTYLE overrides, written from the model: raw ACAD groups
// on it are refused (nil, nothing changes). On a line, ACAD is foreign data and stays.
let mut s = session();
s.script("dimlinear 0,0 10,0 5,-3\n").unwrap();
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget (entlast))))"), "\"DIMENSION\"");
assert_eq!(ok(&mut s, "(entmod (append (entget (entlast)) '((-3 (\"ACAD\" (1070 . 1))))))"), "nil");
assert_eq!(ok(&mut s, "(assoc -3 (entget (entlast) '(\"*\")))"), "nil");
let made = ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0) (-3 (\"ACAD\" (1000 . \"MINE\") (1070 . 42)))))");
assert!(made.contains("LINE"));
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"ACAD\"))))"), "((\"ACAD\" (1000 . \"MINE\") (1070 . 42)))");
}
#[test]
fn entity_lists_hold_angles_in_radians() {
let mut s = session();
@@ -908,6 +1056,48 @@ fn appload_and_load() {
assert!(r["error"].as_str().is_some_and(|e| e.contains("bad argument type")));
}
/// Echo lines until the next one trims the command history from the front.
fn fill_history(s: &mut Session) {
// Grow it to its first trim, then back up to the length it had just before it.
let mut top = 0;
loop {
let len = s.log.len();
s.echo("filler");
if s.log.len() < len {
break;
}
top = s.log.len();
}
while s.log.len() < top {
s.echo("filler");
}
}
/// #3643: the `lisp` and `appload` JSON commands report the lines their run printed, also when
/// the command history is trimmed from the front while it runs.
#[test]
fn a_lisp_calls_output_survives_the_history_trim() {
let mut s = session();
// The `y` lines a reply reports; it reports nothing from before the call.
let ys = |r: &serde_json::Value| {
let out = r["output"].as_array().cloned().unwrap_or_default();
assert!(!out.contains(&serde_json::json!("filler")), "{r}");
out.iter().filter(|l| *l == "y").count()
};
let lines = |n: usize| format!("(repeat {n} (princ \"y\") (terpri))");
fill_history(&mut s);
let r = s.execute("lisp", &serde_json::json!({"code": lines(20)})).unwrap();
assert_eq!(ys(&r), 20, "{r}");
fill_history(&mut s);
let r = s.execute("appload", &serde_json::json!({"name": "ys.lsp", "text": lines(20)})).unwrap();
assert_eq!(ys(&r), 20, "{r}");
// A run that prints more than the history holds reports every line still held: all its own.
fill_history(&mut s);
let held = s.log.len();
let r = s.execute("lisp", &serde_json::json!({"code": lines(held + 100)})).unwrap();
assert_eq!(ys(&r), s.log.len(), "{r}");
}
/// `command` gives an entity name, alone or as `entsel` returns it (name and point), to a prompt
/// picking one object: the point picks that object, and a bare name stands at its DXF group 10
/// point. Each call and its numbers are AutoCAD 2024's (accoreconsole, read back with `entget`);
@@ -1631,6 +1821,54 @@ fn an_expression_at_a_prompt_has_a_short_allowance() {
assert_eq!(circles(&s), 0);
}
/// #3635: a script's next input goes to a routine an earlier input started only once that routine
/// has run on to its end or to the input it waits for: where there is no window, nothing else
/// carries on a routine that gave the interface a frame. Each loop here takes more than a slice.
#[test]
fn a_script_runs_a_long_routine_on_before_its_next_input() {
let mut s = session();
let circles = |s: &Session| s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_doc::EntityKind::Circle(_))).count();
let n = super::SLICE;
// CIRCLE's radius (a `pause`) and the `getint` answer come on the next lines, after a loop
// each; the last line's routine runs on before the script returns.
let script = format!(
"(progn (repeat {n} (setq x 1)) (command \"circle\" \"0,0\" pause) (setq k (getint \"Count: \")) (repeat {n} (setq x 2)))\n\
5\n\
42\n\
(setq after (list x k))\n\
(progn (repeat {n} (setq x 3)) (setq last x))\n"
);
s.script(&script).unwrap();
assert!(!s.lisp_running(), "{:?}", s.log);
assert_eq!(circles(&s), 1, "{:?}", s.log);
assert_eq!(ok(&mut s, "after"), "(2 42)");
assert_eq!(ok(&mut s, "last"), "3");
}
/// #3635: a routine a script runs on gets no frames, so nothing can stop it by hand: an endless
/// one is stopped with an error once it has taken the steps it may, an endless `*error*` handler
/// in turn, and the script goes on.
#[test]
fn a_script_stops_an_endless_routine() {
let mut s = session();
let slice = super::SLICE;
// How far an endless count gets with a cap of `cap` steps; the line after it still runs.
let count = |s: &mut Session, cap: u64| {
s.lisp.limits.frameless_steps = cap;
s.script("(setq i 0)\n(while T (setq i (1+ i)))\n(setq after i)\n").unwrap();
assert!(!s.lisp_running(), "{:?}", s.log);
ok(s, "after").parse::<i64>().unwrap()
};
// Stopped after its first slice, and after five: about five times as far, not unbounded.
let first = count(&mut s, 0);
let five = count(&mut s, 4 * slice);
assert!(first > 0 && five > 3 * first && five < 7 * first, "{first} {five}");
assert!(s.log.iter().any(|l| l.starts_with("; error: routine stopped after")), "{:?}", s.log);
s.script("(defun *error* (msg) (setq caught msg) (while T))\n(while T)\n").unwrap();
assert!(!s.lisp_running(), "the routine and its handler were stopped: {:?}", s.log);
assert!(ok(&mut s, "caught").contains("routine stopped after"));
}
/// #1933: a whole number past 32 bits is a real, as the reader and `fix` make one, not a wrapped
/// or clamped integer: `atoi` gives the number its digits read as, `gcd` the true divisor.
#[test]
+50 -1
View File
@@ -437,7 +437,7 @@ impl Formatted {
out.push_str("\\P");
}
if *props != emitted {
out.push_str(&props.code());
out.push_str(&props.code_after(&emitted));
emitted = props.clone();
}
let end = chars.iter().skip(i).position(|c| *c == '\n').map_or(chars.len(), |n| i + n);
@@ -664,4 +664,53 @@ mod tests {
assert!(Formatted::fits(&format!("{}a{}", "{".repeat(64), "}".repeat(64))));
assert!(!Formatted::fits(&format!("{}a{}", "{".repeat(65), "}".repeat(65))));
}
#[test]
fn mixed_paragraph_line_spacing_reset_survives_textedit_roundtrip() {
let mut s = crate::Session::new();
let res = s
.execute(
"mtext",
&serde_json::json!({
"at": [0.0, 0.0],
"height": 0.2,
"text": "\\pxsm1.5;First\\P\\pxs*;Second\\PThird",
}),
)
.unwrap();
let handle = res["handle"].as_str().unwrap().to_string();
let doc_handle = cadcraft_doc::Handle::parse_hex(&handle).unwrap();
let orig_contents = match &s.doc().unwrap().entity(doc_handle).unwrap().kind {
cadcraft_doc::EntityKind::MText(m) => m.contents.clone(),
_ => panic!("expected MText"),
};
let mut f = Formatted::from_contents_with_height(&orig_contents, Some(0.2));
assert!(f.set_text("First\nSecond edited\nThird", &CharFmt::default()));
let edited = f.to_contents();
s.execute("textedit", &serde_json::json!({"handle": handle, "text": edited})).unwrap();
let saved_contents = match &s.doc().unwrap().entity(doc_handle).unwrap().kind {
cadcraft_doc::EntityKind::MText(m) => m.contents.clone(),
_ => panic!("expected MText"),
};
let reopened = Formatted::from_contents_with_height(&saved_contents, Some(0.2));
assert_eq!(reopened.para(0).line_spacing, Some(cadcraft_fonts::ParaLineSpacing::Multiple(1.5)), "{saved_contents}");
assert_eq!(reopened.para(1).line_spacing, None, "{saved_contents}");
assert_eq!(reopened.para(2).line_spacing, None, "{saved_contents}");
let p_08 = cadcraft_fonts::MTextParams {
line_spacing: 0.8,
line_spacing_exact: false,
..cadcraft_fonts::MTextParams::new(cadcraft_geom::Vec2::ZERO, 0.2)
};
let saved_layout = cadcraft_fonts::layout_mtext_with(&saved_contents, &p_08);
let all_15 = cadcraft_fonts::layout_mtext_with("\\pxsm1.5;First\\PSecond edited\\PThird", &p_08);
assert!(
saved_layout.bounds.height() < all_15.bounds.height() - 0.05,
"saved={:?} vs all_15={:?} ({saved_contents})",
saved_layout.bounds.height(),
all_15.bounds.height()
);
}
}
+7 -32
View File
@@ -126,36 +126,14 @@ pub fn snap_name(m: u32) -> &'static str {
mode::ALL.iter().find(|(b, _)| *b == m).map_or("None", |(_, n)| *n)
}
/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
/// first, then every other snap of the modes in `osmode` under the aperture (each endpoint of
/// each object, each intersection …; [`crate::snap::osnap_all`]), best first, without repeats.
/// The candidate snaps near `cursor` for Tab cycling: every object snap within the aperture, the
/// one [`crate::snap::osnap`] picks first and the rest in its order (specific snaps nearest
/// first, then deferred snaps, then Nearest), without repeats.
pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
snap_candidates_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
}
/// [`snap_candidates`] skipping entities (and block leaves) on `frozen` layers in `space`.
#[allow(clippy::too_many_arguments)]
pub fn snap_candidates_with_frozen(
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
) -> Vec<SnapHit> {
// A base that is not a number would give meaningless perpendiculars and tangents.
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 || base.is_some_and(|b| !b.is_finite()) {
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 {
return Vec::new();
}
let mut out: Vec<SnapHit> = crate::snap::osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen).into_iter().collect();
for h in crate::snap::osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen) {
if !out.iter().any(|o| o.same(&h, aperture)) {
out.push(h);
}
}
out
crate::snap::osnap_all(d, space, cursor, aperture, osmode, base, deferred)
}
/// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with.
@@ -365,15 +343,12 @@ impl Session {
Frame::Snap { mode } => {
// Snap the point with this mode alone, within the aperture.
let prompt = self.current_prompt();
let (doc, space, frozen) = {
let st = self.state()?;
(st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec())
};
let space = self.space();
let aperture = self.pixel_size() * self.settings.aperture.max(1.0);
let hatch = if self.settings.osnaphatch { mode::HATCH } else { 0 };
let base = prompt.as_ref().and_then(|q| q.base);
let deferred = prompt.as_ref().is_some_and(|q| q.deferred);
let hit = crate::snap::osnap_with_frozen(&doc, &space, p, aperture, mode | hatch, base, deferred, &frozen);
let hit = crate::snap::osnap(self.doc()?, &space, p, aperture, mode | hatch, base, deferred);
match hit {
Some(h) if self.point_mods.is_empty() => return self.input_snapped(h),
Some(h) => p = h.point,
+11 -3
View File
@@ -76,14 +76,17 @@ pub struct Prompt {
/// Rubber-band origin (for direct distance entry, ortho and polar).
pub base: Option<Vec2>,
/// The command resolves deferred tangent/perpendicular snaps ([`Input::Deferred`]) at this
/// prompt (a point with no base yet, e.g. the first point of a line; with a base, only
/// tangents, e.g. a circle's radius). Elsewhere a deferred pick arrives as the plain point it
/// was picked at.
/// prompt (a point with no base yet, e.g. the first point of a line). Elsewhere a deferred
/// pick arrives as the plain point it was picked at.
pub deferred: bool,
/// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit
/// cell, MTEXT): ortho does not bend the opposite corner, so the rectangle keeps its area.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub corner: bool,
/// Dynamic Input asks for this point as X and Y, whatever DYNPIFORMAT says: a rectangle's size
/// (RECTANG's other corner), as the reference application does.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub xy: bool,
/// The grip this prompt stretches (one hot grip at the STRETCH prompt), as (object, grip
/// index): Dynamic Input shows its dimensions ([`crate::grip_dims`]).
#[serde(skip_serializing_if = "Option::is_none")]
@@ -193,6 +196,11 @@ impl Prompt {
self.corner = true;
self
}
/// Dynamic Input asks for X and Y (the `xy` field).
pub fn xy(mut self) -> Self {
self.xy = true;
self
}
/// Asks for a distance from the base (the `distance` field).
pub fn distance(mut self) -> Self {
self.distance = true;
+6 -1
View File
@@ -365,7 +365,12 @@ fn text_groups(c: &Ctx, ents: &[&Entity], texts: &[&Text]) -> Vec<Group> {
c.row("positionY", "Position Y", Kind::Distance, texts.iter().map(|t| json!(t.justify_point().y))),
c.row("positionZ", "Position Z", Kind::Distance, texts.iter().map(|t| json!(t.insert.z))),
];
vec![Group { name: "Text", rows: text }, Group { name: "Geometry", rows: geometry }]
// The text's own effects (new text takes them from its style).
let misc = vec![
c.row("upsideDown", "Upside down", Kind::Bool, texts.iter().map(|t| json!(t.upside_down))),
c.row("backwards", "Backwards", Kind::Bool, texts.iter().map(|t| json!(t.backwards))),
];
vec![Group { name: "Text", rows: text }, Group { name: "Geometry", rows: geometry }, Group { name: "Misc", rows: misc }]
}
fn mtext_groups(c: &Ctx, ents: &[&Entity], mts: &[&MText]) -> Vec<Group> {
+3 -1
View File
@@ -48,6 +48,8 @@ fn text(at: Vec2, h: f64, s: &str) -> EntityKind {
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
backwards: false,
upside_down: false,
})
}
@@ -214,7 +216,7 @@ pub fn bracket() -> Drawing {
add(on("Notes"), text(Vec2::new(4.1, -0.3), 0.16, "FRONT VIEW"));
add(
on("Notes"),
EntityKind::MText(MText { insert: v3(Vec2::new(14.2, 6.2)), height: 0.12, width: 3.4, attach: 1, rotation: 0.0, style: "Standard".into(), contents: "NOTES:\\P1. MATERIAL: 6061-T6 ALUMINUM.\\P2. BREAK ALL SHARP EDGES 0.02 MAX.\\P3. BORE %%c1.750 THRU, H7.\\P4. FINISH: CLEAR ANODIZE.".into(), line_spacing: 1.0, line_spacing_exact: false, columns: None }),
EntityKind::MText(MText { insert: v3(Vec2::new(14.2, 6.2)), height: 0.12, width: 3.4, attach: 1, rotation: 0.0, style: "Standard".into(), contents: "NOTES:\\P1. MATERIAL: 6061-T6 ALUMINUM.\\P2. BREAK ALL SHARP EDGES 0.02 MAX.\\P3. BORE %%c1.750 THRU, H7.\\P4. FINISH: CLEAR ANODIZE.".into(), line_spacing: 1.0, line_spacing_exact: false, columns: None, background: None }),
);
let tb0 = Vec2::new(14.0, -0.5);
add(on("Title"), lwpoly(rect_vertices(tb0, tb0 + Vec2::new(4.0, 2.0)), true));
+132 -26
View File
@@ -1,6 +1,6 @@
//! Hit testing and window/crossing selection.
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, Prim, Space, entity_bounds};
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, Prim, Space, ViewportBounds, entity_bounds};
use cadcraft_geom::{Bounds2, Line, Vec2, point_in_polygon};
use crate::spatial::{self, SpatialIndex};
@@ -13,8 +13,19 @@ fn draws_a_block(e: &Entity) -> bool {
/// Polylines approximating an entity for hit testing, tessellated at `tol`.
pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec<Vec<Vec2>> {
hit_polylines_in(d, e, &mut ViewportBounds::new(&[]), tol, true)
}
/// [`hit_polylines`] through the layout viewport `view`: the parts of a block reference on the
/// layers frozen in that viewport are not drawn there, so they are not hit, and the box around a
/// dimension or multileader is the box around the parts that are drawn ([`bounds_in`]). A
/// dimension's definition points stay, as [`ViewportBounds`] says. With `room` the rectangle a
/// dimension is hit along keeps the room of the text the viewport leaves out ([`outline_in`]), as
/// a selection that touches the dimension tests it; without, it is the box of what the viewport
/// draws, as a selection that must hold the dimension tests it.
fn hit_polylines_in<'a>(d: &'a Drawing, e: &Entity, view: &mut ViewportBounds<'a>, tol: f64, room: bool) -> Vec<Vec<Vec2>> {
if matches!(e.kind, EntityKind::Insert(_)) {
let list = insert_geometry(d, e, tol);
let list = insert_geometry(d, e, tol, view.frozen());
return list
.prims
.iter()
@@ -57,19 +68,21 @@ pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec<Vec<Vec2>> {
{
// 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);
let b = bounds_in(d, e, None, view);
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::MLeader(_)) || draws_a_block(e) {
let list = cadcraft_render::build_entities(
let list = cadcraft_render::build_entities_in_viewport(
d,
std::iter::once(e),
&cadcraft_render::Options { tolerance: tol, text: false, linetypes: false, ..Default::default() },
view.frozen(),
);
v = list.prims.iter().map(|p| list.points(p).to_vec()).collect();
let c = if room { outline_in(d, e, view, b) } else { b }.corners();
v.push(vec![c[0], c[1], c[2], c[3], c[0]]);
}
v
@@ -122,8 +135,46 @@ 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 rectangle a selection through the layout viewport `view` hits `e` along, where `b` is the
/// box of what that viewport draws of it ([`bounds_in`]): `b`, and for a dimension drawn from a
/// block also the room of the text in that block that the viewport leaves out
/// ([`ViewportBounds::leaves_out`]) and the drawing itself shows. Without the text the box ends at
/// the dimension line, so a side of the rectangle would run through the place of the text, and a
/// crossing window there, which touched nothing while the rectangle held the text, would take the
/// dimension by that side. Text the drawing hides (its own invisible flag, a layer frozen for the
/// whole drawing or turned off) had no room in the rectangle before a viewport was counted, and
/// has none here. A selection that only has to touch the dimension tests this rectangle, its box
/// test first included ([`touch_box_in`]). A window and a window polygon still need only what the
/// viewport draws inside them ([`in_window_in`], [`select_polygon_in`]).
fn outline_in(d: &Drawing, e: &Entity, view: &ViewportBounds<'_>, b: Bounds2) -> Bounds2 {
let EntityKind::Dimension(dm) = &e.kind else { return b };
if view.frozen().is_empty() {
return b;
}
let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n)) else { return b };
let at = dm.insertion_point.xy();
let shown = |part: &Entity| part.common.visible && d.layer(&part.common.layer).is_none_or(|l| !l.frozen && l.on);
let mut out = b;
for part in
blk.entities.iter().filter(|part| matches!(part.kind, EntityKind::Text(_) | EntityKind::MText(_)) && view.leaves_out(part) && shown(part))
{
let t = entity_bounds(d, part, 0);
if !t.is_empty() {
out = out.union(&Bounds2::from_points([t.min + at, t.max + at]));
}
}
out
}
/// What the layout viewport that freezes the layers in `frozen` draws of the block reference `e`
/// (none frozen: what the drawing shows), for hit testing at `tol`.
fn insert_geometry(d: &Drawing, e: &Entity, tol: f64, frozen: &[String]) -> cadcraft_render::DisplayList {
cadcraft_render::build_entities_in_viewport(
d,
std::iter::once(e),
&cadcraft_render::Options { tolerance: tol, linetypes: false, ..Default::default() },
frozen,
)
}
/// The part of an image its clips leave showing, as triangles (three points each); empty when a
@@ -141,8 +192,10 @@ fn shown_image_tris(img: &cadcraft_render::DImage) -> Vec<Vec2> {
tris
}
fn insert_fill_hits_box(d: &Drawing, e: &Entity, bx: &Bounds2, tol: f64) -> bool {
let list = insert_geometry(d, e, tol);
/// Whether a fill or an image of the block reference `e` reaches into the box `bx`, of what the
/// layout viewport that freezes the layers in `frozen` draws of it ([`insert_geometry`]).
fn insert_fill_hits_box(d: &Drawing, e: &Entity, bx: &Bounds2, tol: f64, frozen: &[String]) -> bool {
let list = insert_geometry(d, e, tol, frozen);
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 };
@@ -169,11 +222,17 @@ fn dist_to_polyline(pts: &[Vec2], p: Vec2) -> f64 {
/// Distance from `p` to the entity (0 inside text boxes and solid fills).
pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 {
let polys = hit_polylines(d, e, tol);
entity_distance_in(d, e, &mut ViewportBounds::new(&[]), p, tol)
}
/// [`entity_distance`] through the layout viewport `view`: to what that viewport draws of the
/// entity ([`hit_polylines_in`]).
fn entity_distance_in<'a>(d: &'a Drawing, e: &Entity, view: &mut ViewportBounds<'a>, p: Vec2, tol: f64) -> f64 {
let polys = hit_polylines_in(d, e, view, tol, true);
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_blank_mtext(d, e, 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, view, p) {
best = 0.0;
}
// A solid hatch fills its loops with odd parity under its island style, as it is drawn, not
@@ -194,8 +253,10 @@ pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 {
/// Whether `p` is on the text of a dimension or multileader: inside the box around its words,
/// turned with the text, as plain text is hit anywhere inside its box. Their other geometry is
/// hit along its lines, so without this the cursor found the object only between the letters'
/// edges and the lines.
fn in_text(d: &Drawing, e: &Entity, p: Vec2) -> bool {
/// edges and the lines. Text in a dimension's block that `view` leaves out
/// ([`ViewportBounds::leaves_out`]) does not count: the viewport does not draw text on a layer
/// frozen in it, and a pick in its box finds nothing there, as in AutoCAD.
fn in_text(d: &Drawing, e: &Entity, view: &ViewportBounds<'_>, p: Vec2) -> bool {
match &e.kind {
// A dimension with a block (as AutoCAD saves them) is drawn from that block: its text is
// the text there, not the text the dimension's own geometry would place.
@@ -203,7 +264,7 @@ fn in_text(d: &Drawing, e: &Entity, p: Vec2) -> bool {
// The block draws translated by the insertion point (group 12): test there (#2634).
Some(blk) => {
let p = p - dm.insertion_point.xy();
blk.entities.iter().any(|be| match &be.kind {
blk.entities.iter().filter(|be| !view.leaves_out(be)).any(|be| match &be.kind {
EntityKind::MText(t) => in_box(cadcraft_render::layout_mtext_entity(d, t).strokes.into_iter().flatten(), t.rotation, p),
EntityKind::Text(_) => entity_bounds(d, be, 0).contains(p),
_ => false,
@@ -380,6 +441,26 @@ pub(crate) fn blank_frame_only(d: &Drawing, e: &Entity, probe: &Bounds2, cursor:
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)))
}
/// The box a selection made through the layout viewport `view` tests `e` against: the box of
/// what that viewport draws of it. `known` is the box the spatial index holds, of what the
/// drawing shows; it stands unless the viewport freezes layers and `e` draws a block (a block
/// reference, a dimension, a multileader), whose contents on those layers the viewport leaves
/// out. That box is never larger than `known`, so the index still finds every candidate. The
/// frame of blank text stays in it, as in [`bounds_of`].
fn bounds_in<'a>(d: &'a Drawing, e: &Entity, known: Option<Bounds2>, view: &mut ViewportBounds<'a>) -> Bounds2 {
let from_a_block = matches!(e.kind, EntityKind::Insert(_) | EntityKind::Dimension(_) | EntityKind::MLeader(_));
if from_a_block && !view.frozen().is_empty() { pick_bounds(d, e, view.entity_bounds(d, e)) } else { bounds_of(d, e, known) }
}
/// The box a selection through `view` that only has to touch `e` (a pick, a crossing window, a
/// fence, a crossing polygon) tests before its hit geometry: [`bounds_in`] with the room
/// [`outline_in`] keeps, so a side of the rectangle a dimension is hit along that lies in that
/// room is not passed over. A selection that must hold `e` tests [`bounds_in`] itself.
fn touch_box_in<'a>(d: &'a Drawing, e: &Entity, known: Option<Bounds2>, view: &mut ViewportBounds<'a>) -> Bounds2 {
let b = bounds_in(d, e, known, view);
outline_in(d, e, view, b)
}
pub(crate) fn is_infinite(e: &Entity) -> bool {
matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_))
}
@@ -456,10 +537,13 @@ pub(crate) fn pick_scanning(
) -> Option<Handle> {
let probe = Bounds2::new(p, p).expand(aperture);
let query = probe.expand(aperture);
// One viewport's boxes serve every candidate, from whichever of the readings below asks.
let view = std::cell::RefCell::new(ViewportBounds::new(frozen));
let hit = |e: &Entity, known: Option<Bounds2>| {
let view = &mut *view.borrow_mut();
selectable(d, e, frozen)
&& (is_infinite(e) || bounds_of(d, e, known).expand(aperture).intersects(&probe))
&& entity_distance(d, e, p, aperture / 4.0) <= aperture
&& (is_infinite(e) || touch_box_in(d, e, known, view).expand(aperture).intersects(&probe))
&& entity_distance_in(d, e, view, p, aperture / 4.0) <= aperture
};
// Candidates come topmost first: the first within the aperture is the one.
let topmost = |ix: &SpatialIndex, cands: Vec<u32>, below: u32| {
@@ -506,9 +590,13 @@ pub fn pick_all_in(d: &Drawing, space: &Space, frozen: &[String], p: Vec2, apert
let ix = spatial::index(d, space);
let probe = Bounds2::new(p, p).expand(aperture);
let Some(cands) = candidates(d, space, &ix, &probe.expand(aperture), true, true) else { return Vec::new() };
let mut view = ViewportBounds::new(frozen);
cands
.filter(|(e, known)| selectable(d, e, frozen) && (is_infinite(e) || bounds_of(d, e, *known).expand(aperture).intersects(&probe)))
.filter(|(e, _)| entity_distance(d, e, p, aperture / 4.0) <= aperture)
.filter(|(e, known)| {
selectable(d, e, frozen)
&& (is_infinite(e) || touch_box_in(d, e, *known, &mut view).expand(aperture).intersects(&probe))
&& entity_distance_in(d, e, &mut view, p, aperture / 4.0) <= aperture
})
.map(|(e, _)| e.handle)
.collect()
}
@@ -555,7 +643,8 @@ pub(crate) fn select_window_with(
) -> Vec<Handle> {
let Some(cands) = candidates(d, space, ix, &bx, crossing, false) else { return Vec::new() };
let tol = window_tol(&bx);
cands.filter(|(e, known)| selectable(d, e, frozen) && in_window(d, e, *known, &bx, crossing, tol)).map(|(e, _)| e.handle).collect()
let mut view = ViewportBounds::new(frozen);
cands.filter(|(e, known)| selectable(d, e, frozen) && in_window_in(d, e, *known, &mut view, &bx, crossing, tol)).map(|(e, _)| e.handle).collect()
}
/// The tessellation tolerance window and crossing tests use for a box.
@@ -566,15 +655,29 @@ pub(crate) fn window_tol(bx: &Bounds2) -> f64 {
/// Whether a window box (`crossing` false: entirely inside) or a crossing box (inside or
/// touching its geometry, not just its bounding box) selects `e`.
pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option<Bounds2>, bx: &Bounds2, crossing: bool, tol: f64) -> bool {
in_window_in(d, e, known, &mut ViewportBounds::new(&[]), bx, crossing, tol)
}
/// [`in_window`] through the layout viewport `view`: a block reference is inside the box, or
/// touches it, by the parts that viewport draws ([`bounds_in`], [`hit_polylines_in`]).
fn in_window_in<'a>(
d: &'a Drawing,
e: &Entity,
known: Option<Bounds2>,
view: &mut ViewportBounds<'a>,
bx: &Bounds2,
crossing: bool,
tol: f64,
) -> bool {
let infinite = is_infinite(e);
let eb = bounds_of(d, e, known);
let eb = bounds_in(d, e, known, view);
if !infinite && bx.contains_box(&eb) {
return true;
}
if !crossing || (!infinite && !eb.intersects(bx)) {
if !crossing || (!infinite && !outline_in(d, e, view, eb).intersects(bx)) {
return false;
}
let polys = hit_polylines(d, e, tol);
let polys = hit_polylines_in(d, e, view, tol, true);
let hit = polys.iter().any(|pl| {
if pl.len() == 1 {
pl.first().is_some_and(|p| bx.contains(*p))
@@ -585,7 +688,7 @@ pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option<Bounds2>, bx: &Bo
// 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))
|| (matches!(e.kind, EntityKind::Insert(_)) && insert_fill_hits_box(d, e, bx, tol, view.frozen()))
{
return true;
}
@@ -629,13 +732,14 @@ pub(crate) fn select_fence_with(
let tol = (fb.width() + fb.height()).max(1e-9) / 2000.0;
let probe = fb.expand(tol);
let Some(cands) = candidates(d, space, ix, &probe, true, false) else { return Vec::new() };
let mut view = ViewportBounds::new(frozen);
let mut out = Vec::new();
for (e, known) in cands {
// Infinite objects have no useful bounds; like window selection, test their geometry directly.
if !selectable(d, e, frozen) || (!is_infinite(e) && !bounds_of(d, e, known).intersects(&probe)) {
if !selectable(d, e, frozen) || (!is_infinite(e) && !touch_box_in(d, e, known, &mut view).intersects(&probe)) {
continue;
}
let polys = hit_polylines(d, e, tol);
let polys = hit_polylines_in(d, e, &mut view, tol, true);
let hit = fence.windows(2).any(|f| {
let (Some(a), Some(b)) = (f.first(), f.get(1)) else { return false };
let fl = Line::new(*a, *b);
@@ -666,17 +770,18 @@ pub fn select_polygon_in(d: &Drawing, space: &Space, frozen: &[String], poly: &[
let Some(cands) = candidates(d, space, &ix, &pb, crossing, false) else { return Vec::new() };
let edges: Vec<Line> =
poly.windows(2).filter_map(|w| Some(Line::new(*w.first()?, *w.get(1)?))).chain(poly.last().map(|l| Line::new(*l, *first))).collect();
let mut view = ViewportBounds::new(frozen);
let mut out = Vec::new();
for (e, known) in cands {
let infinite = is_infinite(e);
if !selectable(d, e, frozen) || (infinite && !crossing) {
continue;
}
let eb = bounds_of(d, e, known);
let eb = if crossing { touch_box_in(d, e, known, &mut view) } else { bounds_in(d, e, known, &mut view) };
if !infinite && if crossing { !eb.intersects(&pb) } else { !pb.contains_box(&eb) } {
continue;
}
let polys = hit_polylines(d, e, tol);
let polys = hit_polylines_in(d, e, &mut view, tol, crossing);
let crosses = polys.iter().any(|pl| {
pl.windows(2).any(|w| {
w.first().zip(w.get(1)).is_some_and(|(p, q)| edges.iter().any(|f| cadcraft_geom::line_line(f, &Line::new(*p, *q)).is_some()))
@@ -857,6 +962,7 @@ mod tests {
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
})
}
+123 -32
View File
@@ -16,6 +16,21 @@ impl Session {
self.input_line(t, false)
}
/// Whether Space with `typed` on the command line types a space instead of submitting: at a
/// free-text prompt, or inside an unclosed parenthesised LISP expression where the command
/// line evaluates one.
pub fn space_is_text(&self, typed: &str) -> bool {
if self.current_prompt().is_some_and(|p| p.accept.text && !p.accept.point && !p.accept.number) {
return true;
}
let accepts_lisp = match self.current_prompt() {
None => self.lisp_prompt().is_none(),
Some(p) => !p.accept.text && self.lisp_prompt().is_none() && !self.lisp_groups_undo(),
};
let rest = if self.running.is_none() { typed.trim_start() } else { typed };
accepts_lisp && matches!(lisp_token_end(rest), Some(None))
}
/// One line of input: each space ends an input and an empty input (two spaces in a row, a
/// trailing space, an empty line) is Enter, which at `Command:` repeats the last command. In a
/// script, a free-text prompt (TEXT/MTEXT contents) takes the rest of the line, a prompt with
@@ -25,6 +40,11 @@ impl Session {
let mut rest = line;
let mut first = true;
loop {
// A script's next input goes to what the routine an earlier one started waits for, or
// comes after that routine: carry it on first, as the window's frames would.
if script {
self.lisp_run_until_input();
}
if self.running.is_none() {
if !script && !first {
return Ok(());
@@ -187,7 +207,14 @@ impl Session {
return Err(EngineError::BadParams { cmd: "script".into(), msg: "a script is already running; nested scripts are not supported".into() });
}
self.in_script = true;
// A script that a LISP routine started (`(command "_.script" …)`) feeds its own lines: they
// are not the routine's input, so a command they start answers as from a script.
let program_input = std::mem::replace(&mut self.program_input, false);
let r = self.script_lines(text);
self.program_input = program_input;
// The routine the last input started or answered runs on too: with no window, nothing
// would carry it on once the script returns.
self.lisp_run_until_input();
self.in_script = false;
r
}
@@ -213,41 +240,105 @@ fn lisp_expression(t: &str) -> bool {
}
/// The next command-line input in `rest` and what follows it: up to a space or tab, except that
/// a LISP expression runs to its closing parenthesis (spaces and quoted strings inside it).
/// a LISP expression runs to its closing parenthesis (spaces, quoted strings and comments
/// inside it).
fn next_token(rest: &str) -> (&str, Option<&str>) {
let lead = rest.len() - rest.trim_start_matches('!').len();
if rest.get(lead..).is_some_and(|r| r.starts_with('(')) {
let (mut depth, mut in_str, mut escaped) = (0i32, false, false);
for (i, c) in rest.char_indices().skip(lead) {
if in_str {
match (escaped, c) {
(true, _) => escaped = false,
(false, '\\') => escaped = true,
(false, '"') => in_str = false,
_ => {}
}
continue;
}
match c {
'"' => in_str = true,
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
let end = i + 1;
// As after any input, a space ends it and a trailing one is Enter.
let more = rest.get(end..).filter(|m| !m.is_empty()).map(|m| m.strip_prefix([' ', '\t']).unwrap_or(m));
return (&rest[..end], more);
}
}
_ => {}
}
match lisp_token_end(rest) {
Some(Some(end)) => {
// As after any input, a space ends it and a trailing one is Enter.
let more = rest.get(end..).filter(|m| !m.is_empty()).map(|m| m.strip_prefix([' ', '\t']).unwrap_or(m));
(&rest[..end], more)
}
// Unbalanced: all of it (the reader reports the error).
return (rest, None);
Some(None) => (rest, None),
None => match rest.split_once([' ', '\t']) {
Some((tok, more)) => (tok, Some(more)),
None => (rest, None),
},
}
match rest.split_once([' ', '\t']) {
Some((tok, more)) => (tok, Some(more)),
None => (rest, None),
}
/// For `rest` starting a parenthesised LISP form (`(…` or `!(…`), the byte offset past its
/// matching `)`, or `Some(None)` while it is still open; `None` when `rest` is not one.
fn lisp_token_end(rest: &str) -> Option<Option<usize>> {
let lead = rest.len() - rest.trim_start_matches('!').len();
let body = rest.get(lead..)?;
if !body.starts_with('(') {
return None;
}
let mut depth = 0i32;
let mut in_str = false;
let mut chars = body.char_indices().peekable();
while let Some((i, c)) = chars.next() {
if in_str {
match c {
'\\' => {
chars.next();
}
'"' => in_str = false,
_ => {}
}
continue;
}
match c {
';' if chars.peek().is_some_and(|(_, n)| *n == '|') => {
chars.next();
while let Some((_, bc)) = chars.next() {
if bc == '|' && chars.peek().is_some_and(|(_, n)| *n == ';') {
chars.next();
break;
}
}
}
';' => {
for (_, lc) in chars.by_ref() {
if lc == '\n' {
break;
}
}
}
'"' => in_str = true,
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
return Some(Some(lead + i + 1));
}
}
_ => {}
}
}
Some(None)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn open_lisp_forms_treat_space_as_text_only_where_lisp_evaluates() {
let mut s = Session::new();
assert!(s.space_is_text("(+ 1"));
assert!(s.space_is_text(" (+ 1"));
assert!(s.space_is_text("!(+ 1"));
assert!(s.space_is_text("(princ \"a ) b\""));
assert!(s.space_is_text("(princ ;| ) |; 1"));
assert!(s.space_is_text("(+ 1 ; )"));
assert!(!s.space_is_text("(+ 1 ; )\n 2)"));
assert!(!s.space_is_text("(+ 1 2)"));
assert!(!s.space_is_text("!x"));
assert!(!s.space_is_text("line"));
assert_eq!(next_token("(+ 1 ;| ) |; 2) rest"), ("(+ 1 ;| ) |; 2)", Some("rest")));
assert_eq!(next_token("(+ 1 ; )\n 2) rest"), ("(+ 1 ; )\n 2)", Some("rest")));
s.cmdline("circle").unwrap();
assert!(s.space_is_text("(list 1"));
assert!(!s.space_is_text("(list 1 2)"));
s.cancel();
// Prompts inside a waiting LISP routine (`getpoint`) do not evaluate LISP expressions.
s.cmdline("(getpoint)").unwrap();
assert!(!s.space_is_text("(+ 1"));
s.cancel();
}
}
+7
View File
@@ -104,10 +104,17 @@ impl Session {
/// Take the last step back. Inside a LISP routine, the routine's last command first; past
/// those, the drawing's step before the routine, which then starts from there.
pub fn undo(&mut self) -> Result<Option<String>> {
// A REFCLOSE Save that wrote an xref's file stops U inside a routine as it does outside.
if let Some(why) = self.lisp_undo_barrier() {
return Err(EngineError::Other(why));
}
if let Some(label) = self.lisp_take_back(false) {
return Ok(Some(label));
}
let st = self.state_mut()?;
if let Some(why) = st.undo.last().and_then(|snap| cmd::blocks::refedit::undo_barrier(&st.doc, &snap.doc)) {
return Err(EngineError::Other(why));
}
let Some(snap) = st.undo.pop() else { return Ok(None) };
let cur = st.swap_in(snap);
let label = cur.label.clone();
+16
View File
@@ -78,6 +78,15 @@ impl Session {
self.command_origin
}
/// Whether an AutoLISP routine is feeding the command line now: the `(command …)` call it makes,
/// or the token it types into a command that is already running. A script's own lines are the
/// program's input too ([`Session::start`] records [`Origin::Program`] for them), so this tells a
/// routine's call from a script's line, and a routine's call inside a script is this, not the
/// script's.
pub fn lisp_program_input(&self) -> bool {
self.program_input
}
/// 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
@@ -233,6 +242,13 @@ impl Session {
if input == Input::Enter
&& let Some(last) = self.last_command.clone()
{
// Why: `pastetable` has no standalone `interactive` factory because its TSV
// payload comes from the clipboard; repeat it with the last pasted payload.
if last == "pastetable"
&& let Some((tsv, th)) = self.last_paste_table.clone()
{
return self.start_paste_table(&tsv, th);
}
return self.start(&last);
}
return Ok(());
+299 -573
View File
File diff suppressed because it is too large Load Diff
+8 -47
View File
@@ -482,38 +482,13 @@ impl Tracker {
cfg: &TrackConfig,
base: Option<Vec2>,
) -> Option<Track> {
self.track_with_frozen(d, space, cursor, aperture, tol, cfg, base, &[])
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn track_with_frozen(
&mut self,
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
tol: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
frozen: &[String],
) -> Option<Track> {
let t = self.find(d, space, cursor, aperture, tol, cfg, base, frozen);
let t = self.find(d, space, cursor, aperture, tol, cfg, base);
self.last = t.clone();
t
}
#[allow(clippy::too_many_arguments)]
fn find(
&self,
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
tol: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
frozen: &[String],
) -> Option<Track> {
fn find(&self, d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, tol: f64, cfg: &TrackConfig, base: Option<Vec2>) -> Option<Track> {
if !(cursor.is_finite() && aperture.is_finite() && tol.is_finite() && aperture > 0.0 && tol > 0.0) {
return None;
}
@@ -563,7 +538,7 @@ impl Tracker {
// 2. A path crossing an object.
if cfg.running(mode::INT | mode::APP) {
let ix = crate::spatial::index(d, space);
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen, None).map(|(_, p)| p).unwrap_or_default();
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
for prim in prims.iter().take(200) {
let extend = cfg.running(mode::APP) && super::extendable(prim);
for seg in super::prim_segments(prim) {
@@ -613,26 +588,12 @@ pub fn candidate(
aperture: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
) -> Option<Acquired> {
candidate_with_frozen(d, space, cursor, hit, aperture, cfg, base, &[])
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn candidate_with_frozen(
d: &Drawing,
space: &Space,
cursor: Vec2,
hit: Option<&SnapHit>,
aperture: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
frozen: &[String],
) -> Option<Acquired> {
if !can_acquire(cursor, aperture, cfg) {
return None;
}
let ix = crate::spatial::index(d, space);
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen, None).map(|(_, p)| p).unwrap_or_default();
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
candidate_from_prims(cursor, hit, aperture, cfg, base, &prims)
}
@@ -828,7 +789,7 @@ impl crate::Session {
s.orthomode ^= q.shift;
let angbase = self.angle_settings().angbase;
let Ok(st) = self.state() else { return CursorSnap { point: raw, ..Default::default() } };
let (doc, space, frozen) = (st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec());
let (doc, space) = (st.doc.clone(), st.edit_space());
if !raw.is_finite() {
return CursorSnap { point: raw, ..Default::default() };
}
@@ -837,10 +798,10 @@ impl crate::Session {
let cfg = TrackConfig::relative_to(&s, angbase, last);
let osmode = s.osmode | if s.osnaphatch { mode::HATCH } else { 0 };
let ix = crate::spatial::index(&doc, &space);
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred, &frozen);
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred);
let cand = match (osmode & mode::HATCH, near_prims.as_deref()) {
(0, Some(prims)) => candidate_with_prims(raw, hit.as_ref(), q.aperture, &cfg, q.base, prims),
_ => candidate_with_frozen(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base, &frozen),
_ => candidate(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base),
};
let wait = self.tracking.hover(cand, q.now, cfg.shift_acquire, q.shift);
if let Some(h) = hit {
@@ -855,7 +816,7 @@ impl crate::Session {
let (origin, angle) = super::grid_frame_in(&doc, &space);
p = super::grid_snap(p, doc.header.snap_unit(), origin, angle);
}
if let Some(mut t) = self.tracking.track_with_frozen(&doc, &space, p, q.aperture, q.tol, &cfg, q.base, &frozen) {
if let Some(mut t) = self.tracking.track(&doc, &space, p, q.aperture, q.tol, &cfg, q.base) {
// PolarSnap (SNAPTYPE 1): steps of POLARDIST, or of the snap X spacing when it is 0.
let step = if s.polardist > 0.0 { s.polardist } else { s.snapunit.x };
if s.snapmode
+79 -1
View File
@@ -90,6 +90,8 @@ pub struct SpatialIndex {
blocks: BTreeMap<String, Arc<Block>>,
dim_styles: Vec<DimStyle>,
dimscale: f64,
/// ATTMODE: a block reference takes room for the constant attribute values it shows.
attmode: i64,
/// Annotation scale factor and ANNOALLVISIBLE: annotative objects measure at that scale.
anno: (u64, bool),
/// Layers turned off or frozen: block contents on them take no room in their inserts.
@@ -142,7 +144,7 @@ impl SpatialIndex {
}
/// Build, reusing `prev` for chunks the two stores share (only when the bounds context —
/// blocks, dimension styles, DIMSCALE, hidden layers — is the same).
/// blocks, dimension styles, DIMSCALE, ATTMODE, hidden layers — is the same).
fn build_from(d: &Drawing, store: &EntityStore, prev: Option<&SpatialIndex>) -> SpatialIndex {
let prev = prev.filter(|p| p.same_context(d));
let old: std::collections::HashMap<usize, Arc<ChunkIx>> =
@@ -180,6 +182,7 @@ impl SpatialIndex {
blocks: (*d.blocks).clone(),
dim_styles: d.dim_styles.to_vec(),
dimscale: d.header.f64("DIMSCALE", 1.0),
attmode: d.header.i64("ATTMODE", 1),
anno: anno_key(d),
hidden_layers: hidden_layers(d).map(str::to_owned).collect(),
chunks,
@@ -194,6 +197,7 @@ impl SpatialIndex {
self.blocks.len() == d.blocks.len()
&& self.blocks.iter().zip(&d.blocks).all(|((ka, a), (kb, b))| ka == kb && Arc::ptr_eq(a, b))
&& self.dimscale.to_bits() == d.header.f64("DIMSCALE", 1.0).to_bits()
&& self.attmode == d.header.i64("ATTMODE", 1)
&& self.dim_styles == *d.dim_styles
&& self.anno == anno_key(d)
&& self.hidden_layers.iter().map(String::as_str).eq(hidden_layers(d))
@@ -424,7 +428,9 @@ mod tests {
xref_path: None,
explodable: true,
units: 0,
scale_uniformly: false,
array: None,
xref_stamp: None,
};
blk.entities
.push(Entity::new(cadcraft_doc::Handle(1_000_000), EntityKind::Circle(cadcraft_doc::Circle { center: v3(0.0, 0.0), radius: 1.0 })));
@@ -466,6 +472,8 @@ mod tests {
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
backwards: false,
upside_down: false,
}),
6 => EntityKind::Point(cadcraft_doc::Point { p: v3(x, y), angle: 0.0 }),
7 => EntityKind::Insert(Insert {
@@ -768,6 +776,76 @@ mod tests {
assert_eq!(select::select_window(&d, &Space::Model, small, false), vec![h]);
}
/// ATTMODE decides whether a reference shows its block's constant attribute values, and so
/// whether they take room in its bounds, without touching the space or the block table: the
/// index must not be reused across a change of it.
#[test]
fn index_follows_attmode_for_constant_attribute_values() {
let mut d = Drawing::new_imperial();
let mut blk = (**drawing(1, 0).blocks.get("B").unwrap()).clone();
let text = cadcraft_doc::Text {
insert: v3(0.0, 500.0),
align_pt: None,
height: 1.0,
value: "C4".into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
backwards: false,
upside_down: false,
};
let def = cadcraft_doc::Attrib {
tag: "C".into(),
text,
invisible: false,
constant: true,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
};
blk.entities.push(Entity { handle: cadcraft_doc::Handle(2_000_000), common: Common::default(), kind: EntityKind::AttDef(def) });
d.blocks.insert("B".into(), Arc::new(blk));
for i in 0..MIN_INDEXED {
let x = 1000.0 + i as f64;
d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: v3(x, 0.0), b: v3(x, 1.0) })).unwrap();
}
let insert = Insert {
block: "B".into(),
insert: v3(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,
};
d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
d.header.set_i64("ATTMODE", 0);
let hidden = SpatialIndex::build(&d, &d.model);
d.header.set_i64("ATTMODE", 1);
assert!(!hidden.matches(&d, &d.model));
let reused = SpatialIndex::build_from(&d, &d.model, Some(&hidden));
let fresh = SpatialIndex::build(&d, &d.model);
let last = u32::try_from(MIN_INDEXED).unwrap();
assert_eq!(reused.bounds(last), fresh.bounds(last));
assert_ne!(fresh.bounds(last), hidden.bounds(last), "the value shown at ATTMODE 1 takes room");
// The top-down picker skips a chunk whose cached envelope misses the query: a box at the
// value, far above everything else, must reach the reference through the reused index.
let at_value = Bounds2::new(Vec2::new(-1.0, 499.0), Vec2::new(3.0, 502.0));
let top = |ix: &SpatialIndex| ix.top_down(&at_value, false, usize::MAX).unwrap().map(|(i, _, _)| i).collect::<Vec<u32>>();
assert_eq!(top(&reused), vec![last], "the reference is found at its value");
assert_eq!(top(&reused), top(&fresh));
assert_eq!(Some(top(&reused)), reused.query(&at_value, false), "as the tree finds it");
assert!(top(&hidden).is_empty(), "nothing is there while the value is hidden");
}
#[test]
fn small_spaces_are_scanned() {
let d = drawing(1, MIN_INDEXED - 1);
+12
View File
@@ -3,6 +3,7 @@
use serde_json::{Value, json};
use crate::{EngineError, Result, Session};
use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_scale};
mod table;
@@ -11,6 +12,8 @@ const SESSION_VARS: &[&str] = &[
"ATTREQ",
"OSMODE",
"OSNAPHATCH",
"HPSPACE",
"HPDOUBLE",
"ANNOAUTOSCALE",
"ORTHOMODE",
"POLARMODE",
@@ -85,6 +88,8 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
let v = match n.as_str() {
"OSMODE" => json!(st.osmode),
"OSNAPHATCH" => json!(i32::from(st.osnaphatch)),
"HPSPACE" => json!(s.last_used.hatch_spacing),
"HPDOUBLE" => json!(i32::from(s.last_used.hatch_double)),
// AutoCAD's values: positive on, negative off (4 = every annotative object).
"ANNOAUTOSCALE" => json!(if st.annoautoscale { 4 } else { -4 }),
// Paper units per drawing unit of the current annotation scale (1:50 → 0.02).
@@ -328,6 +333,13 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
// The `color` command's input: ByLayer, ByBlock, a name, an index or a true colour.
"CECOLOR" => crate::cmd::set_current_color_value(s, v).ok_or_else(bad)?,
"OSNAPHATCH" => st.osnaphatch = as_bool(v).ok_or_else(bad)?,
"HPSPACE" => {
s.last_used.hatch_spacing = as_f64(v).filter(|f| is_supported_hatch_pattern_scale(*f)).ok_or_else(|| EngineError::BadParams {
cmd: "setvar".into(),
msg: format!("HPSPACE must be greater than {MIN_HATCH_PATTERN_SCALE:e} drawing units"),
})?;
}
"HPDOUBLE" => s.last_used.hatch_double = table::int_value(v).filter(|i| (0..=1).contains(i)).ok_or_else(bad)? == 1,
"ANNOAUTOSCALE" => st.annoautoscale = as_i(v).filter(|i| (-4..=4).contains(i)).ok_or_else(bad)? > 0,
// A scale of the drawing's list; ANNOAUTOSCALE adds it to the annotative objects.
"CANNOSCALE" => crate::cmd::annoscale::set_current(s, v.as_str().ok_or_else(bad)?)?,
+3 -1
View File
@@ -85,6 +85,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
// XCLIP boundaries: 0 hidden, 1 shown and plotted, 2 shown but not plotted.
("XCLIPFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(2)),
// How much objects outside the working set fade while a reference is edited in place (REFEDIT).
("XFADECTL", Kind::Int(0, 90), Def::Int(50)),
];
/// The standard lineweights in hundredths of a millimetre.
@@ -142,7 +144,7 @@ pub(super) fn get(s: &Session, name: &str) -> Option<Value> {
})
}
fn int_value(v: &Value) -> Option<i64> {
pub(super) fn int_value(v: &Value) -> Option<i64> {
match v {
Value::Number(n) => n.as_i64().or_else(|| n.as_f64().filter(|f| f.fract() == 0.0 && f.abs() < 1e15).map(|f| f as i64)),
Value::Bool(b) => Some(i64::from(*b)),
+169 -2
View File
@@ -598,6 +598,15 @@ fn hot_grip_scale_scales_heights_and_thickness() {
let mut s = Session::new();
let r = s.execute("text", &json!({"at": [10, 0], "height": 2.0, "text": "H"})).unwrap();
let h = cadcraft_doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
let h2 = s
.doc_mut()
.unwrap()
.add(
&cadcraft_doc::Space::Model,
cadcraft_doc::Common::default(),
EntityKind::Line(cadcraft_doc::Line { a: cadcraft_geom::Vec3::new(10.0, 0.0, 5.0), b: cadcraft_geom::Vec3::new(15.0, 0.0, 8.0) }),
)
.unwrap();
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
@@ -607,7 +616,7 @@ fn hot_grip_scale_scales_heights_and_thickness() {
}
})
.unwrap();
s.set_selection(vec![h]);
s.set_selection(vec![h, h2]);
s.start_grip_edit(&[(h, 0)]).unwrap();
// STRETCH -> MOVE -> ROTATE -> SCALE
for _ in 0..3 {
@@ -620,7 +629,165 @@ fn hot_grip_scale_scales_heights_and_thickness() {
assert_eq!(e.common.thickness, 6.0);
let EntityKind::Text(t) = &e.kind else { panic!("expected text") };
assert_eq!(t.height, 4.0);
assert_eq!(t.insert.z, 10.0);
// Selected grip is the SCALE base point and must remain stationary in all three coordinates.
assert!((t.insert.x - 10.0).abs() < 1e-9);
assert!(t.insert.y.abs() < 1e-9);
assert!((t.insert.z - 5.0).abs() < 1e-9);
let EntityKind::Line(l) = &s.doc().unwrap().entity(h2).unwrap().kind else { panic!("expected line") };
assert!((l.a.x - 10.0).abs() < 1e-9 && l.a.y.abs() < 1e-9 && (l.a.z - 5.0).abs() < 1e-9);
assert!((l.b.x - 20.0).abs() < 1e-9 && l.b.y.abs() < 1e-9 && (l.b.z - 11.0).abs() < 1e-9);
// JSON `grip.scale` using `index` also keeps the selected grip stationary in 3D.
s.execute("grip.scale", &json!({"handles": [h.hex()], "index": 0, "factor": 0.5})).unwrap();
let e = s.doc().unwrap().entity(h).unwrap();
assert_eq!(e.common.thickness, 3.0);
let EntityKind::Text(t) = &e.kind else { panic!("expected text") };
assert_eq!(t.height, 2.0);
assert!((t.insert.x - 10.0).abs() < 1e-9 && t.insert.y.abs() < 1e-9 && (t.insert.z - 5.0).abs() < 1e-9);
}
#[test]
fn scale_reference_preview_and_drag() {
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
// Plain SCALE preview and drag.
for t in ["scale", "all", "", "0,0"] {
s.cmdline(t).unwrap();
}
assert_eq!(s.preview(Vec2::new(2.0, 0.0)).len(), 2);
let (d, extra) = s.drag(Vec2::new(2.0, 0.0)).unwrap();
assert!(d.matrix.apply(Vec2::new(10.0, 0.0)).near(Vec2::new(20.0, 0.0), 1e-9));
assert_eq!(extra.len(), 1);
// Enter accepts default reference length 1.0, then drag/preview at new length, then Points option.
for t in ["r", ""] {
s.cmdline(t).unwrap();
}
assert_eq!(s.current_prompt().unwrap().message, "Specify new length");
let (d, extra) = s.drag(Vec2::new(3.0, 0.0)).unwrap();
assert!(d.matrix.apply(Vec2::new(10.0, 0.0)).near(Vec2::new(30.0, 0.0), 1e-9));
assert!(matches!(&extra[0].kind, EntityKind::Line(l) if l.a.xy().near(Vec2::ZERO, 1e-9) && l.b.xy().near(Vec2::new(3.0, 0.0), 1e-9)));
assert_eq!(s.preview(Vec2::new(3.0, 0.0)).len(), 2);
s.cmdline("p").unwrap();
assert!(s.drag(Vec2::new(5.0, 0.0)).is_none());
assert!(s.preview(Vec2::new(5.0, 0.0)).is_empty());
s.cmdline("5,5").unwrap();
let (d, extra) = s.drag(Vec2::new(5.0, 7.0)).unwrap();
assert!(d.matrix.apply(Vec2::new(10.0, 0.0)).near(Vec2::new(20.0, 0.0), 1e-9));
assert!(matches!(&extra[0].kind, EntityKind::Line(l) if l.a.xy().near(Vec2::new(5.0, 5.0), 1e-9) && l.b.xy().near(Vec2::new(5.0, 7.0), 1e-9)));
assert_eq!(s.preview(Vec2::new(5.0, 7.0)).len(), 2);
s.cmdline("").unwrap();
assert!(s.running.is_none());
}
#[test]
fn select_then_reference_cancel_and_previews() {
fn line_end(s: &Session) -> Vec2 {
let e = s.doc().unwrap().model.iter().next().unwrap();
let EntityKind::Line(l) = &e.kind else { panic!("expected line") };
l.b.xy()
}
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
// Reference before length is given: no drag/preview; after first point, only rubber-band preview; Enter cancels.
for t in ["scale", "all", "", "0,0", "r"] {
s.cmdline(t).unwrap();
}
assert!(s.drag(Vec2::new(5.0, 0.0)).is_none());
assert!(s.preview(Vec2::new(5.0, 0.0)).is_empty());
s.cmdline("0,0").unwrap();
let pv = s.preview(Vec2::new(5.0, 0.0));
assert_eq!(pv.len(), 1);
assert!(matches!(&pv[0].kind, EntityKind::Line(l) if l.a.xy().near(Vec2::ZERO, 1e-9) && l.b.xy().near(Vec2::new(5.0, 0.0), 1e-9)));
assert!(s.drag(Vec2::new(5.0, 0.0)).is_none());
s.cmdline("").unwrap();
assert!(s.running.is_none());
assert!(line_end(&s).near(Vec2::new(10.0, 0.0), 1e-9));
// COPY and ROTATE previews also emit transformed geometry plus rubber-band.
for cmd in ["copy", "rotate"] {
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
for t in [cmd, "all", "", "0,0"] {
s.cmdline(t).unwrap();
}
assert_eq!(s.preview(Vec2::new(4.0, 3.0)).len(), 2);
s.input(Input::Cancel).unwrap();
}
}
#[test]
fn hot_grip_scale_and_reference_point_picks() {
let mut s = Session::new();
let rl = s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
let l = cadcraft_doc::Handle::parse_hex(rl["handles"][0].as_str().unwrap()).unwrap();
let rt = s.execute("text", &json!({"at": [10, 0], "height": 2.0, "text": "H"})).unwrap();
let t = cadcraft_doc::Handle::parse_hex(rt["handle"].as_str().unwrap()).unwrap();
s.doc_mut().unwrap().modify_entity(t, |e| e.common.thickness = 3.0).unwrap();
// Hot-grip SCALE: coincident point is rejected; valid point scales line, text height, and thickness.
s.set_selection(vec![l, t]);
s.start_grip_edit(&[(l, 0)]).unwrap();
for _ in 0..3 {
s.input(Input::Enter).unwrap();
}
s.cmdline("0,0").unwrap();
assert!(s.running.is_some());
s.cmdline("2,0").unwrap();
assert!(s.running.is_none());
let EntityKind::Line(ln) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!("expected line") };
assert!(ln.b.xy().near(Vec2::new(20.0, 0.0), 1e-9));
let te = s.doc().unwrap().entity(t).unwrap();
assert_eq!(te.common.thickness, 6.0);
let EntityKind::Text(tx) = &te.kind else { panic!("expected text") };
assert_eq!(tx.height, 4.0);
// Hot-grip SCALE Reference: zero new length point is rejected; valid point scales back by 0.5.
s.set_selection(vec![l, t]);
s.start_grip_edit(&[(l, 0)]).unwrap();
for _ in 0..3 {
s.input(Input::Enter).unwrap();
}
for cmd in ["r", "20", "0,0"] {
s.cmdline(cmd).unwrap();
}
assert!(s.running.is_some());
s.cmdline("10,0").unwrap();
assert!(s.running.is_none());
let EntityKind::Line(ln) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!("expected line") };
assert!(ln.b.xy().near(Vec2::new(10.0, 0.0), 1e-9));
let te = s.doc().unwrap().entity(t).unwrap();
assert_eq!(te.common.thickness, 3.0);
let EntityKind::Text(tx) = &te.kind else { panic!("expected text") };
assert_eq!(tx.height, 2.0);
// Hot-grip ROTATE Reference with picked new-angle point.
s.set_selection(vec![l]);
s.start_grip_edit(&[(l, 0)]).unwrap();
for _ in 0..2 {
s.input(Input::Enter).unwrap();
}
for cmd in ["r", "0", "0,10"] {
s.cmdline(cmd).unwrap();
}
assert!(s.running.is_none());
let EntityKind::Line(ln) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!("expected line") };
assert!(ln.b.xy().near(Vec2::new(0.0, 10.0), 1e-9));
// Hot-grip MIRROR with coincident point is rejected; eXit ends cleanly.
s.set_selection(vec![l]);
s.start_grip_edit(&[(l, 0)]).unwrap();
for _ in 0..4 {
s.input(Input::Enter).unwrap();
}
s.cmdline("0,0").unwrap();
assert!(s.running.is_some());
s.cmdline("x").unwrap();
assert!(s.running.is_none());
}
#[test]
+2
View File
@@ -68,6 +68,8 @@ fn corrupt(d: &mut Drawing) -> (Handle, Handle) {
style: "Vanished".into(),
halign: Default::default(),
valign: Default::default(),
backwards: false,
upside_down: false,
}),
);
raw(d, &Space::Model, on("0"), insert("Nowhere"));
+109
View File
@@ -0,0 +1,109 @@
//! #3213, with the real DXF and DWG readers and writers: a drawing read from a 2013 DXF (AC1027)
//! exported or saved as a 2000 DXF or DWG says AC1015, and a plain export keeps the drawing's own
//! version.
//!
//! In its own test binary, not `tests/it`, because it installs the real io hooks. The hooks are
//! process-wide and set once (`set_io` and `set_write_as` keep the first value), so in `tests/it`
//! they would change what the other tests' saves, exports and opens do, by test order. They also
//! cannot share a binary with `save_version.rs`, whose stub writer must be the one installed.
use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, base64_decode, set_io, set_write_as};
use cadcraft_engine::doc::EntityKind;
use serde_json::json;
#[path = "support/temp_dir.rs"]
mod temp_dir;
use temp_dir::TempDir;
fn install() {
set_io(IoHooks {
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: None,
});
set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
});
}
/// The `$ACADVER` an exported DXF declares.
fn acadver(r: &serde_json::Value) -> String {
header_version(&String::from_utf8(base64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap())
}
/// The version a DWG file's bytes open with ("AC1015" for 2000).
fn dwg_version(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes.get(..6).unwrap_or_default()).into_owned()
}
/// The radii of the circles in the active drawing.
fn radii(s: &Session) -> Vec<f64> {
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Circle(c) = &e.kind { Some(c.radius) } else { None }).collect()
}
/// The `$ACADVER` in the header of the DXF text `text`.
fn header_version(text: &str) -> String {
let mut lines = text.lines().map(str::trim);
while let Some(l) = lines.next() {
if l == "$ACADVER" {
lines.next();
return lines.next().unwrap_or_default().to_string();
}
}
String::new()
}
#[test]
fn a_2013_drawing_exports_as_a_2000_dxf() {
install();
// Removed when the test ends, even when an assertion fails.
let dir = TempDir::new("export-version");
let file = dir.path_str("plan.dxf");
let mut s = Session::new();
s.cmdline("circle 0,0 5").unwrap();
s.execute("saveas", &json!({ "path": file, "version": "2013" })).unwrap();
s.execute("open", &json!({ "path": file })).unwrap();
assert_eq!(acadver(&s.execute("export", &json!({ "format": "dxf" })).unwrap()), "AC1027");
assert_eq!(acadver(&s.execute("export", &json!({ "format": "dxf", "version": "2000" })).unwrap()), "AC1015");
}
#[test]
fn a_2013_drawing_saved_as_2000_says_ac1015() {
install();
let dir = TempDir::new("saveas-version");
let (file, copy) = (dir.path_str("plan.dxf"), dir.path_str("plan-2000.dxf"));
let mut s = Session::new();
s.cmdline("circle 0,0 5").unwrap();
s.execute("saveas", &json!({ "path": file, "version": "2013" })).unwrap();
s.execute("open", &json!({ "path": file })).unwrap();
s.execute("saveas", &json!({ "path": copy, "version": "2000" })).unwrap();
assert_eq!(header_version(&std::fs::read_to_string(&copy).unwrap()), "AC1015");
}
/// The DWG writer itself writes the chosen version: the file opens with AC1015, not the 2013
/// drawing's AC1027, and reads back with its circle.
#[test]
fn a_2013_drawing_exports_and_saves_as_a_2000_dwg() {
install();
// The drawing is the test's own, so the DWG conversion may run in this process.
cadcraft_io::dwg_worker::allow_in_process();
let dir = TempDir::new("dwg-version");
let (file, copy) = (dir.path_str("plan.dxf"), dir.path_str("plan-2000.dwg"));
let mut s = Session::new();
s.cmdline("circle 0,0 5").unwrap();
s.execute("saveas", &json!({ "path": file, "version": "2013" })).unwrap();
s.execute("open", &json!({ "path": file })).unwrap();
let exported = |s: &mut Session, p: serde_json::Value| base64_decode(s.execute("export", &p).unwrap()["data"].as_str().unwrap()).unwrap();
assert_eq!(dwg_version(&exported(&mut s, json!({ "format": "dwg" }))), "AC1027");
assert_eq!(dwg_version(&exported(&mut s, json!({ "format": "dwg", "version": "2000" }))), "AC1015");
s.execute("saveas", &json!({ "path": copy, "version": "2000" })).unwrap();
assert_eq!(dwg_version(&std::fs::read(&copy).unwrap()), "AC1015");
s.execute("open", &json!({ "path": copy })).unwrap();
assert_eq!(radii(&s), [5.0]);
}
+23
View File
@@ -150,6 +150,29 @@ fn a_drawing_file_becomes_a_block_with_its_insbase_and_tables() {
assert_eq!(inserts(&s).len(), n);
}
#[test]
fn expert_two_or_more_redefines_a_file_block_without_asking() {
// #2995: with EXPERT 2 or more the "already exists. Redefine it?" question is not asked; it
// is answered Yes, so the next INSERT of the same file finishes and the block is redefined
// from the file as it is now.
hooks();
let dir = TempDir::new("insert-file-expert");
let bolt = dir.file("bolt.dxf", "10,10");
let mut s = Session::new();
s.script(&format!("-INSERT {bolt} 0,0 1 1 0\n")).unwrap();
s.execute("setvar", &json!({ "name": "EXPERT", "value": 2 })).unwrap();
dir.file("bolt.dxf", "0,0");
s.script(&format!("-INSERT {bolt} 20,0 1 1 0\n")).unwrap();
assert!(s.running.is_none(), "INSERT finished: {}", s.prompt_text());
assert_eq!(inserts(&s).len(), 2);
assert_eq!(s.doc().unwrap().block("bolt").unwrap().base, Vec3::ZERO, "redefined from the file");
// EXPERT 1 still asks.
s.execute("setvar", &json!({ "name": "EXPERT", "value": 1 })).unwrap();
s.cmdline(&format!("-INSERT {bolt}")).unwrap();
assert!(s.prompt_text().contains("Redefine"), "{}", s.prompt_text());
}
#[test]
fn exploded_json_insert_is_one_undo_step() {
for params in [json!({ "name": "*B", "at": [5, 5] }), json!({ "name": "B", "at": [5, 5], "explode": true })] {
+2
View File
@@ -41,6 +41,8 @@ fn read(bytes: &[u8], _name: &str) -> Result<Drawing, String> {
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
backwards: false,
upside_down: false,
};
let def = Attrib {
tag: "NUMBER".into(),
+76
View File
@@ -118,6 +118,80 @@ fn attribute_tags_match_in_any_case_and_unknown_tags_are_reported() {
assert_eq!(r, json!({"changed": 1}));
}
#[test]
fn attedit_takes_a_selected_block_reference_at_once() {
let mut s = with_block();
let h = handle(&insert(&mut s, 100.0, json!({})));
s.set_selection(vec![h]);
s.cmdline("attedit").unwrap();
assert!(s.prompt_text().contains("Enter value for T <one>"), "{}", s.prompt_text());
type_lines(&mut s, &["picked", ""]);
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!((value(&s, h, "T"), value(&s, h, "U")), ("picked".into(), "u".into()));
}
#[test]
fn attedit_leaves_constant_attributes_and_locked_references_alone() {
let mut s = with_block();
let h = handle(&insert(&mut s, 100.0, json!({})));
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let EntityKind::Insert(i) = &mut e.kind {
i.attribs[1].constant = true;
}
})
.unwrap();
let rows = cadcraft_engine::attributes(s.doc().unwrap(), h);
assert_eq!(rows.iter().map(|r| (r.tag.as_str(), r.editable)).collect::<Vec<_>>(), [("T", true), ("U", false)]);
let r = s.execute("attedit", &json!({"handle": h.hex(), "values": {"T": "t2", "U": "u2"}})).unwrap();
assert_eq!((r["changed"].clone(), r["constantTags"].clone()), (json!(1), json!(["U"])));
assert_eq!((value(&s, h, "T"), value(&s, h, "U")), ("t2".into(), "u".into()));
// One undo step.
s.undo().unwrap();
assert_eq!(value(&s, h, "T"), "one");
// Not a block reference, a value too long, a locked layer.
let line = s.execute("line", &json!({"points": [[0, 50], [10, 50]]})).unwrap()["handles"][0].clone();
assert!(s.execute("attedit", &json!({"handle": line, "values": {"T": "x"}})).is_err());
assert!(s.execute("attedit", &json!({"handle": h.hex(), "values": {"T": "x".repeat(70_000)}})).is_err());
s.execute("layer.set", &json!({"name": "0", "locked": true})).unwrap();
let e = s.execute("attedit", &json!({"handle": h.hex(), "values": {"T": "x"}})).unwrap_err().to_string();
assert!(e.contains("locked"), "{e}");
assert_eq!(value(&s, h, "T"), "one");
}
#[test]
fn attedit_at_changes_one_of_two_attributes_sharing_a_tag() {
let mut s = with_block();
let h = handle(&insert(&mut s, 100.0, json!({})));
// As a DXF reference may carry them: the second attribute's tag is T too.
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let EntityKind::Insert(i) = &mut e.kind {
i.attribs[1].tag = "T".into();
}
})
.unwrap();
let values = |s: &Session| -> Vec<String> {
let EntityKind::Insert(i) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") };
i.attribs.iter().map(|a| a.text.value.clone()).collect()
};
let r = s.execute("attedit", &json!({"handle": h.hex(), "at": {"1": "second"}})).unwrap();
assert_eq!(r, json!({"changed": 1}));
assert_eq!(values(&s), ["one", "second"]);
// By tag, every attribute with it, as before.
s.execute("attedit", &json!({"handle": h.hex(), "values": {"t": "both"}})).unwrap();
assert_eq!(values(&s), ["both", "both"]);
// Hostile places are refused and change nothing.
for at in [json!({"2": "x"}), json!({"-1": "x"}), json!({"one": "x"}), json!({"0": [1]}), json!([1]), json!({"18446744073709551616": "x"})] {
assert!(s.execute("attedit", &json!({"handle": h.hex(), "at": at})).is_err(), "{at}");
}
assert_eq!(values(&s), ["both", "both"]);
}
/// -ATTEDIT Position moves an aligned or fit attribute without losing its baseline: both of its
/// points move by the same offset (setting both to the picked point would leave no direction or
/// length to fit the text between).
@@ -230,6 +304,7 @@ fn dash_attedit_edits_a_multiline_attributes_text() {
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
};
set_t(&mut s, h, |a| a.multiline = Some(MultilineAttrib { mtext: mtext.clone(), read_as: "abc".into() }));
let before = attrib_t(&s, h).text.insert;
@@ -263,6 +338,7 @@ fn dash_attedit_defaults_of_a_multiline_attribute_come_from_its_multiline_text()
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
};
set_t(&mut s, h, |a| {
a.text.height = 1.25;

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