Compare commits

...
Author SHA1 Message Date
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
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
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
Tanish Manku 39ae41b5ea Merge fix: one destructuring for the viewport chunks 2026-11-30 12:31:45 -07:00
Tanish Manku e056946bdb Merge pull request #3472 from storytold/land/3288
Land #3288: SCALE Reference takes Points and Copy; grip Scale scales text height and thickness
2026-11-30 12:31:06 -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 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
Tanish Manku d52b505afc Merge branch 'main' into land/3288 2026-11-30 12:16:38 -07:00
HagaiBA c1652286b5 fix(mtext): floor AtLeast paragraph line spacing at entity text height 2026-11-30 17:26:30 +02: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 <[email protected]>
2026-11-30 19:39:28 +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 <[email protected]>
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
HagaiBA 53a0b41c53 fix(mtext): preserve paragraph spacing resets across Formatted::to_contents 2026-11-30 09:54:57 +02: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 <[email protected]>
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
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 <[email protected]>
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
FredApps 1bdf4273f8 cadcraft-cli: --version and -V on every subcommand (RFC-0018 rule 1.1) (#3577) 2026-11-30 05:11:27 +01:00
FredAppsandFredApps c1af8dcf83 i18n: load the shared Construction Geometry label (#3414)
* Load Construction Geometry from the shared Chinese catalog

* Format the shared Chinese catalog validation

---------

Co-authored-by: FredApps <[email protected]>
2026-11-30 05:10:56 +01: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
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
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 <[email protected]>
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
mattlafyandClaude Opus 5.5 4568970e50 Offset: OFFSETGAPTYPE extends, fillets or chamfers polyline corner gaps (#1506)
* feat(offset): OFFSETGAPTYPE extends, fillets or chamfers polyline corner gaps

OFFSETGAPTYPE is a system variable (0, 1 or 2, default 0) kept in the
drawing header. Offsetting a polyline fills the gap at the outside of a
corner between two line segments: 0 extends both copies to meet, 1 inserts
an arc of radius equal to the offset distance centred on the original
vertex, 2 inserts a chamfer line at the offset distance from the vertex.
Inside corners and joints with an arc keep the extended join. OFFSET's
settings echo shows the current value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* OFFSETGAPTYPE fills only corners the source polyline has; geometry parity headline and history match

* test(offset): OFFSETGAPTYPE fillets and chamfers open outside corners turning either way

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(offset): interactive OFFSET previews and makes the OFFSETGAPTYPE fill

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Remove a leftover merge file

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* OFFSETGAPTYPE: leave docs/geometry-parity.md to the maintainers

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 03:44:41 +01:00
aldozarandClaude Opus 5.5 7f212ef9c7 Dimension text below the line (\X) and leader text at DIMSCALE (#1055, #1056) (#1084)
* Dimension text below the line (\X) and leader text at DIMSCALE (#1055, #1056)

- #1055: in dimension text, `\X` starts the text below the dimension
  line (DXF Reference). CADCraft drew only the part before it, and its
  *D block held only that part. The part after `\X` is now drawn below
  the line, on the other side of it at the same distance (text centred
  on the line moves above it), on screen, in plots and in the *D block
  as a second MTEXT; text width for the fit is the wider part's.
- #1056: LEADER's annotation was DIMTXT high whatever DIMSCALE said
  (0.25 instead of 6.25 beside dimensions at DIMSCALE 25). It is now
  DIMTXT × DIMSCALE (the style's, else the drawing's; 1 for annotative
  styles), in the style's text style, as AutoCAD's LEADER makes it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dimension `\X`: measure from the dimension line, not DIMTMOVE 1's leader

The part after `\X` is placed from the dimension line's longest segment, and DIMTMOVE 1's leader
(added by #2015) is drawn as a dimension line too: with the text moved far away, the leader won
and the part below went next to the text. The leader's ends are now kept (`text_leader`) and its
segments skipped. Text moved off its place also leaves the part below at the usual clearance
under the line, instead of as far below as the text is above.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* LEADER text of an annotative dimension style: DIMSCALE, and annotative

With an annotative dimension style the leader's text left DIMSCALE out and was not annotative,
so at an annotation scale it stayed small beside the dimensions. It now takes DIMTXT × DIMSCALE
as a dimension of the style does, and is annotative at the current annotation scale.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* LEADER text of an annotative style: the annotation scale replaces DIMSCALE

An annotative dimension takes the annotation scale in DIMSCALE's place (anno_scaled sets its
scale override), so its text is DIMTXT × the annotation scale. The annotative leader text took
DIMTXT × DIMSCALE and then the annotation scale again: twice the dimension text with DIMSCALE 2.
It is now DIMTXT high and annotative; a non-annotative style still takes DIMTXT × DIMSCALE.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DIMTMOVE 1 leader is kept as the text leader again

The merge of main moved the leader into dim/linear.rs without the text_leader record, so the
text below the line was placed over the leader.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Keep `\X` text below a suppressed or extension-line dimension line

With DIMSD1 and DIMSD2 both on, no dimension line segment is drawn, so
the part after `\X` was dropped. The linear dimension now records its
whole dimension line (`dim_axis`) and the `\X` layout falls back to it.

With DIMJUST 3 or 4 the text runs along an extension line, so its normal
is across the dimension line's: the text no longer moves onto the
dimension line at the arrow, and the part below stacks under it in the
text's own frame.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 03:44:21 +01:00
aldozarandClaude Opus 5.5 9907d9272b FILLET/CHAMFER with polylines: picked side, two polylines, middle segments, closed polylines, arc segments (#1223)
* FILLET/CHAMFER with polylines keep the picked side and join two polylines

A line crossing an open polyline's end segment cut the polyline on the
wrong side when the pick was past the crossing: the polyline always kept
the part towards its other end. Each object now keeps the side it was
picked on and drops what lies past the corner, as AutoCAD does.

Two open polylines picked at their end segments were refused. They now
join into one polyline through the corner (the first one picked keeps
its handle and direction), as AutoCAD does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* FILLET/CHAMFER: a line or polyline joins any straight segment of an open polyline

AutoCAD accepts a middle segment too: an open polyline's end segment
crossing another's middle segment joins them, each keeping its picked
side and dropping what lies past the crossing. Closed polylines and arc
segments are still refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* FILLET with polylines: a closed polyline opens to join a line; an arc segment is cut where a line crosses it

Checked against AutoCAD with the same shapes:

- A closed polyline filleted with a line opens at its first vertex: the
  picked side of the picked segment joins the line, either side, and the
  result is an open polyline. CADCraft refused closed polylines.
- An arc segment crossed by a line (radius 0) is cut where they cross,
  keeping its picked side, with the bulge of what is left of it. A line
  that misses the arc, or a radius, stays refused, as in AutoCAD.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* FILLET: a pick just before a polyline arc's start keeps the start side

Where the pick lies along an arc segment was clamped to the arc's end, so a pick a little before
its start (within the pick box) kept the end side. It now counts at the nearer end.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 03:43:37 +01:00
aldozarandClaude Opus 5.5 98e5c2b08f Drawing locks and WHOHAS: say when a drawing is open elsewhere (part of #540) (#1018)
* Drawing locks and WHOHAS: say when a drawing is open elsewhere (part of #540)

While a drawing opened from a DWG/DXF/DWT file is open, the app keeps
`.<file name>.cadcraft-lock` beside it (user, computer, app instance,
when opened), touched every minute; a lock not touched for five minutes
is stale. Opening a drawing someone else has open says who and since
when, on the command line and in the status bar, and opens it anyway:
the lock only informs. A lock is released when its drawing closes or is
saved under another name and when the app exits, only ever by the
instance that holds it; a stale one is taken over, and an app that finds
its lock taken over notes it instead of touching it. WHOHAS reports the
holder of the current drawing or of a file. The locks run with the
autosave tick; the format is CADCraft's own, not AutoCAD's .dwl.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Drawing lock: claim a free lock atomically

Two apps opening a drawing with no lock at the same moment could both write it and both think
they held it, so neither told its user until a later heartbeat. A missing lock is now created
atomically (a hard link of the staged file, or create_new without hard links), and a stale one
is replaced only if no other app has taken it meanwhile, then read back. The app that loses is
told at once who has the drawing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* WHOHAS: a `path` that isn't text is an error

A `path` of another type (`{"path": 7}`) was taken as left out, so WHOHAS answered for the
current drawing. Left out or null still means the current drawing; anything but a string is now
refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Drawing locks: name the imports of the native module

The workspace now denies clippy's wildcard_imports, which `use super::*`
in drawlock's native module trips after the merge of main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Autosave: wake up for the drawing-lock heartbeat, not only for autosaves

Autosaver::tick kept the drawing locks but returned only the next autosave,
None with every drawing saved or SAVETIME 0, and the UI only schedules a
repaint on Some. An idle app then never touched its locks: after STALE_SECS
another app took the drawing over without a word. Locks::next_beat gives
the shortest wait until a held lock (or someone else's) is due again, and
tick returns the sooner of that and the next autosave.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* WHOHAS: an error on the web, not "nobody has it open"

The web has no lock files, so the lookup isn't done there; reporting no
holder presented that as a negative result.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Fix the wasm build after the merge

The merge dropped the native-only cfg from main's autosave lock field, and
two drawlock items used only by native code warned on wasm.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 03:41:02 +01:00
midasdfandmidasdf 758dc4e805 Plot: JIS B4/B5/B6 and Japanese paper sizes (はがき・封筒・四六判) (#1810)
* Plot: JIS B4/B5/B6 and Japanese paper sizes

Japanese drafting uses the JIS B series: B4 257×364 mm, B5 182×257 mm and
B6 128×182 mm. The paper table only had the ISO sizes, so a JIS B5 drawing
plotted about 7 mm short in each direction. B4/B5/B6 are now the JIS sizes (the
names Japanese Excel and drawings use) and the ISO ones stay reachable as
`B4 (ISO)`/`B5 (ISO)`; a drawing that stored the ISO sheet keeps its stored
size, and a caller that means ISO B5 says so.

Adds the Japanese papers the table lacked: Japanese Postcard (はがき,
100×148 mm), Japanese Double Postcard (往復はがき, 148×200 mm), Japanese
Envelope #3 (長形3号, 120×235 mm), Japanese Envelope Kaku #2 (角形2号,
240×332 mm) and 四六判 (127×188 mm). A6 was already an ISO sheet.

Paper names resolve case-insensitively and ignore spaces, hyphens, underscores
and parentheses (`B5 (JIS)`, `b5-jis`, `b5jis`), with the Japanese spellings as
aliases too (`はがき`, `往復はがき`, `長形3号`, `角形2号`, `四六判`). The
built-in plotters and the Page Setup/Plot paper combo pick the new sizes up
from PAPER_SIZES, and the PDF plot's MediaBox and the plot preview use them.

Tests: the render paper test pins every new size and alias, the ISO sizes keep
their values and the unknown-name fallback is unchanged; a new io test pins the
PDF MediaBox for each new paper (JIS B5 515.91×728.50 pt, はがき 283.46×419.53 pt,
ISO B4/B5 and the rest), and the plot-preview test checks that `B5` resolves to
JIS B5 and `B5 (ISO)` to ISO B5.

Docs: docs/plotters.md standard sizes and the `pagesetup`/PDFBOOK parameter
notes, and ROADMAP.md progress log + revision history, dated 2026-10-21.

* Plot: B4/B5/B6 stay ISO; JIS sizes by explicit name

Review follow-up: making the bare names mean JIS changed the ISO sizes for
every user. `B4`/`B5` are the ISO sizes again, an ISO B6 row (125×176 mm)
completes the bare series, and the JIS sheets (JIS P 0138, 257×364,
182×257 and 128×182 mm) are reachable only as `B4 (JIS)`/`JIS B4`,
`B5 (JIS)`/`JIS B5` and `B6 (JIS)`/`JIS B6`.

Drop the ambiguous bare `Postcard` and `Double Postcard` aliases; the name
and はがき/往復はがき say which postcard is meant. Drop the ROADMAP.md edit
(ROADMAP.md stays at origin/main's content).

The render and io paper tests, the plot-preview test and docs/plotters.md
follow the new mapping; the Japanese stationery sizes and their はがき/
往復はがき/長形3号/角形2号/四六判 spellings are unchanged.

Still safe for stored papers: a page setup keeps the canonical paper name
with its width/height, DXF groups 44/45 round-trip those sizes, and the ISO
canonical names (and the JIS rows by name) did not change.

* Plot: full-width paper names resolve like their ASCII forms

A Japanese keyboard or IME gives B5 (JIS); fold U+FF01..U+FF5E to ASCII (and the
ideographic space to a space) before the existing normalisation, with a test.

---------

Co-authored-by: midasdf <[email protected]>
2026-11-30 03:40:20 +01:00
HagaiBA bfd659e984 MTEXT: honor paragraph line spacing codes (\pxsm, \pxse, \pxsd) (#3638) 2026-11-29 23:50:45 +02:00
Dylan M. Taylor cb12bc7984 ci(nightly): enable automated 00:30 UTC schedule and Stage 2 signer dispatch (#3616) 2026-11-29 16:16:22 -05: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
Dylan M. Taylor c1669adaed ci(sonarcloud): give each main commit its own concurrency group (#3655) 2026-11-29 15:54:17 -05:00
Dylan M. Taylor b7079ece62 test(nightly): preserve saved state and refuse invalid profile startup (#3653) 2026-11-29 15:22:26 -05:00
Dylan M. Taylor 5a06e105d6 feat(nightly): adopt craft-nightly for direct-launch self-isolation (#3644)
* feat(nightly): wire craft-nightly for direct-launch self-isolation

* fix(nightly): bump craft-nightly for single-instance sockets and add Windows regression test
2026-11-29 14:40:43 -05: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 <[email protected]>
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 <[email protected]>
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
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
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 <[email protected]>
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 <[email protected]>
2026-11-29 17:44:20 +07: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 <[email protected]>
2026-11-29 14:29:46 +07: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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
2026-11-29 11:05:38 +07:00
Dylan M. Taylor 32ad922df5 fix(nightly): enable Linux package_formats (including Flatpak) in signing policy (#3623) 2026-11-28 22:40:35 -05: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 <[email protected]>
2026-11-29 09:11:49 +07:00
Dylan M. Taylor 4118ce9a8f ci: pin storytold/craft-common-actions to @main universally (#3619) 2026-11-28 16:05:28 -05:00
Dylan M. Taylor 66931918cb ci(nightly): enable all signed Linux package formats (deb, rpm, appimage, flatpak, oci, arch) (#3618) 2026-11-28 15:25:02 -05: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
95af8ba086 Add Russian translation (ru) (#3378)
* Add Russian translation (ru).

Update the in-app Russian catalog and add Russian strings to the
Linux desktop, AppStream, and MIME metadata.

Copyright (c) 2026 SuperSfera LLC, MIT OR Apache-2.0.

* ru: address review (metainfo license notice)

* i18n(ru): apply review suggestions from #2296

* i18n(ru): keep a single copy of the translation notice

The desktop entry, MIME file and Russian catalog repeated the same copyright line. The notice text itself is unchanged.

Co-authored-by: sesaposa1 <[email protected]>

* i18n(ru): translate Generate Boundary

The hatch command label was the one English command name still absent from the catalog. It follows the catalog's own Boundary / Create wording.

Co-authored-by: sesaposa1 <[email protected]>

* ru: state CC0-1.0 for Russian metainfo strings

* ru: remove the per-file translation notices

The translation is under the repository's licence, and authorship is in git history.

* i18n(ru): 15 strings added on main since the last catch-up

Array dialog fields and the update and right-click option hints.
Docs counts updated to 2,274 rows.

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: sesaposa1 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 21:00:12 +01:00
fcaf13da40 i18n(cs): bring the Czech catalog up to date (#1579)
* i18n(cs): translate the 115 strings added since the Czech catalog

Adds Czech rows for every key of the Ukrainian reference catalog that the
code looks up and cs.tsv was missing: the 3D mouse window and its status
messages, the Hatch and Gradient dialog, the Block Editor and dynamic block
commands, multileader editing, Options (selection, grips, selection preview
and automatic save), the MTEXT editor toolbar, palette tool sets and recent
files. 1,214 -> 1,329 rows; the i18n tests now report no Czech gaps.

"SVG drawings (SVG, SVGZ)" is left out: no production code looks it up.

Rows are inserted in the reference catalog's order; existing rows are
unchanged. Translations are original, written from the meaning of the
English strings (AI-assisted, not yet proofread by a native speaker).
docs/localization.md and docs/localization-parity.md updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n(cs): review fixes for the new Czech rows

Independent review of the 115 rows added in the previous change:

- Hatch Pick: "Výběr pro šrafy", matching the existing helper command
  QuickCalc Pick ("Výběr pro rychlou kalkulačku").
- 3D Mouse Navigation: noun form "Ovládání pohledu 3D myší", as in the
  English label and the Enable 3D mouse navigation checkbox (the command
  applies one navigation frame).
- Automatic save hint: "Výkresy, které ještě nemají soubor, ..." reads
  more naturally than "Výkresy bez souboru".
- 3D mouse busy: "obsazena", the same short form as "připojena" and
  "odpojena" in the sibling status messages.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: note the intermediate Czech baseline in the parity history

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n(cs): translate the 33 strings added on main since

Rows for UI that landed on main after this branch started, so the
Czech catalog again covers every key of the Ukrainian reference catalog
the code looks up (no gaps reported):

- Command Aliases dialog (ALIASEDIT) and Tools > Customize.
- Express Tools commands: BREAKLINE, TXT2MTXT, BURST, MOCORO.
- Options: two-click selection window, interface scale.
- HATCHEDIT: removing boundaries, the Island boundary label.
- Properties: a dimension's arrow size, overall scale and precision.
- Three command prompts (DATAEXTRACTION, TOLERANCE, APPLOAD).

Not added: the Plot dialog labels in managers.rs, which the code does
not look up yet, and the unused SVG filter label.

1,330 -> 1,363 rows; counts updated in localization.md and
localization-parity.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n(cs): drop the duplicate Normal row after merging main

Main's ATTDISP work (View > Attribute Display > Normal) added the row
`Normal → Normální` to cs.tsv, the same one this branch had added at the
end, so the merge left the key twice and the catalog test failed on
"duplicate key Normal". The branch's copy goes; main's stays.

Czech has 1,373 rows (main has 1,219); the counts in the docs follow.
`cargo test -p cadcraft-ui-egui` passes (307) and `translation_gaps`
reports nothing missing for cs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n(cs): put the two backup rows in the reference catalog's order

Backup copy and Create backup copy with each save follow Automatic save
file location, as in uk.tsv; the other five new keys are not in the
reference catalog and stay at the end.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n(cs): the 7 strings translation_gaps lists after merging main

Alias import confirmation, the right-click hint in Options, MINSERT and the Xref clip menu; no reference catalog has the first five yet.

* i18n(cs): the Dimension Style Manager and dimension properties

184 rows for the strings #1460 added (Dimension Style Manager, dimension
and text properties, unit formats, arrowheads), 1,653 rows in all.
translation_gaps: cs nothing missing. Docs counts and history updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n(cs): 19 strings added on main since the last catch-up

Array dialog fields, the update and right-click option hints,
the unsaved-changes prompt, and Unnamed.

---------

Co-authored-by: Losminek <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 20:34:58 +01: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 <[email protected]>
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
348ab510b4 feat(area): add translucent fill to AREA measurement preview (#1303)
* feat(area): expose active interactive command to canvas

* feat(area): shade temporary AREA preview and add tests

* fix(area): skip ambiguous self-intersecting preview fills

Reject overlapping or touching nonadjacent polygon edges before triangulation, preserving the AREA measurement and outline. Add bowtie and degenerate-boundary regression coverage with documented behavior.

* fix(area): preserve fill when cursor repeats last selected point

Strip only the redundant cursor vertex from the temporary AREA preview before polygon validation; keep genuine duplicate selected points invalid. Add two regression tests for stationary cursor and duplicate selected clicks.

* fix(area): keep preview fill when cursor revisits any selected point

Drop only the final temporary cursor vertex when it duplicates a selected vertex. Preserve rejection of actual duplicate selections and add closure/interior-cursor regression tests.

* perf(area): cache selected-edge validation while keeping cursor checks live

* perf(area): keep preview validation cache in canvas state

* style(area): clean preview formatting and let-else layout after review

* style(area): apply rustfmt per maintainer review

---------

Co-authored-by: mrepzzz <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 18:16:01 +01: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
81ec2264d3 HATCH by internal point keeps the arcs of its boundary (#1167) (#1474)
* HATCH by internal point keeps the arcs of its boundary (#1167)

The boundary search works on flattened curves, so a hatch made by
picking inside a circle stored 158 chords and AREA came out short
(5025.22 for pi*40^2 = 5026.55).

Each traced edge now keeps the input polyline it came from
(region::Boundary::outer_edges, Island::edges, outline_edges,
enclosing_loop_edges_gap; bridged gaps are None), and each input
polyline is one piece of one object: a line, a circle, an arc or one
segment of a polyline. arcs::with_arcs turns each run of edges on the
same circular piece back into one bulged vertex and moves the corners
onto the exact curves (line-circle or circle-circle crossing nearest the
traced corner, within the reach a shallow crossing needs, else onto the
circle). Nothing is matched by proximity, so a line or an ellipse next
to a circle is never taken for it. The associative refill does the same,
so a hatch keeps its arcs when its objects move.

dedup_loops now merges only loops with the same role: a loop that is one
pick's outer loop and another's island stays twice, as the even-odd fill
needs (one hatch picked inside a circle and around it, or inside a square
within a square, left the inner shape empty once the two loops matched).
A boundary object selected twice is used once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Hatch arcs: origin from the arcs' extents; opposite-role duplicate loops cancel

- HPORIGINMODE's corners came from the loop vertices only, so a circle kept as two half-circles
  had no height and its corner origins fell on its centre line. The extents now include each
  bulged edge's arc.
- A pick inside a circle and one around it keep the circle as an outer loop and as an island.
  The renderer collapsed the two into one loop, so the circle drew empty, and AREA measured them
  by nesting. Two loops that are the same boundary now collapse only in the same role (a repeated
  loop); in opposite roles they cancel, as they do under the odd-parity fill. AREA measures the
  loops the fill keeps (`hatch_fill_loop_indices`), exactly with their arcs.
- Tests: the circle's corner origins, BOUNDARY keeping a circle's and a rounded rectangle's
  arcs, and the drawn fill and AREA of the circle inside a square.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Hatch loops: same-role repeats collapse before opposite roles cancel; HATCHEDIT keeps islands

- The renderer cancelled an outer loop and an island as it met them, so the same loops in another
  order filled differently (outer, island, outer left a hole; outer, outer, island left none).
  Repeats within a role now collapse first, then an outer loop and an island that are the same
  boundary cancel, spending the same comparison budget.
- HATCHEDIT adding a boundary the hatch already has (its island) added a second copy, which then
  cancelled the island. A boundary already there is no longer added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* HATCHEDIT: a boundary already there takes the added objects' links

Adding a boundary the hatch already has dropped the added loop, and with it the objects it came
from, so an unlinked island picked with addBoundary stayed unlinked. The objects now join the
loop already there (no second copy is added).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* AREA of a hatch tests nesting at an edge's middle, as the fill does

AREA tested whether a loop is an island at its first vertex, which can lie on the loop around it
(an island touching the outer boundary): the island was then added instead of subtracted. It now
uses the fill's own test point, the middle of the first non-degenerate edge (`hatch_loop_probe`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Hatch loop dedup: look only at loops that could match, stop when the budget is spent

The comparison budget bounded `same_polygon`, but both passes still walked every kept loop for
each new one, O(n²) in the number of loops however few matched. Loops are now found by (role,
vertex count), so only possible matches are looked at, and once the budget is spent no more are.
A test sorts 40,000 distinct loops.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: hatch gap tolerance (HPGAPTOL) is done, not missing

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: BOUNDARY keeps the arcs of what it traces

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 17:58:38 +01:00
c370b1beb4 RENAME keeps a layer's, block's or style's xdata, extension dictionary and reactors (#1020)
* RENAME keeps a layer's, block's or style's xdata, extension dictionary and reactors

The data CADCraft keeps for a table record or block without modelling it
(Drawing.foreign.records, and the roles of its file handles in foreign.targets)
is keyed by kind and upper-case name, so a rename left it under the old name:
a renamed dynamic block lost its dynamic data, and a renamed layer, text style,
dimstyle, linetype, view, UCS, multileader style or table style lost its other
applications' xdata, extension dictionary and reactors on the next save.

Foreign::rename re-keys both maps; every rename site (layer.set newName, which
RENAME and the Layer manager use; block; style; dimstyle; linetype; view, UCS,
multileader and table style) calls it through Foreign::rename_shared, which
clones the shared Foreign only when it holds something for that name. Undo needs
nothing: foreign is part of the drawing snapshot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* A case-only rename leaves the shared foreign data uncloned

* A case-only rename test checks the saved layer and block names exactly

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: RENAME keeps the foreign data of layers, blocks, linetypes, text styles and dimension styles

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 17:39:44 +01: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 <[email protected]>
2026-11-28 23:31:28 +07:00
07b4ceb4b5 feat(layout): New Layout from Area to pick the model area a layout shows (#2080)
* feat(layout): pick the model area a new layout shows

Creating a layout from the "+" button or the layout tab menu takes the next
free name, shows the Model tab for two corners picking the model area the new
layout's viewport shows (Enter: the whole drawing; Esc creates nothing and puts
the tab back), then shows the new layout. `layout.new` takes `window` for the
same from JSON.

Interactive::cancelled lets a command put back the view or tab it moved when it
is cancelled (forwarded by the Guarded wrapper). Rebased onto main: the tests
live in cmd/layout/tests.rs, the cancel hook in session/interactive.rs.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* fix(layout): Esc restores the starting tab only if the Model tab is still shown

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* i18n(it): the prompt that asks the model area of a new layout

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* feat(layout): keep "+" and New Layout instant; pick the area with New Layout from Area

"+" and the tab menu's New Layout create the next layout at once, as before, and
LAYOUT.NEW asks only for the name. The model-area pick moves to its own command,
layout.newarea ("New Layout from Area..."), offered in the layout tab menu. Its
code is unchanged; layout.new {window} still covers scripts.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* i18n(zh): the New Layout from Area menu item

main's Chinese test requires a label for every menu item and command.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Classify layout.newarea as a no-files command

every_command_is_classified requires every registered command to be on one of the file-access lists. layout.newarea does not touch a file, so it belongs next to layout.new on NO_FILES.

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 17:26:42 +01:00
3709d68862 Draw %%c with the style font's U+2205 or Ø when it has no U+2300, else the stroke glyph (fixes #1608) (#1816)
* Stroke font: U+2205 is the diameter sign too

Files from other software store the %%c symbol as U+2205 (empty set)
rather than U+2300. The stroke font drew Ø, ø and U+2300 with its
diameter glyph but had nothing for U+2205, so a stroke-font style showed
it as a missing-glyph box, or as an installed font's ∅ when one had it.
Draw it with the same strokes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Draw %%c with the style font's U+2205 or Ø when it has no U+2300, else the stroke glyph (fixes #1608)

%%c becomes U+2300, which most Latin TrueType fonts lack (Arial, Times,
Liberation Sans on Linux). A text style set in one of them drew the
font's missing-glyph box for the diameter sign; only when a wide-coverage
font (DejaVu Sans) happened to be installed did the per-character
fallback show a symbol, in that other font's size and look.

A character the style's face lacks is now first looked for as one of its
substitutes in the same face: U+2300 as U+2205 or Ø, U+2205 as U+2300 or
Ø (`substitutes`, a pure candidate list). All three read as the diameter
sign in drawing text, and every Latin font has Ø, so the symbol keeps the
text's font, size and weight. The existing fallback chain (FONTFALLBACK,
FONTALT, installed fonts) is unchanged and comes next, as for every other
missing character; when no font has the character and the stroke font
does, its glyph is drawn as strokes instead of the face's box. The PDF
glyph record carries the character actually drawn, so the ToUnicode map
stays one-to-one when a text has both %%c and a literal Ø. Lines with
right-to-left text (the shaped path) apply the same substitution before
itemizing.

Tests: the candidate order; the last resort's choice; and, with a real
installed font that lacks U+2300 but has Ø (Liberation Sans, Arial...),
%%c, U+2300 and U+2205 shape, measure and record the same glyph as Ø,
also on a right-to-left line. Skips cleanly without such a font; no font
file is added.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Test the Ø substitution only in a font that also lacks U+2205

The installed-font test picks a face without U+2300 that has Ø, and
expects %%c, U+2300 and U+2205 to shape as its Ø. A face that lacks
U+2300 but has U+2205 satisfied that predicate, yet in it the
substitution rightly chooses U+2205 over Ø, so the comparison with
"Ø50" failed on such a machine. Require the face to lack U+2205 too;
Liberation Sans does, so the test still runs where it ran before and
still skips cleanly when no such font is installed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Shaped lines: draw what no font has with the stroke font too

The left-to-right path draws a character that neither the text's font,
its substitutes nor any installed font has with the stroke font's glyph
when it has one, in place of the face's missing-glyph box. The shaped
path for lines with right-to-left text stopped short: `resolve` went
from the fallback chain straight to the face's box, so %%c on such a
line in a font without a diameter sign, with no installed font to lend
one, still showed a box where a left-to-right line showed the symbol.

Select the stroke glyph before the face's box there as well. The piece
is drawn and measured as the stroke-font pieces of a stroke-font line
already are (the stroke font's advance, no PDF glyph record, since it
is strokes, not an outline), so no other site needs a case. One
difference remains deliberate: a stroke-font line leaves the trailing
gap of its last glyph out of the width, as `shape_stroke` does; a
TrueType line now keeps it, as `ttf::shape` does, so a line measures
the same whichever path lays it out.

Tests: with a face that maps nothing standing in for a font lacking
the character, `resolve` picks the stroke glyph when no installed font
has the character (the fallback font when one does), keeps the face's
missing-glyph shape for what the stroke font lacks too, and the shaped
line draws strokes rather than a box at the stroke font's advance. The
installed-font test's right-to-left part also checks the width and
that the face's Ø, not the stroke font's, is drawn.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Shaped lines: take the bidi runs from the text before substitution

A character the text's font lacks is drawn as one of its substitutes
when the font has that: %%c (U+2300) as Ø in Arial, Liberation Sans and
the like. The shaped path (lines with right-to-left text) substituted
first and then ran the bidi algorithm over the substituted characters.
U+2300 and U+2205 are bidi-neutral, Ø is left-to-right, so on a line
like "⌀50 אב", right-to-left by its first strong character (the Hebrew),
the Ø became the first strong character instead, the paragraph flipped
to left-to-right and the runs changed order: "⌀50" moved from the right
end of the line to the left, where a font with U+2300 never puts it.

Resolve the runs from the characters as decoded and draw the substitute
at the same logical index: substitution is one character for one, so
the runs index both lists alike. Itemizing, shaping, mirroring and the
widths keep using the substituted characters, since those are drawn.

Tests: a TrueType font built in the test (character map and metrics, no
outlines) gives a face whose coverage the test chooses, with or without
U+2300, whatever is installed. "%%u⌀50%%u אב" in both faces underlines
"⌀50" at the same place, the right end, at the same width. The
installed-font test compared the glyphs of "⌀50 א" with "Ø50 א", equal
only while the line flipped; it now checks that the face's Ø is the
rightmost glyph of the former and the leftmost of the latter, at the
same width and glyph count, still without stroke-font glyphs.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Skip empty glyph slots when finding the rightmost glyph in the diameter test

Main now keeps an empty outline slot for a glyph without contours (the
space), so the slot's missing x put it last in the right-to-left check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 17:10:18 +01:00
40d7375f20 Picking reads the index topmost first when the aperture holds more than 1024 candidates (#2701) (#2822)
* Picking reads the index topmost first when the aperture holds more than 1024 candidates (#2701)

When a drawing is shown small, the pick aperture under the cursor covers most of it and the
spatial index returned nearly every entity on each pointer move: the hover highlight collected,
mapped and sorted all of them before testing the topmost. A pick now takes at most 1024
candidates from the tree as before; past that it reads the index chunks from the last one down
(skipping chunks whose bounds miss the query), stops at the first hit, and sorts the tree's
candidates only for the entities below those it examined, after 4096 of them. Picks are
identical (parity tests against the scan at every limit).

select::pick per call, 1396 px canvas, PICKBOX 3 (synthetic 374k-entity site plan / 2M lines):
  zoom 20x        0.006 / 0.005 ms  ->  0.006 / 0.005 ms
  zoom extents    0.014 / 0.112 ms  ->  0.015 / 0.115 ms
  0.005x          17.0  / 148 ms    ->  8.4   / 74 ms
  0.0005x         12.3  / 121 ms    ->  0.017 / 0.019 ms
Hovering over the 2M-line drawing at 0.0005x: 100% of a core at 7.6 frames/s before, 9% after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Picking past 1024 candidates skips the layers frozen in the viewport

The test covers the frozen-layer filter on the topmost-first and below-floor
routes of a pick, which #3124's tests do not reach.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 16:54:04 +01:00
a67a8b5edd engine: check a paper's margins against its own axis (#1266)
* engine: check a paper's margins against its own axis

* doc: turn a paper's margins with the sheet when it is stored portrait

* fmt: keep plotters.rs rustfmt-clean

* engine: turn a device paper's margins to the page's orientation

* engine: turn a page's margins when only its orientation changes

PAGESETUP sets `landscape` before `page_device`, but a command that names no paper copies no
device paper, so the retained margins stayed on the old sheet's axes and Sheet::from_page
refused them on the new orientation, falling back to the whole sheet. Turn them with the page,
using the inverse of the rotation `set_paper` applies.

* engine: an orientation-only pagesetup turns the retained margins the way the page turns

---------

Co-authored-by: midasmatterhorn <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 16:41:14 +01:00
aljormon84andFredApps 9f553d6764 feat(engine,ui): close F1 (-ATTEDIT, -RENAME), F16 (groups), F19 (draworder) and -LAYER stAte (#2152)
* feat(engine): implement -ATTEDIT Position/Height/Angle/Style and -RENAME VPort

* docs(gaps): update F15 reflecting MVIEW Restore landed

* feat(engine): implement -LAYER stAte options (Save/Restore/Name/Delete/?)

* feat(engine,ui): implement GROUPDISPLAYMODE, group copy replication, and all-space TEXTTOFRONT/HATCHTOBACK

---------

Co-authored-by: FredApps <[email protected]>
2026-11-28 16:27:41 +01:00
c5770734e2 DXF read: fewer allocations on the per-group and per-entity paths (#1076) (#1833)
* Key the raw reader's entity map by handle, not hex text

dxf_raw::read built a HashMap<String, bool> from Handle::hex() of every
entity and probed it with the handle text of every entity record: for
the #1076 reference drawing that is 1.1 M String allocations plus
SipHash over text, and the record's handle was parsed, formatted and
parsed again. Keyed by Handle, the map is built from the entities' own
handles and probed with the handle the record's head already yields.
handle() only rejects null and absurd handles, which the lookups' users
skipped a few lines later anyway.

Reading the #1076 reference DXF: 0.34 s less of 5.85 s.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Skip the raw reader's head scan for records without 102 groups

dxf_raw::read ran head() three times per entity (its extras, the
extension-dictionary map and the per-entity handle), and each call
allocates the handle and owner text (parsed, then formatted again) even
when the record has no reactors and no extension dictionary, which is
the case for most entities of a large drawing. Both scans that only
need those two fields now first check whether the record has any 102
group at all; without one there is nothing to find.

Reading the #1076 reference DXF: 0.28 s less.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Unescape DXF text only when it holds a backslash

The ASCII parser allocated every string value twice: once in typed()
and once in unescape_unicode(), which copies its input even when there
is no \U+ or \M+ escape to resolve, after two scans for them. Half the
16.7 M groups of the #1076 reference drawing are strings, so that was
8 M needless allocation pairs. A value without a backslash cannot hold
an escape and now moves into the tag as it is. The end-of-file check
reads the value before it is pushed, as the binary parser already did,
instead of cloning the text of every record's type group.

Reading the #1076 reference DXF: tag parsing 1.22 s to 1.17 s, 0.12 s
less overall.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Size the DXF tag list from the line count

parse_with_limit already counts the file's lines to refuse an oversized
drawing before reading it; that count is the number of groups, so the
tag list is now created at that size instead of growing by doubling.
For the 16.7 M groups of the #1076 reference drawing the doubling moved
about 670 MB of tags in all and, at the last step, held the 335 MB old
list next to the 670 MB new one. The hint is capped by the tag limit
and never trusted beyond it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Size the entity list of a DXF section from its record count

parse_entities grew its list of (owner, paper, Entity) by doubling: for
the 1.1 M entities of the #1076 reference drawing that is a list of
about 700 MB moved at every doubling and, at the last one, held beside
its 350 MB predecessor. The records come from the file but are already
in memory and bounded by the tag limit, so the list is sized to their
count once; nearly every record becomes an entity.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Borrow group text in the DXF reader's per-tag scans

Tag::str() clones the value, and the reader called it in loops that run
over every group of the file or every group of a record: the handle
seed scan over every 5/105 group (1.2 M clones for the #1076 reference
drawing), the CADCRAFT_HANDSEED probe over the OBJECTS section, the
entity plot style lookup, the handle of every entity record, the record
split of every section, the AcDbEntity marker search, the xdata brace
check and the head scan's handle, owner and group names. A private
text() helper in the io crate borrows a string or hex value instead
(the dxf crate's API is left alone), and split() keeps a record's type
as a borrowed &str, as the writer's record list already can.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Bound the tag-list reservation by the text's length

The reservation came from the newline count alone, so a file of blank
lines (`0`, `EOF`, then megabytes of newlines) reserved a tag slot per
two newlines before the parser found its one group: far more than the
grow-as-needed list would ever have taken for that input. A group is two
lines of at least two bytes each, so the text's length over four bounds
what any file of that size can hold; the reservation now stops there.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Size the entity list by the records that can become entities

VERTEX, ATTRIB and SEQEND fold into the POLYLINE or INSERT before them,
so a heavy polyline file reserved a slot per vertex it never filled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Reserve the tag list fallibly, so a refused reservation grows the list instead of aborting

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Bound the entity list's reservation and make it fallible

parse_entities reserved its staging list for every record that can become
an entity, infallibly, before any record was read. The reservation now
stops at MAX_RESERVED_ENTITIES (1 << 16 entries, about 46 MiB; larger
lists grow as usual) and goes through try_reserve_exact, so a refused
reservation is a "DXF: out of memory reserving N entities" error rather
than an abort; parse_entities and read_blocks return a Result for it.
Review by FredApps on PR #1833.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 16:14:57 +01:00
fcf353c74b Keep tiny arc sweeps instead of treating them as full circles (#2559)
Found while testing crates/geom/src/lib.rs:43-46 (ccw_sweep), used by Arc::sweep and angle_in_sweep

Co-authored-by: Claude Haiku 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 15:58:20 +01: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 <[email protected]>
2026-11-28 21:47:41 +07:00
midasmatterhornandFredApps 5cc0a86eac doc: a mirrored dimension reflects its direction about the mirror line (#1263)
* doc: a mirrored dimension reflects its direction about the mirror line

* test(doc): set insertion_point on the mirrored-dimension fixture

main added Dimension::insertion_point in #2636. The test in this PR
constructed a Dimension without that field, so clippy failed after
merging main.

---------

Co-authored-by: FredApps <[email protected]>
2026-11-28 15:39:16 +01:00
f845ed5f72 REVCLOUD: arcs use the bulge readers need to recognise a cloud (follow-up to #1605, #1570) (#1692)
* Write RevcloudProps xdata on revision clouds

Fixes #1570

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* REVCLOUD: arcs use the bulge readers need to recognise a cloud (follow-up to #1605, #1570)

Readers take a closed polyline for a revision cloud only with RevcloudProps
xdata (#1605) and every bulge within 0.02 of 0.520567; clouds used 0.5,
just outside, so ezdxf's is_revcloud still said no. Clouds now use
0.520567050552 on every creation path. Tests check the reader's condition
for all six ways of drawing a cloud and after a DXF round trip.

* Parity checklist: regenerated after merging main

* Parity checklist: regenerated after merging main

* REVCLOUD: import RawTag in the revcloud module main split out of draw2

* Parity checklist: regenerated after merging main

* Revcloud: update the recognition test for main's prompts (#1692)

Main now asks for the minimum and maximum arc length and, after an object
pick, whether to reverse direction, so the old scripts left a prompt waiting
and the test read the previous entity. A helper now checks the prompts
finished and exactly one new entity was created.

* Revcloud: drop the file-format-parity.md change from this PR (#1692)

The LWPOLYLINE note and changelog entry are moved to the PR description, as review asked.

---------

Co-authored-by: NetterSilver <[email protected]>
Co-authored-by: Claude Haiku 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
Co-authored-by: SBaksa <[email protected]>
2026-11-28 15:22:40 +01:00
oracola91andFredApps 72a71b58df CADCraft.app ships the licence files (#1710)
Since #2119 the app bundle carries NOTICE and ATTRIBUTION.md, but not
LICENSE-MIT and LICENSE-APACHE, which the .deb, .rpm, .tar.gz, AppImage
and both zips ship. Copy them into Contents/Resources next to the
notices, before signing, so the bundle seal covers them.

Co-authored-by: FredApps <[email protected]>
2026-11-28 15:10:30 +01:00
Khuong DoanandClaude Opus 5.5 909fad52c4 fix(io): find table, multileader and multiline styles and viewport configurations without scans, so crafted files don't open or save in quadratic time (#3590)
* fix(io): look up table, multileader and multiline styles without scans

A crafted DXF made several style lookups cost N^2 name comparisons
(#1924, F-04 item 5):
- the reader's TABLESTYLE, MLEADERSTYLE and MLINESTYLE records, each
  scanning the styles read so far for an earlier one of its name, and its
  VPORT records, each scanning the viewport configurations;
- each table from another writer, scanning the table styles on read;
- each TABLE, MULTILEADER and MLINE on DXF save, for its style's handle
  and values;
- render's table_style_of, which a DXF save calls for every table;
- AUDIT's multileader and table style checks, which RECOVER runs on open.

On main, N = 40 000 MLEADERSTYLE or TABLESTYLE records took 65-69 s to
open, and the DXF save of 40 000 multileaders or foreign tables naming a
missing style ran past 300 s. With this change they take 0.4-5.5 s, and
the output is byte-identical.

- ByName (from #3562) moves to dxf_ext.rs and gains position(). The record
  dedups go through it, keeping the rule: a later record of a name
  replaces the first in place and takes its name. A VPORT record still
  adds a tile to the first configuration of its name.
- Drawing::table_styles is a NamedList, like the other style tables.
- The writer's Ctx keeps a ByName beside its table and multileader style
  lists. dxf_mline::plan and Plan keep one too. Missing names fall back as
  before.
- When no styles are planned (entity_groups, for entget), the multileader
  style is still looked up in the drawing.
- AUDIT checks multileader styles against a lower-cased BTreeSet, and
  table styles with by_name.

Tests: cost tests for each path, with behaviour checks that also hold on
the old code, and an entity_groups test for the multileader's style.

Part of #1924.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(io): trim a multiline style's name when reading it

A DXF MLINESTYLE named " Road " was kept with its spaces. Its multilines
look their style up trimmed (dxf_mline::plan, Plan::handle,
Drawing::mline_style), so a save missed it, wrote a second Road style and
pointed the multilines at that copy. main did the same: its scan compared
the trimmed query with the untrimmed name. The writer already writes the
name trimmed, and the reader's fill key trims it, so the name is now
trimmed where it is read (CodeRabbit, on #3590).

Test: a_padded_multiline_style_name_is_saved_once (fails without the
trim: the save writes STANDARD, Road and Road).

Part of #1924.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-28 14:56:15 +01:00
Dylan M. Taylor 190d88fc03 Fix reopening CADCraft nightly after saving its profile (#3603)
* fix: reopen populated nightly profiles

* fix: validate nightly file metadata with the pinned Windows API
2026-11-27 19:04:59 -05:00
FredApps 4c4d2690d4 Parity: headless column (RFC-0052) (#3602)
* Add the RFC-0052 headless column to the parity checklist

* AGENTS.md: keep a submenu headless mark until every leaf under it is covered
2026-11-28 00:01:28 +01:00
skylar taylor-barrick f7adf3ad56 Prepare CADCraft nightly signing and Mac archive layout (#3598) 2026-11-27 15:19:23 -06:00
Dylan M. TaylorandFredApps 1981067187 ci: notify artcraft-services on release state changes (#3581)
* ci: notify artcraft-services on release state changes

* ci: pass only the dispatch token to the notify-services workflow

secrets: inherit hands the called workflow every repository secret, including
the signing credentials. The reusable workflow only reads
ARTCRAFT_SERVICES_DISPATCH_TOKEN, so map just that one.

---------

Co-authored-by: FredApps <[email protected]>
2026-11-27 09:44:56 -05:00
FredApps 717f9520d3 Merge pull request #3564 from 2ez4gcx/fix/linetype-dash-budget
Linetypes: a dash budget per build, and say when a run is drawn continuous
2026-11-27 14:43:50 +01:00
FredApps ff4de54a14 Merge remote-tracking branch 'origin/main' into real-3564
# Conflicts:
#	crates/render/src/lib.rs
#	crates/render/src/pipeline.rs
#	crates/render/src/viewports.rs
2026-11-27 20:23:57 +07:00
FredApps dd423db3a8 Merge pull request #3572 from 2ez4gcx/fix/lisp-blocking-run
LISP: an expression typed at a prompt gets a short step allowance
2026-11-27 14:23:02 +01:00
FredApps fa6e282d16 Merge pull request #3562 from 2ez4gcx/fix/table-record-dedup
fix(io): read VIEW and UCS records, and each layout's named UCS, without scanning, so crafted files don't open in quadratic time
2026-11-27 14:22:56 +01:00
FredApps 59efc33013 Merge pull request #3561 from 2ez4gcx/fix/datalink-stored-paths
Data links: read a link saved in a drawing only from its folder
2026-11-27 14:22:50 +01:00
FredApps e3418eddbc Merge pull request #3560 from 2ez4gcx/fix/dimension-block-render-cycle
fix(render): a dimension whose block leads back to its own block is drawn once, not down to the depth limit
2026-11-27 14:22:45 +01:00
FredApps 1c45f0e307 Merge remote-tracking branch 'origin/main' into pr-3572
# Conflicts:
#	crates/engine/src/lisp/tests.rs
2026-11-27 20:06:58 +07:00
FredApps 456fdacf01 Merge pull request #3589 from 2ez4gcx/fix/hatch-edge-path-chaining
DXF/DWG: chain HATCH edge-path edges that are out of order or reversed
2026-11-27 14:06:09 +01:00
FredApps 1b48b22546 Merge pull request #3588 from 2ez4gcx/fix/control-preauth-bound
Bound what the control server reads before the token check (part of #1925, F-12)
2026-11-27 14:06:04 +01:00
FredApps 1858b04c2f Merge pull request #3582 from 2ez4gcx/fix/attdef-ocs-plane
Read a tilted ATTDEF or ATTRIB at its world point (#3541)
2026-11-27 14:05:59 +01:00
FredApps 86731b23e4 Merge pull request #3576 from 2ez4gcx/fix/lisp-integer-wrap
LISP: gcd and atoi give a real past 32 bits instead of wrapping
2026-11-27 14:05:35 +01: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 <[email protected]>
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 <[email protected]>
2026-11-27 19:26:23 +07:00
2ez4gcxandClaude Opus 5.5 1aa8d9db9c Keep the lost-reply warning on the control client's retry
exchange() retries once when the first attempt was not sent (or is
read-only), but the retry dropped `sent`: a mutation the retry sent and
whose reply was lost came back as a plain transport error, without the
"may or may not have been applied" warning. The new ping before long
requests adds a way into that retry (a lost ping reply counts as not
sent). The retry now keeps `sent` and returns the same warning for
mutations; read-only methods keep the plain error.

Test: a_lost_reply_on_the_retry_still_says_a_mutation_may_have_been_applied.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 17:18:56 +07:00
2ez4gcxandClaude Opus 5.5 364881867c Hatch edge chaining: close each later outline at its exact start
A later outline was closed back to its start only when its end lay farther
than the tolerance from it (review). With the end within the tolerance but
not equal, the jump back to the first outline left from the end while the
jump out arrived at the start, so the two did not cancel under even-odd
fill and a sliver between them was filled. The start is now added whenever
the end differs from it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 16:17:07 +07:00
2ez4gcxandClaude Opus 5.5 3da5c2c319 Hatch edge chaining: ends meet only within the tolerance
The end lookup took any unused end in the 3x3 grid cells around a point,
so ends up to about 2.8 tolerances apart could be joined (review). The grid
now only gives candidates; each is checked with Vec2::near against the
tolerance and the lowest eligible end wins, as the "runs on" and closed-run
checks already did. A cell's scan stops at the best match so far, and the
ends visited are capped at 32 per end of the loop: past that, a crafted
loop is read in file order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 15:36:01 +07: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
2ez4gcxandClaude Opus 5.5 02ea1d1c31 DXF/DWG: chain HATCH edge-path edges that are out of order or reversed
An edge path was read in file order, so an edge listed elsewhere or stored
end to start made the vertex list jump, and the even-odd fill filled the
polygon of the jumps (a square listed AB, DC, BC, AD filled as an hourglass).

Each edge is now read on its own and hatch/chain.rs joins them. A path whose
edges already run on is joined in file order as before. Otherwise edges are
chained into runs by their ends (within a millionth of the loop's extent,
at least 1e-9), turned around when needed (points reversed, bulges negated
and moved). Closed runs fill as loops of their own; open runs are joined in
order, as a path read in file order is. Ends are looked up in a sorted grid,
O(n log n).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 14:11:23 +07:00
2ez4gcxandClaude Opus 5.5 db0a4aca42 Bound what the control server reads before the token check (#1925)
The control server checks a request's token only after reading the whole
line, and clients send the token last, so a local peer without it could
make the app buffer a line of up to 256 MiB (512 MiB across connections).

Until a request on a connection has passed the token check, a request
line may be at most 64 KiB (control_token::MAX_UNAUTHENTICATED_LINE); a
longer one gets an error reply and the connection is closed. After that
the usual 256 MiB limit applies.

The MCP bridge sends a short ping with the token before a longer request
on a new connection, and sends the request only when the ping's reply
shows the token check passed; a refused or lost ping leaves the request
unsent and safe to retry. docs/control-protocol.md describes the limit.

Part of #1925 (F-12).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 14:09:23 +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
2ez4gcxandClaude Opus 5.5 293d79fac8 Read a tilted ATTDEF or ATTRIB at its world point (#3541)
An ATTDEF or ATTRIB in a tilted plane facing up holds its insertion
point, alignment point and rotation in that plane's OCS (DXF Reference,
ATTDEF and ATTRIB groups 10 and 11 "in OCS"; "Object Coordinate Systems
(OCS)"). The reader took them as world coordinates, and the writer saves
attributes with no group 210, so a save moved the attribute millions of
units in a drawing near survey coordinates.

flatten_tilted maps them through Mat4::ocs and turns group 50 into the
plane's direction in plan, as tilted LWPOLYLINE and HATCH are drawn
flat; an ATTDEF's extrusion is then spent. ATTRIBs of a reference that
is itself left in its tilted plane (#1158) stay as read with it; the
INSERT arm and that check share mirrored_reference. Planes facing down
(mirror_text), flat attributes and TEXT (#3296) are unchanged.

Fixes #3541

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 11:11:12 +07:00
2ez4gcxandClaude Opus 5.5 7b482c5e3b render: a pattern of gaps only draws no line on any run
e9e4b0e1f made a gaps-only pattern draw nothing past the per-run limit, but
it was still drawn as one continuous line where a pattern with a dash falls
back to continuous: a run shorter than one period, a pattern under
`min_pattern` (sub-pixel), past 50,000 periods with a level of detail, and
a run of one point (review of #3564). On screen that also differed from the
plot of the same run.

apply, apply_as and ranges now return no dashes for a pattern whose elements
are all gaps, before any of those fallbacks. Patterns with a dash or a dot
keep every fallback, and an empty (continuous) pattern is drawn whole. Texts
and shapes in a gaps-only pattern are placed as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 09:05:09 +07: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 <[email protected]>
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 <[email protected]>
2026-11-26 16:34:27 -05:00
2ez4gcxandClaude Opus 5.5 e9e4b0e1ff render: charge a closed run for the periods it walks; gaps only draw nothing at any length
Review of #3564:

- A closed run is stretched to round(L / period) periods and laid out from
  the period before its anchor to the one after its last, up to half a
  period more than the (L / period + 2) elements it was charged. A run of
  192 on 127 dashes and a gap (period 128) walked 508 elements for a charge
  of 448. It is now charged (round(L / period) + 2) x the pattern's length.
  The per-run limit keeps its formula, so runs under it keep their output.
- A pattern of gaps only was refused past the per-run limit, drawn as one
  continuous line and counted as undashed, while below the limit it draws
  nothing. It now draws nothing at any length, uncharged and unreported.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 01:19:53 +07:00
2ez4gcxandClaude Opus 5.5 7dfb39d3db LISP: gcd and atoi give a real past 32 bits instead of wrapping
`(gcd -2147483648 0)` gave 2147483647 (the divisor clamped to the
largest integer), and `atoi` cast its digits with `as i32`, so
"99999999999" gave 1215752191 and "99999999999999999999" gave 0.

They now follow what the reader, `fix` and JSON inputs already do with
a whole number that doesn't fit 32 bits: it is a real. `gcd` gives
2147483648.0 for its one such result; `atoi` gives the real `atof`
reads from the digits, the number the reader makes of them. Results
that fit are the same integers as before. Integer arithmetic still
wraps.

Part of #1933.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 00:47:43 +07:00
2ez4gcxandClaude Opus 5.5 a44fcd4fce engine: EXPORT, PLOT and SAVEAS to an image say when dashes were drawn continuous
The first commit made `cadcraft-cli convert` print the note, but the app's
own commands write images through IoHooks::write and ::plot, which return
bytes only, so the desktop and web apps and LISP stayed silent (#1069).

- cmd::file::set_noted_io(NotedIo { write, plot }): an optional hook beside
  IoHooks (which is built by struct literal in ~70 places), installed by the
  CLI, desktop and web apps with cadcraft_io::write_framed_noted and the new
  cadcraft_io::plotter::plot_noted / pdf::plot_noted.
- EXPORT, PLOT (so EXPORTPDF, PUBLISH and PDFBOOK per sheet), QSAVE and
  SAVEAS to an image and document.bytes echo the note and add it to the
  result's `warnings`. An image written with a `version` option goes through
  the same writer (same bytes), so it is noted too.
- report_notes adds to `warnings` instead of replacing them;
  report_dwg_notes uses it (no result had `warnings` before it, so DWG
  results don't change). Without the hook nothing changes.

Not covered: the plot preview and the canvas show no message.

Fixes #1069.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 00:11:22 +07:00
2ez4gcxandClaude Opus 5.5 ef42a37dcb LISP: an expression typed at a prompt gets a short step allowance
An expression typed at a command's prompt (CIRCLE, then `(while T)` as
the radius) is the prompt's answer, so it ran as a blocking run with the
500,000,000-step cap meant for programmatic calls: about 17 s on a dev
build with no frame drawn and Esc not handled.

It now runs through `lisp_eval_answer` with a 20,000,000-step cap, and
the callbacks it runs (`vl-sort`'s comparator and the other synchronous
callbacks) share what is left of that allowance instead of each taking
the 500,000,000-step callback allowance inside one step. The error says
the expression was stopped and to run long routines at Command:, where
they run a slice per frame and Esc stops them. Routines at Command:,
`c:` commands, APPLOAD, dropped files, the `lisp`/`appload` JSON calls
and startup files are unchanged.

Part of #1926 (item 3).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 23:32:33 +07:00
2ez4gcxandClaude Opus 5.5 861223423d Data links: drop the file linked longest ago at the bound
DATALINK remembers up to 1000 linked files per open drawing. At the
bound a new file dropped an arbitrary entry of a HashSet, which could be
the file linked just before it. Each remembered file now carries when it
was last linked: linking it again moves it to the newest, and a new file
at the bound drops the one linked longest ago.

Test: remembered_links_are_the_most_recent_ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 22:27:50 +07: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 <[email protected]>
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 <[email protected]>
2026-11-26 15:18:05 +01:00
FredApps a3ed0682ab Merge pull request #1633 from KnottyDyes/squad/docs-dxf-dwg-write-version
Docs: describe DXF and DWG save-version selection
2026-11-26 15:12:38 +01:00
FredApps b1340f0697 Merge main into docs/save-version (keep main's craft-dwg and acadrust 0.6.6 text; this PR's version-selection rules) 2026-11-26 20:48:14 +07:00
2ez4gcxandClaude Opus 5.5 c824e5e96a render: a dash budget per build, and say when a run is drawn continuous
A dashed run is laid out over at most two million pattern elements, but
nothing bounded the total, and a pattern of mostly gaps visits many elements
for each point it draws, so the 64M-point display budget never stopped it:
1,000 lines on a 256-element pattern of gaps and one dash (a 58 KB DXF) took
11.6 s to PNG and 12.7 s to a 69 MB PDF on a dev build. A run past the
per-run limit was also drawn continuous without a word (#1069).

- MAX_DASH_ELEMENTS (64M, as many as the list's points) is charged by
  linetype::layout before a run is laid out, on a counter shared like the
  point budget's (parallel parts, XCLIP parts, viewport contents). Once a run
  does not fit, the rest of the build's dashed runs are drawn continuous.
  The per-run limit is MAX_RUN_DASH_ELEMENTS, unchanged.
- A run drawn continuous because of either limit sets DisplayList::truncated
  and counts in the new DisplayList::undashed, merged where lists are joined.
  Runs drawn continuous by rule (short, sub-pixel, the screen's 50,000-period
  level of detail) are not counted.
- cadcraft_io::write_framed_noted (and png/svg/pdf "noted" variants) return
  the note; cadcraft-cli convert and run --export print it.
- Linetype texts are placed only on a run whose dashes were laid out; phase
  checks the limits without laying the run out again.

On 11 real drawings the most a complete plot asked was 26.5M elements; a
16M total would have drawn 8,241 runs of that drawing solid. With 64M the
gap-pattern file takes 0.8 s / 0.4 s, the #1069 controls and three real
drawings export byte-identical, and the audit's dense dash/gap file stays as
on main (it fills the point budget at the same time).

Part of #1923 (F-05 f). Part of #1069: the app's EXPORT and PLOT don't show
the note yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:13:14 +07:00
FredApps b3bc4a7618 Merge pull request #997 from aldozar/perf/cjk-text
Faster CJK-heavy drawings: per-thread font caches, offscreen glyphs left out (#666, #662)
2026-11-26 13:43:40 +01:00
FredApps e66cdcec29 Merge main into perf/cjk-text
Conflicts: crates/fonts/src/ttf.rs (main made OutlineMesh's points pub(crate); kept that and this PR's bounds field) and crates/render/src/tests.rs (kept this PR's #666 view test and main's fixture-font section).

Main also added a public font-set GENERATION/generation() for redraws (2c979eb1), which clashed by name with this PR's private lookup-cache counter. Renamed this PR's counter to LOOKUP_GENERATION/lookup_generation(), and set_font_dirs now also calls changed() so the per-thread caches drop fonts from removed folders.

cargo test -p cadcraft-fonts -p cadcraft-render and cargo fmt --check pass locally.
2026-11-26 19:31:45 +07:00
2ez4gcxandClaude Opus 5.5 077a5fd247 fix(io): read VIEW and UCS records and each layout's named UCS without scans
The DXF reader looked for an earlier VIEW or UCS of the same name by
scanning the records read so far, and found each layout's named UCS by
scanning every UCS, on read and on save. A crafted file of N VIEW or N UCS
records, or of N layouts each naming one of N UCSs, cost N^2 name
comparisons (#1924, F-04 item 3): at N = 40 000 it took 67 s and 194 s to
open on main.

- ByName: the records of a table read so far by lower-cased name; a later
  record of a name replaces the first, which keeps its place and takes the
  later record's name, as before. DIMSTYLE records use it too.
- UcsNames: the drawing's UCSs by lower-cased name with their positions in
  table order; a layout's named UCS is the first of that name whose frame
  is the layout's, as named_ucs finds it. Built once per read and per save.

Tests: VIEW/UCS records (main 118.9 s, now 0.23 s) and layouts naming
UCSs, read and saved (39.9 s, now 1.6 s), against a 10 s bound; a
behaviour test compares UcsNames with named_ucs. Follows #3539.

Part of #1924

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 18:55:44 +07:00
2ez4gcxandClaude Opus 5.5 8f4f06b9fb Data links: read a link saved in a drawing only from its folder
A table's data link path is stored in the drawing, and DATALINKUPDATE
copies the linked file's text into the table, where the next save keeps
it. A stored path could name any local file (by `..` or an absolute
path), so a drawing could pull any readable file into itself.

A link the drawing itself names is now read only when its file, resolved
by the file system (`..`, symbolic links and junctions followed), lies in
the drawing's folder or a folder below it, compared by whole components;
the resolved path is the one read. A file the user links with DATALINK
is remembered for that open drawing (never saved, at most 1000, newest
kept), so it keeps updating until the drawing is opened again. Refused
links are listed in DATALINKUPDATE's errors; the other links update. The
automation roots are still checked first.

Part of #1929 (F-08).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 18:48:34 +07:00
2ez4gcxandClaude Opus 5.5 851d154843 fix(render): draw a dimension whose block leads back to its own block from its definition points
A dimension block holding dimensions of itself, directly or through block references, other
dimension blocks, multileader blocks or proxy graphics, was drawn again for every such dimension at
every level down to MAX_BLOCK_DEPTH: k of them made up to k^16 copies, a loop through many
distinct blocks one copy per ordering of them, cut only by the 2M expansion budget. A crafted
490-byte DXF took 79 s to export to PNG (dev build), 602 bytes over 300 s.

A dimension inside block C is now drawn from its own block T only if T does not lead back to C.
A short search from T (16 blocks, 256 objects) settles ordinary blocks; past it the strongly
connected components of the block graph are found once per build (iterative Tarjan, shared through
a OnceLock). A dimension on a loop is drawn from its definition points, as one whose block is
missing is. Loops made only of block references are unchanged.

Part of #1923 (F-05).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 17:45:00 +07:00
FredApps e59031a441 Merge pull request #2782 from 2ez4gcx/fix/arraypath-closed-spacing
ARRAYPATH: no extra item where a closed path closes, by spacing
2026-11-26 10:39:43 +01:00
FredApps e0d64c676d Merge pull request #2705 from 2ez4gcx/fix/spline-closed-autocad
SPLINE: closed fit-point splines built as AutoCAD 2024 builds them
2026-11-26 10:29:22 +01:00
FredApps a46923c96d Merge remote-tracking branch 'origin/main' into ic45-2782 2026-11-26 16:20:50 +07:00
FredApps 61f4632e60 Merge pull request #2762 from 2ez4gcx/fix/arraypath-item-count
ARRAYPATH: the item count takes a whole number as AutoCAD 2024 does
2026-11-26 10:20:35 +01:00
FredApps 28fd71600c Merge pull request #2778 from 2ez4gcx/fix/splinedit-elevate-order-integer
SPLINEDIT: take a whole number as typed for Elevate order
2026-11-26 10:20:17 +01:00
FredApps 6525de811e Merge pull request #2784 from 2ez4gcx/fix/insert-points-at-scale-prompts
INSERT/MINSERT: take points at the scale, rotation and spacing prompts
2026-11-26 10:20:00 +01:00
FredApps daa6bf9063 Merge main into fix/spline-closed-autocad 2026-11-26 16:09:42 +07:00
FredApps b4ad0f3800 Merge pull request #2703 from 2ez4gcx/fix/spline-file-tangent-length
SPLINE: a file's end tangents count with their length, as in AutoCAD 2024
2026-11-26 10:09:24 +01:00
FredApps 5096e1503f Merge pull request #3500 from 2ez4gcx/feat/vi-catalog-phase1
Vietnamese catalog: approved terminology and the 249 missing strings (craft-i18n#401 phase 1)
2026-11-26 10:09:06 +01:00
FredApps bcfc9a0786 Merge pull request #2780 from 2ez4gcx/fix/divide-count-integer
DIVIDE: take a whole number as typed for the number of segments
2026-11-26 10:04:21 +01:00
FredApps 9df34c448c Merge remote-tracking branch 'origin/main' into ic45-2762 2026-11-26 16:00:43 +07:00
FredApps edbdf0dd8f Merge pull request #2774 from 2ez4gcx/fix/arraypath-json-params
ARRAYPATH: refuse a JSON count or spacing it can't use
2026-11-26 10:00:31 +01:00
FredApps 60ca94cd7a Merge commit 'bb3b0cd5' into ic46-2705 2026-11-26 16:00:25 +07:00
FredApps 02bc55aaaa Merge remote-tracking branch 'origin/main' into ic45-2778
# Conflicts:
#	crates/engine/tests/it/pedit_splinedit.rs
2026-11-26 15:56:21 +07:00
FredApps 66d92125f1 Merge pull request #2772 from 2ez4gcx/fix/splinedit-precision-integer
SPLINEDIT: take a whole number as typed for the polyline precision
2026-11-26 09:54:22 +01:00
FredApps 40c4c7dac1 Merge main into feat/vi-catalog-phase1 2026-11-26 15:52:44 +07:00
FredApps bb3b0cd5cd Merge main into fix/spline-file-tangent-length 2026-11-26 15:52:12 +07:00
FredApps efa617fcd5 Merge remote-tracking branch 'origin/main' into ic45-2784
# Conflicts:
#	crates/engine/tests/it/minsert.rs
2026-11-26 15:51:50 +07:00
FredApps 19290804a1 Merge pull request #2699 from 2ez4gcx/fix/spline-fit-autocad
SPLINE: open fit-point splines built as AutoCAD 2024 builds them
2026-11-26 09:51:49 +01:00
FredApps bb375992f4 Merge pull request #2789 from 2ez4gcx/fix/minsert-json-counts
MINSERT: JSON rows and columns are whole numbers
2026-11-26 09:51:23 +01:00
FredApps f2d1845aee Merge pull request #2205 from 2ez4gcx/fix/pline-undo-plinewid
PLINE: Undo returns to the last segment's mode, and PLINEWID is the width
2026-11-26 09:48:33 +01:00
FredApps 2c4ab18255 Merge pull request #2761 from 2ez4gcx/fix/array-count-integer
ARRAY: counts take a whole number as typed, as AutoCAD 2024 does
2026-11-26 09:48:12 +01:00
FredApps a37797484d Merge pull request #2204 from 2ez4gcx/fix/rectang-autocad-vertices
RECTANG: Area with cut corners, oversized corners and Rotation as AutoCAD takes them
2026-11-26 09:48:01 +01:00
FredApps 900ed557f1 Merge pull request #2726 from 2ez4gcx/feat/copy-autocad
COPY as AutoCAD 2024: COPYMODE, mOde/Multiple, Array with Fit, Undo, and Enter for a displacement
2026-11-26 09:47:40 +01:00
FredApps d7ea0ede4c Merge pull request #2209 from 2ez4gcx/fix/stretch-arcs-bulges-splines
STRETCH: arcs and polyline arc segments keep their height; spline control points move
2026-11-26 09:47:17 +01:00
FredApps 0e3a58418f Merge remote-tracking branch 'origin/main' into ic45-2780 2026-11-26 15:44:23 +07:00
FredApps 6a3199d5a4 Merge pull request #3539 from 2ez4gcx/fix/style-name-lookups
fix(doc, io): look linetypes, text and dimension styles and layouts up by name through an index, so crafted files don't open or draw in quadratic time
2026-11-26 09:42:20 +01:00
FredApps c352afc399 Merge remote-tracking branch 'origin/main' into ic45-2774 2026-11-26 15:40:39 +07:00
FredApps 292b6bc7ce Merge remote-tracking branch 'origin/main' into ic45-2772 2026-11-26 15:38:23 +07:00
FredApps 45b20c6470 Merge remote-tracking branch 'origin/main' into ic45-2789 2026-11-26 09:35:09 +01:00
FredApps fbea6d1ffc Merge pull request #2766 from 2ez4gcx/fix/minsert-count-integer
MINSERT: take a whole number as typed for the rows and columns
2026-11-26 09:34:52 +01:00
FredApps 22ba34c123 Merge main into feat/vi-catalog-phase1 2026-11-26 09:32:53 +01:00
FredApps 331c867476 Merge main into fix/array-count-integer 2026-11-26 09:28:41 +01:00
FredApps bddbf390f7 Merge main into fix/rectang-autocad-vertices 2026-11-26 09:28:12 +01:00
FredApps 5f24b4b667 Merge main into fix/pline-undo-plinewid 2026-11-26 09:28:06 +01:00
FredApps 6b403674ed Merge main into fix/stretch-arcs-bulges-splines 2026-11-26 09:27:59 +01:00
FredApps 2485c2e758 Merge main into feat/copy-autocad 2026-11-26 09:17:23 +01:00
FredApps 2ca9557d2c Merge remote-tracking branch 'origin/main' into ic45-2766 2026-11-26 09:16:22 +01:00
FredApps ea66defc0d Merge main into fix/spline-fit-autocad 2026-11-26 09:12:33 +01:00
FredApps 2e9fe9462c Merge main into fix/style-name-lookups 2026-11-26 09:10:47 +01:00
ATOM 1db31ea608 dxf: store DIMLFAC-scaled dimension measurements 2026-11-26 01:45:45 -06:00
2ez4gcxandClaude Opus 5.5 4c1ea7d320 Merge main (ba344a89) into feat/copy-autocad
One conflict, in crates/engine/src/cmd/modify/select_then.rs: this branch
adds COPY's copy_prompt, copy_input and copy_done just above join_now, and
main (#2725) rewrote join_now's doc comment. Kept both: the COPY methods,
then main's two-line doc. The struct fields (copy_single, copies,
copy_array, ask_circle), SelectThen::new and the match arms merged without
conflict. No behaviour changed on either side.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:39:48 +07:00
vantruong-dang 20d4247ed5 fix(ui): preserve clipboard event ordering for PasteTable in shortcut dispatch 2026-11-26 14:35:13 +07:00
2ez4gcxandClaude Opus 5.5 d290fc886f fix(doc, io): look linetypes, styles and layouts up by name through an index
Drawing::linetype, text_style, dim_style and layout scanned their table,
once per entity while a drawing is drawn, measured or saved, and once
per layout after every command. The DXF reader also scanned the
dimension styles once per DIMSTYLE record and the layouts by exact name
once per paper-space object. So a crafted file of N records and N
entities naming one it lacks, N DIMSTYLE records, or N layouts with N
objects in the last of them cost N^2 name comparisons (#1924, F-04
item 3): at N = 40 000 a PNG export took 23 s, opening 107-151 s or
more than 300 s on main.

- linetypes, text_styles, dim_styles and layouts are NamedLists (from
  #3484) and the four lookups use its index: the first entry of a name
  in list order, ASCII case folded, as the scan returned.
- NamedList::by_name_mut: the first entry of a name to change.
- Scans with the same answer go through the lookup (STYLE, DIMSTYLE,
  RENAME, -DIMSTYLE, .lin loading, COMPARE, COUNT, UCS, plotter, DXF
  header, Layers panel).
- The DXF reader indexes DIMSTYLE records by lower-cased name, and maps
  layout names (exact) to the first layout of that name once per pass.

Cost tests (doc: one per table; io: DIMSTYLE records and layouts) fail
on main at 66-421 s and pass within 3 s; a behaviour test compares
every lookup with a scan.

Part of #1924

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:02:33 +07:00
skylar taylor-barrick 12eef22768 Nightly: stop blocking a refused launch on macOS (#3537)
Nightly launch fix under Skylar's Exec 454: the Launcher's trailing `--` no longer reaches the file list where that applied, and a refused launch no longer blocks on macOS (the reason goes to stderr and the app exits 2).
2026-11-26 00:46:02 -06:00
FredApps 7c8f8ada92 Merge pull request #3536 from 2ez4gcx/fix/dwg-ltype-dash-count
DWG save: keep the first 255 dash elements of a linetype, and say so (part of #1923)
2026-11-26 07:43:27 +01: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
FredApps ba344a894b Merge pull request #2790 from 2ez4gcx/fix/join-other-height
JOIN: ends meet at the same height; objects facing the other way stay out
2026-11-26 06:13:20 +01:00
2ez4gcxandClaude Opus 5.5 b861b6c0a5 DWG save: keep the first 255 dash elements of a linetype, and say so
acadrust 0.6.6 writes and reads a DWG linetype's element count as one
byte, so a linetype of 256 elements came back from a DWG save with none
(continuous) and one of 300 with 44. The DXF read cap of #3482 lets 256
through, so every capped DXF linetype hit the 256 -> 0 case.

The DWG bridge text now writes at most 255 elements per linetype (the
first ones, with group 40 totalling them); DXF output is unchanged.
cadcraft_io::dwg_notes gives one note counting the linetypes cut, counted
by the writer so an xref linetype the file leaves out is not counted. An
engine hook installed by the apps echoes it and returns it in `warnings`
on every DWG write: QSAVE/SAVEAS, document.bytes, EXPORT, WBLOCK,
-WBLOCK, LAYOUT SAVEAS; cadcraft-cli convert prints it.

Part of #1923 (F-05).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 12:07:14 +07:00
FredApps c9260d1b59 Merge pull request #2740 from 2ez4gcx/feat/qleader
QLEADER at the command line, as AutoCAD 2024 runs it
2026-11-26 06:06:19 +01:00
FredApps d2587c694e Merge pull request #2487 from 2ez4gcx/fix/linetype-dash-layout
Linetypes: lay dashes out as AutoCAD does
2026-11-26 06:05:59 +01:00
vantruong-dang e3f1a0b1d2 test(engine): cover SCALE Reference previews and hot-grip point-pick branches 2026-11-26 11:46:29 +07:00
FredApps a06b236f0c Merge branch 'main' into fix/join-other-height 2026-11-26 05:34:33 +01:00
FredApps 4a4b1e2339 Merge pull request #2906 from 2ez4gcx/fix/pedit-heights
PEDIT: polylines at their objects' height; Join only at the same height
2026-11-26 05:32:57 +01:00
FredApps b5481e3bbf Merge pull request #2725 from 2ez4gcx/feat/join-autocad
JOIN onto the source object as AutoCAD 2024 does: lines, arcs, and a polyline that keeps its handle
2026-11-26 05:32:42 +01:00
FredApps 7244d2bc96 Note QLEADER in the Leaders, tables, fields parity row
The command-line form lands in #2740 / #3532; the Settings dialog is still open.
Percentages and hours are not re-measured.
2026-11-26 05:30:16 +01:00
FredApps d8aa2c60dc Merge main into feat/qleader 2026-11-26 05:30:16 +01:00
FredApps b38215b7cf Merge main into fix/linetype-dash-layout 2026-11-26 05:30:04 +01:00
FredApps d955a3ccfc Clamp gap-first open-run dashes to the start of the run
In the x < 0 branch, a dash that starts slightly before p0 could push a
negative range. Keep the start at p0 (and the existing end cap at p0 + len).
2026-11-26 05:30:04 +01:00
aiongg b55abde2a8 Merge pull request #3449 from aiongg/minimal-port-next
CadCraft: move to craft-libs next (minimal port)
2026-11-25 23:16:50 -05:00
aiongg a3640199b6 Quit CADCraft asks about unsaved drawings again
muda's predefined Quit ends the process through terminate: without asking. The menu item
is craft-quit's Quit, a close request of the main window, so the close path asks first
as the close button does (#2157).
2026-11-26 03:48:00 +00:00
FredApps 91966ccc9d Classify qleader under NO_FILES for automation roots 2026-11-26 10:15:15 +07:00
FredApps 414e544282 Merge pull request #2760 from 2ez4gcx/fix/options-reset-profile
OPTIONS: reset restores every profile variable; a refused change leaves the drawing's snap and grid
2026-11-26 03:58:53 +01:00
FredApps b255d58275 Merge pull request #3491 from 2ez4gcx/fix/attrib-tag-matching
fix(doc,render,io,engine): match attributes to their definitions by tag in one lookup (part of #1923)
2026-11-26 03:54:12 +01:00
FredApps 1fb86ec415 Merge remote-tracking branch 'origin/main' into ic40-2740 2026-11-26 09:50:41 +07:00
FredApps 8a5bd99e46 Merge pull request #3482 from 2ez4gcx/fix/ltype-element-cap
DXF read: keep at most 256 dash elements per linetype (part of #1923)
2026-11-26 03:45:04 +01:00
skylar taylor-barrick cad62242eb Switch on supervised nightlies on the nightly-signer branch (#3522)
Supervised nightly switch-on, merged under Skylar's explicit Nightly 758 override after green CI, CodeRabbit on this head with no open threads, Sonar passing, and an independent adversarial review with no blockers.
2026-11-25 20:43:56 -06:00
FredApps bc5749ec18 fix(doc): order attribute tags instead of hashing them, so crafted tags can't collide on the web build
The web build's RandomState keys come from addresses, not entropy, so a
file could pick tags whose hashes collide and bring back the A x K cost
this change removes. Key the by-tag maps by the tag's ASCII-folded bytes
in a BTreeMap, as the layer and block name index (#3484) does. Matching
is unchanged: TagKey's order is consistent with eq_ignore_ascii_case.

Part of #1923.
2026-11-26 09:42:42 +07:00
FredApps 4cc0e1f19a Merge main into fix/attrib-tag-matching 2026-11-26 09:34:25 +07:00
FredApps 927108262a Merge pull request #3484 from 2ez4gcx/fix/open-name-lookups
fix(doc): look layers and blocks up by name through an index, so crafted files don't open in quadratic time
2026-11-26 03:33:57 +01: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
aiongg f99ae6956c A copy fired in a floating panel keeps the modifiers it was pressed with 2026-11-25 20:11:31 +00:00
aiongg b844248903 Floating windows carry the running channel's app id 2026-11-25 20:09:16 +00:00
aiongg 1cff8cd681 Repin craft-libs to storytold next 8fa4db64a9 and egui to b9770908e 2026-11-25 19:15:09 +00: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
aiongg 09944da2a4 Repin craft-libs to the hidden-window and modal-focus fixes (next + float-fixes) 2026-11-25 18:45:26 +00: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
aiongg 433e51abc4 Reset Panel Layout cancels a panel drag in progress again
As before the move to the craft-ui dock, a tab held while the layout
resets is not dropped into the reset layout. The reset replaces the
workspace, so its generation changes.
2026-11-25 18:29:18 +00:00
aiongg 53d1790348 Close tests: a close that goes ahead is checked without quitting
The tests assert CADCraft's own close decision for a saved drawing and
for a programmatic quit, as they did before the platform's quit joined
the close path, so they pass on macOS, where that quit cancels the window
close. Unsaved drawings still run the whole close frame.
2026-11-25 18:24:58 +00:00
aiongg f4c3018003 An opened panel's floating window comes to the front again
As before the move to the craft-ui dock, opening or activating a panel
with a command raises the floating window that holds it, once. Docked
panels only become the front tab.
2026-11-25 18:24:58 +00:00
aiongg 239f8a32f0 Repin craft-libs to the fix for windows that stay hidden (next + float-menu) 2026-11-25 18:19:04 +00: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
aiongg 9d214d6e88 Drawing focus comment: a click on a palette leaves the drawing focused 2026-11-25 15:50:21 +00:00
aiongg d26d9ca01f Repin craft-libs to storytold next aa401985d 2026-11-25 15:50:21 +00:00
aiongg c9286726ab Copy, Cut and Paste pressed in a floating panel reach the app 2026-11-25 15:15:06 +00: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
aiongg 138f447988 Ctrl+=, Ctrl++, Ctrl+- and Ctrl+0 change the interface scale
The keys (Cmd on macOS) step the Options interface scale by a tenth, within its limits, and Ctrl+0 sets it back to 100 %. They work while a text field or the command line has the keyboard, and a key the user gave to a command runs the command. In the browser they zoom the page.
2026-11-25 14:35:42 +00:00
aiongg e425c71c44 Enter and Space leave the drawing's right-click menus open 2026-11-25 14:20:12 +00: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 <[email protected]>
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
aiongg c3f691264a Repin craft-libs to storytold next d1bdf8e5da 2026-11-25 13:44:10 +00: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 <[email protected]>
2026-11-25 08:30:49 -05:00
aiongg aac7ae1cf2 A running command keeps Tab after a click on the palette or the status bar 2026-11-25 13:24:08 +00:00
aiongg 849e6fd5c4 The drawing takes the keyboard focus and keeps Tab while the command line has work for it
A press in the drawing, and a drawing that opens or becomes active, give the drawing the focus; a text field, a dialog
or a menu keeps it. The focused drawing keeps Tab (KeepKeys::Tab) only while a command runs, text is typed, value boxes
are live or a snap marker is under the cursor. A bare Tab with nothing focused is the framework's: capture_tab is gone.
2026-11-25 13:06:11 +00: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 <[email protected]>
2026-11-25 07:56:36 -05:00
aiongg 9e5889b782 Tab reaches the palettes from the document tabs
The drawing's host canvas is declared with the id of the drawing's own widget, so egui keeps the focus Tab gives it.
While the drawing is the focused Tab stop, the command line and the shortcuts take the keyboard as with nothing focused.
2026-11-25 12:38:02 +00: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
2ez4gcxandClaude Opus 5.5 3439895ec3 Vietnamese catalog: approved terminology and the 249 missing strings
Phase 1 of storytold/craft-i18n#401 for CADCraft's own vi.tsv.

- 44 existing rows: the 8 terms raised in #401 (14 rows), "nạp" for
  loading into CADCraft (8 rows), Boundary as "Đường bao" (2), the 17
  rows left in English (Find and Replace, Magenta, Working Set, Feet)
  and 3 rows kept consistent with them. "tỉ lệ" stays as spelled.
- 249 new rows, one for each string the translation_gaps report listed
  (Dimension Style Manager and dimension properties, keyboard shortcuts,
  right-click customization, Array dialog, UCS, ALIASEDIT, commands),
  grouped under comments. The report now prints "vi: nothing missing".
- ATTRIBUTION.md: the phase 1 changes were reviewed by a native
  Vietnamese speaker; older rows are not yet proofread in full.

Translations are written from the meaning of the English strings and
their use in the code (clean room).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 17:58:46 +07:00
2ez4gcxandClaude Opus 5.5 04c880e96f fix(doc): key the layer and block name index by the folded name, not a hash
The index mapped a hash of the case-folded name to the first entry of that hash, and scanned the
table when the entry's name differed. On wasm32-unknown-unknown, std's RandomState takes its keys
from a stack and a heap address (library/std/src/sys/random/unsupported.rs), so a crafted file
could pick colliding names and keep every lookup a full scan on the web build (review of #3484).

The index is now a BTreeMap from the name's bytes with ASCII letters lower-cased to the first
entry of that name. eq_ignore_ascii_case compares exactly those bytes, so a lookup returns what the
scan returns without a fallback, and costs O(log N) comparisons whatever the names are. Short
names are folded on the stack. Measured, one search costs about a scan of 100 names and a build
about 100-350 scans, so tables are indexed from 128 entries and after 256 scans since their last
change.

A new test builds the index alone and finds the first entry of every name: case variants, names
that differ after a long shared prefix, names of 64 bytes and longer, non-ASCII names and the empty
name. The cost test now uses 60 000 names and a 10 s bound (166.6 s on main).

Part of #1924 (F-04).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 16:39:36 +07:00
2ez4gcxandClaude Opus 5.5 a34ebd0bd0 Match attributes to their definitions by tag in one lookup (part of #1923)
One block reference with A attributes of a block with K attribute
definitions cost A x K tag comparisons wherever they are matched: the
extents (constant values a reference carries, the layer of an attribute
without its own), the renderer's constant values (per MINSERT copy), the
DXF writer (ATTRIB properties, MULTILEADER block-content values), BURST,
ATTSYNC/BLOCKREPLACE and the dynamic-grip preview. Crafted 16k x 16k and
32k x 32k files took 2-28 s to open, draw or save in a dev build.

TagKey compares and hashes a tag without ASCII case, as
eq_ignore_ascii_case does; Block::attdefs_by_tag and
Insert::attribs_by_tag keep the first definition or attribute of a tag,
as the scans' find/any did. Each site builds the map once and looks each
tag up once. Outputs of the crafted files are byte-identical.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 15:26:03 +07:00
aiongg c089fdff1a Paste tests that run only the shortcut table don't install the runtime (no drawing keeps the clipboard events in egui) 2026-11-25 07:19:23 +00:00
2ez4gcxandClaude Opus 5.5 3532ddf65e fix(doc): look layers and blocks up by name through an index, so crafted files don't open in quadratic time
Drawing::layer scanned every layer, and Drawing::block scanned every block when the exact name
missed. Both run once per entity while a drawing is read, measured and inspected, so a file with N
layers, or with N blocks and N references to blocks it doesn't have, opened in N² comparisons
(40 000 missing-block references: 75.7 s in a dev build; 40 000 layers: 6.8 s).

Drawing::layers is now a NamedList<Layer> and Drawing::blocks a NamedMap<Arc<Block>>. They read
and change as the Vec and BTreeMap they wrap, and keep an index from a keyed hash of the
case-folded name to the first entry of that hash. A hit is checked against the name and falls back
to the scan, so results are the same as before: same case rule, first match in table order, exact
block name first. Every change goes through DerefMut, which drops the index; a clone (undo
snapshot) shares it. The index is built only for tables of 64 entries or more, after 32 scans
since the last change, so code that changes a table between lookups costs what it did.

Part of #1924 (F-04).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 14:07:49 +07:00
2ez4gcxandClaude Opus 5.5 7867366a14 DXF read: keep at most 256 dash elements per linetype
An LTYPE record kept every dash element a DXF listed, while a .lin file
is capped at MAX_LINETYPE_ELEMENTS (256). The renderer clones the whole
linetype for every object drawn with it and walks the pattern on every
run, so a crafted 400,000-element pattern made a PNG export of 250
lines take 18-22 s on a dev build (8 s or less with this change; the
rest is the renderer walking 1M gap steps per line).

ltype_pattern now stops at the 257th element: the linetype keeps its
first 256 elements, the text and shapes of the dropped ones are not read,
and one read note counts the linetypes cut. Saving writes the elements
kept. A DWG reaches the reader as DXF but cannot carry more than 255
elements (one-byte count), so the cap does not fire there.

Part of #1923 (F-05).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 13:49:49 +07:00
aiongg ad1446c302 Allow egui::ComboBox: craft-libs next has no craft_ui::ComboBox 2026-11-25 06:47:06 +00:00
aiongg 7eb9401f08 cargo fmt 2026-11-25 06:40:11 +00:00
aiongg 69a040acc6 Merge main into the minimal port
Conflicts: Cargo.toml (kept the next/egui pins for every craft-libs entry, including main's new craft-csv and hayro-interpret/cmap/postscript patches), apps/cadcraft/src/main.rs (port's framework frame decision and apply_frame with main's os_window identity, persistence path and exit hook), crates/ui-egui/src/updates_ui.rs (next's argument-free check calls with main's check_updates_at_start gate). Main's new tests and dialogs switched to install_headless and escape_pressed.
2026-11-25 06:38:00 +00:00
aiongg 2282d11b37 Repin egui to storytold b15ffe9bfc (what craft-libs next pins) 2026-11-25 06:32:55 +00:00
aiongg d659315743 Repin craft-libs to storytold next 16001e7210 and egui to storytold b15ffe9bfc 2026-11-25 06:31:24 +00:00
Tanish Manku d7df84316f Merge #3288: SCALE Reference Points/Copy and grip scaling of heights 2026-11-24 22:02:14 -07:00
vantruong-dang 23e5688a6f fix(cmd): mark SCALE Reference new-length prompt with distance() 2026-11-25 11:26:15 +07:00
vantruong-dang faba6b7e1e Merge remote-tracking branch 'origin/main' into fix/scale-reference-points
# Conflicts:
#	crates/ui-egui/src/cmdline.rs
2026-11-25 11:26:04 +07:00
2ez4gcxandClaude Opus 5.5 5bff714e00 ARRAY counts: withdraw the ARRAYEDIT measurement claim
b781f047 said AutoCAD 2024 was measured at ARRAYEDIT's columns, rows
and items. That measurement was made after the clean-room standard of
20 November (one agent session must not both operate AutoCAD and write
code), so the claim is withdrawn.

The module doc now lists only ARRAYRECT's rows and columns,
ARRAYPOLAR's items and rows, and -ARRAY's rows and items as measured.
The arrayedit_counts doc says ARRAYEDIT's counts go through the same
count() parser in crates/engine/src/cmd/array.rs, so they refuse and
take the same texts; no AutoCAD measurement of ARRAYEDIT is claimed.
Comments only: the test logic and the engine code are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 10:41:49 +07: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 <[email protected]>
2026-11-24 22:14:11 -05:00
vantruong-dang cd5620a75d Merge remote-tracking branch 'origin/main' into fix/scale-reference-points
# Conflicts:
#	crates/engine/src/cmd/modify.rs
2026-11-25 10:02:17 +07: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
2ez4gcxandClaude Opus 5.5 c4f139ac50 Merge main into fix/spline-closed-autocad
Conflict in crates/engine/tests/it/spline_options.rs, where both sides
appended tests: keep reverse_keeps_a_closed_spline_seam and main's SPLINE
CV method tests (#3456).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 09:02:43 +07: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
aiongg 9ea307ede8 Capture tests: frames run the app's raw input hooks; one geometry for the admission test
The capture rig ran note_raw_geometry alone, so the framework never got
the Options interface scale (FrameInput's Scale, given in before_input)
and egui's zoom stayed 1: the settled-scale test saw 800×600. It now runs
raw_input_hook and before_input, as the desktop app does.

The admission test reseeded the geometry for each request, an identity
change that the next drain rejects queued requests for; it now admits
all four against one geometry, so all four issue and stay undrained.
2026-11-24 19:28:13 +00:00
aiongg c125e9ebb8 Repin craft-libs to 9fd8b0cdaa; frame-only work and captures skip passes that will run again 2026-11-24 19:08:26 +00:00
aiongg ddee4e5bec Tests on next: clipboard rig without the runtime, wheel rig with the frame input, QuickCalc field under its panel, traversal from a focused control, left-edge drop case 2026-11-24 17:40:53 +00:00
aiongg 092ab07e66 Repin craft-libs to next-host-input 3ad64a26ea 2026-11-24 17:06:04 +00:00
aiongg 5195d9e5c8 Screenshots need no egui import on the web; iconic-column test reads the icons right of the drawing 2026-11-24 16:57:16 +00:00
aiongg 4f4a3e94b6 Tests: install the runtime in harnesses that run the app's UI; dock tests on next's model
Harnesses and bare contexts that run CadApp::ui install the runtime headless; rigs that
run the raw hook also run before_input. Dock tests use the workspace accessors, next's
action constructors and the tabs' accessible names; tests of the old renderer's hit rects,
divider ids and drag bar are removed.
2026-11-24 16:47:31 +00:00
aiongg 68de3797cc Host the craft-ui runtime from CADCraft's eframe App on craft-libs next
The runtime is installed in the desktop and web shells, before_input runs in the raw hook,
the close path decides in embed::logic, and the interface scale is the runtime's RootEnv
scale. The dock is next's DockArea over the saved workspace with CADCraft's panel bodies
and the drawing as its canvas group; ui.dock keeps its JSON vocabulary. Update dialogs run
on a DialogHost, the macOS title row is shell::TitleBar, screenshots use the runtime's
screenshot slot, and Escape with nothing focused is read as the window's cancel.
2026-11-24 16:47:31 +00:00
aiongg b6ee77e3ac Cargo.lock for the next pins (rustix 1.1.6) 2026-11-24 16:35:24 +00:00
aiongg 180ff4471d minimal-port rewrite: 99 edits (dock rename 43, combo 40, dock 10, split rename 3, deps 2, split 1) 2026-11-24 16:27:10 +00:00
aiongg 8fe5682b63 minimal-port repin: 35 edits (revs 30, features 5) 2026-11-24 16:26:54 +00:00
2ez4gcxandClaude Opus 5.5 bc976e9bde Merge main into fix/pline-undo-plinewid
Conflict in crates/engine/src/cmd/draw/line_pline.rs PlineM::begin():
keep main's drawing elevation (#3423) and the branch's PLINEWID start
widths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 08:57:36 +07: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
vantruong-dang 7819b4b65a fix(ui-egui): separate pointer-box display from dyn_frame point completion 2026-11-21 19:02:26 +07:00
vantruong-dang 9efc5e3541 fix(ui-egui/cmdline): keep dyn_frame active for Prompt::distance prompts 2026-11-21 18:14:51 +07:00
vantruong-dang 1203f087d3 Merge remote-tracking branch 'origin/main' into fix/scale-reference-points
# Conflicts:
#	crates/ui-egui/src/cmdline.rs
2026-11-21 17:41:09 +07: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
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
2ez4gcxandClaude Opus 5.5 b781f04784 ARRAY counts: test ARRAYEDIT's counts and the MAXARRAY bounds
ARRAYEDIT's columns, rows and items, measured in AutoCAD 2024's core
console, refuse 5.0, 5., 4.5, 1e1 and 8/2 and take +5, 05 and 5, as the
other count prompts do. A count runs from 1 to the MAXARRAY limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 21:19:36 +07:00
2ez4gcxandClaude Opus 5.5 c40fc740ab Merge main into fix/array-count-integer
Conflict in crates/engine/tests/it/main.rs: keep both array_counts and
main's array_key_point (#2368).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 19:21:22 +07:00
2ez4gcxandClaude Opus 5.5 fb20f102df Merge main into fix/spline-closed-autocad
Conflict in crates/io/src/dxf_read/entities.rs: keep the branch's
keeps_closing_tangent() and main's hatch curve budget parameter (#3306).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 18:06:39 +07:00
2ez4gcxandClaude Opus 5.5 ee13c648df Merge main into fix/linetype-dash-layout
Conflict in crates/render/src/wide.rs dashed(): keep main's point budget
for segments() (#3306) and the branch's closed PLINEGEN anchor.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 17:34:35 +07: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
vantruong-dang 573488d5a3 fix(cmd): support SCALE Reference Points and Copy, disable pointer boxes on numeric prompts, and scale heights in grip SCALE 2026-11-19 16:47:55 +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
2ez4gcxandClaude Opus 5.5 62a1a23288 Prompt: declare NO_OR as a slice
This PR and #2915 each add a prompt to NO_OR and raise its array length
from 28 to 29, so with both merged the array holds 30 entries under a
length of 29 (E0308), whichever lands first. A slice has no length to
keep in step; both PRs make the same change to this line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 09:06:54 +07:00
2ez4gcxandClaude Opus 5.5 12b7742384 JOIN: set the new polyline's elevation without with_z
#2548 rewrites BREAK and deletes with_z; with both PRs in, this branch's
call to it no longer compiled (E0425), whichever landed first. Set the
elevation on the polyline lwpoly() makes instead: the same value, and
nothing of this branch depends on with_z any more.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 08:59:04 +07:00
2ez4gcxandClaude Opus 5.5 927a417255 Merge branch 'fix/spline-file-tangent-length' into fix/spline-closed-autocad
Brings chord_interpolate's start-condition row ahead of the fit-point
rows, so its system stays banded. chord_closed builds closed chord fits
through it: control points are bit-identical, and a closed fit of 1,000
points took 17.4 -> 3.2 ms (dev profile).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 08:02:36 +07:00
2ez4gcxandClaude Opus 5.5 fc838dce98 SPLINE: assemble the chord fit's start condition before its points
chord_interpolate added the start tangent or zero-curvature row after
all the fit-point rows, so its column-0 entry sat in row n and solve
swept the whole width. With the start row first, the system has a lower
and upper bandwidth of at most two. The control points come out
bit-identical; a fit took 17.5 -> 4.4 ms at 1,000 points and
414 -> 135 ms at 4,000 (natural ends, dev profile).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 07:58:59 +07:00
2ez4gcxandClaude Opus 5.5 a1142566b8 SPLINE: assemble the chord fit's start condition before its points
chord_interpolate added the start tangent or zero-curvature row after
all the fit-point rows, so its column-0 entry sat in row n and solve
swept the whole width. With the start row first, the system has a lower
and upper bandwidth of at most two. The control points come out
bit-identical; a fit took 17.5 -> 4.4 ms at 1,000 points and
414 -> 135 ms at 4,000 (natural ends, dev profile).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 07:28:58 +07:00
2ez4gcxandClaude Opus 5.5 db8f6cc6e4 Merge main into fix/spline-fit-autocad
Main's banded solve came with a dense-solver oracle test whose cases all
use chord-length knots; on this branch those go through
chord_interpolate, so the test no longer reached interpolate. Extend it
with square-root and uniform knots, with and without end tangents, and
a 1000-point square-root fit (the same change as on
fix/spline-file-tangent-length).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 07:08:12 +07:00
2ez4gcxandClaude Opus 5.5 4b76e4a305 Merge branch 'fix/spline-file-tangent-length' into fix/spline-closed-autocad
Brings in main f9c0c96e. Main's clippy-pedantic refactor of
spline_fit.rs conflicted in three places: fit_sanitized takes main's
if-let form and keeps closed_fit's tangent argument, closed_fit keeps
main's #[expect] on its four-parameter signature, and the closed
tolerance test keeps main's bit-exact assert with this branch's comment.

Closed chord-length fits go through chord_closed on this branch, so the
dense-solver oracle's comments say so, and an n=150 closed square-root
fit keeps the large cyclic matrix compared.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 06:24:09 +07:00
2ez4gcxandClaude Opus 5.5 17888ad5c6 Test the dense-solver oracle on interpolate's fits too
With chord-length knots, open fit-point splines are now built by
chord_interpolate, so fits_are_bit_identical_to_the_dense_solver no
longer reached interpolate (a panic there left the test passing). Add
square-root and uniform knots, with and without end tangents, and a
1000-point square-root fit, so interpolate's matrices, its tangent rows
and the closed cyclic interpolation stay compared with the dense solver.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 06:01:28 +07:00
2ez4gcxandClaude Opus 5.5 0edd056e8e Merge main into fix/spline-file-tangent-length
Main's clippy-pedantic refactor of spline_fit.rs restyled the body of
Spline::fit_with; this branch had moved that body into fit_sanitized.
Keep the split and apply main's if-let form inside fit_sanitized.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 05:30:27 +07:00
2ez4gcxandClaude Opus 5.5 74c183415b Merge main into fix/linetype-dash-layout
Brings the branch up to main ca87680f. The one conflict is in
crates/render/src/linetype_text.rs, texts(): main's #2744 adds a point
allowance for the labels of a run, and this branch starts the run a period
before its start. Both are kept: the allowance is charged for each label
placed, and elements before the run's start are skipped before any charge.
Main's new test placed_labels_stop_at_the_point_allowance now passes the
Layout argument this branch added to texts().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 11:54:27 +07:00
2ez4gcxandClaude Opus 5.5 67c78743dd DXF: write the closing fit point after a closed list ending with its first
The reader drops one closing fit point from a closed spline, so the writer
now adds one whenever the reader will drop one: also after a list that
already ends with its first point (a kink where it closes, as a file can
give it). Before, [A, B, C, A, A] came back as [A, B, C, A], and a later
fit-point edit smoothed the seam. Three points ending with the first are
still written as they are, since the reader keeps them so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 13:56:20 +07:00
2ez4gcxandClaude Opus 5.5 45300ee3a2 Merge main into fix/pedit-heights
Brings the branch up to main 6d744887, which has #2954's fix for
mtext::tests::strips_formatting, so the gate runs on a main that passes.
No conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 12:52:16 +07:00
2ez4gcxandClaude Opus 5.5 d6dc7131c3 Merge main into fix/spline-closed-autocad
Brings the branch up to main 6d744887, which has #2954's fix for
mtext::tests::strips_formatting. The one conflict is in
crates/geom/src/nurbs.rs, where main makes the derivative allocation-free
(#2434, basis_pair_into) and this branch adds reversed_loop. The merged
file is main's plus exactly this branch's own lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 11:08:03 +07:00
2ez4gcxandClaude Opus 5.5 96e62b4632 PEDIT Join: only objects in one plane with the polyline, as AutoCAD 2024
AutoCAD 2024 joins only objects that lie in one plane with the polyline:
the plane the polyline and every line picked share, if they share one,
else the polyline's own. Measured: a triangle at Z 5 whose last side slopes
to Z 0 leaves that side out; a sloped line followed by a line turning off
their vertical plane joins neither; a sloped line followed by an arc joins
the line only. Before, a sloped line joined wherever its end met the chain
at the same height.

Also, after review: tests for the sloped line drawn either way, a chain
meeting its start at another height, arcs below Z 0 and mirrored above it,
thickness, the joined polyline's normal and bulges, fuzz in plan only, and
an exact pick on the arc; doc comments for the plane rule, the height
tolerance and tilted arcs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 04:04:46 +07:00
2ez4gcxandClaude Opus 5.5 e20f5ed590 PEDIT: polylines at their objects' height; Join only at the same height
PEDIT turned a line or an arc into a polyline at elevation 0, so a line at
Z 5 dropped to Z 0, and its Join took any object meeting the polyline in
plan. As AutoCAD 2024 does (measured):

- Convert puts the polyline at the line's height or the arc's centre
  height and keeps the thickness; a line's polyline faces up whatever the
  line's normal, a mirrored arc's keeps its normal and runs as the arc
  does in its own coordinates.
- PEDIT's Join takes an object only where the ends meet at the same
  height, and none facing the other way (an arc or polyline whose normal
  points down Z where the polyline's points up, or the other way round;
  a line counts as facing up). After a sloped line, the chain continues
  from its far end's height.
- Multiple's Join leaves out objects facing the other way too, but takes
  them at any height.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 21:19:21 +07:00
2ez4gcxandClaude Opus 5.5 6133dc60bb JOIN: a new polyline stays at the source's height
JOIN made the new polyline from a line or arc source at elevation 0, so
lines at Z 5 moved down to Z 0. It now takes the source's height, as a
polyline source keeps its elevation with a sloped line joined to it
(AutoCAD 2024, measured), negated when the polyline inherits a normal
pointing down Z. The new polyline itself wasn't measured: the core
console's JOIN never makes one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 09:02:04 +07:00
2ez4gcxandClaude Opus 5.5 8b1adcd8d5 MINSERT: test that JSON null counts and distances are taken as missing
A null rows or columns is 1 and a null rowSpacing or columnSpacing is 0,
as when the key is missing. Each count is tested null on its own; the
distances on a 2 x 2 grid, since one row or column drops its distance
anyway.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 23:39:33 +07:00
2ez4gcxandClaude Opus 5.5 19dcf74419 JOIN: ends meet at the same height; objects facing the other way stay out
JOIN compared chain ends in plan only, so an end meeting another only in
plan at another height was joined and collapsed onto the source's
elevation. Each piece now carries its ends' world heights (a line's own
Z, an arc's centre Z, a polyline's elevation, negated when its normal
points down Z), turned round with the piece, and ends must meet at the
same height too.

Onto a polyline source, an object facing the other way stays out: an arc
or a polyline faces its normal, a line always counts as facing up.
AutoCAD 2024 (accoreconsole, measured) joins a line with normal 0,0,-1
to a polyline facing up, no line to a polyline facing down, and an arc
or polyline only when it faces the polyline's way. A line or arc source
keeps the old behaviour: the core console can't measure it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 23:18:18 +07:00
KnottyDyesandClaude Opus 5.5 b573490901 Docs: qualify the README DWG read claims
The format-parity table marks R13 and R14 DWG reading as untested and
2018 as tested only on synthetic files; say the same in the README.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:13:35 -07:00
KnottyDyesandClaude Opus 5.5 5f4c2ed819 Docs: SAVEAS version overrides the kept version and is remembered
Say so wherever the docs describe a drawing keeping its own version,
as file-format-parity.md already does: save_as writes an explicit
version into $ACADVER, so later saves use it too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:13:35 -07:00
KnottyDyes 203ed93f51 Docs: describe DXF and DWG save-version selection 2026-11-04 09:13:35 -07:00
2ez4gcxandClaude Opus 5.5 20a9ac7433 MINSERT: JSON rows and columns are whole numbers
The JSON form read rows and columns as numbers with no fraction, so 2.0 and
1e2 were counts. They must now be JSON whole numbers from 1 to 32767, as the
array commands' JSON counts already are; missing or null is still 1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 22:08:20 +07:00
2ez4gcxandClaude Opus 5.5 22b2f7a5a9 Merge main into feat/copy-autocad; NO_OR is 29 long
main and this branch each added a row to NO_OR in prompt.rs ("Enter
option" and "Enter a copy mode option") on top of the same 27, and both
declared 28; the merge has 29 rows, so the declared length is now 29.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 20:51:41 +07:00
2ez4gcxandClaude Opus 5.5 ca3ff7997f INSERT/MINSERT: take points at the scale, rotation and spacing prompts
These prompts ignored a point. AutoCAD 2024 (measured on INSERT and
MINSERT) takes one as the first of two at the Scale, X, Y, Z and Rotate
presets and at MINSERT's column spacing, asking "Specify second point:"
(the distance is the scale or spacing, the direction the rotation; Enter
there keeps a preset's default); at XYZ's Z a point gives its distance from
the insertion point; Y scale refuses a point. They now do the same, with
AutoCAD's messages at each prompt ("Value must be nonzero.", "Requires
numeric distance or two points.", "Requires valid numeric angle or two
points.", "Requires numeric distance or second point.", "Requires numeric
value."). Exploded INSERT's scale takes a positive number only ("Value must
be positive and nonzero."). The Rotate preset still reads typed text as an
angle, so <<45 stays 45 degrees.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 20:33:17 +07:00
2ez4gcxandClaude Opus 5.5 a113667951 ARRAYPATH: no extra item where a closed path closes, by spacing
The JSON spacing form made floor(length / spacing) + 1 items on every path,
so on a closed one the last sat on top of the first (or nearer to it than
the spacing). AutoCAD 2024 fills a closed path with floor(length / spacing)
items and an open one with one more, at its end (measured with Fill entire
path on a closed and an open square and a circle). The spacing form now does
the same, letting length / spacing fall 1e-9 short for rounding.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 19:46:34 +07:00
2ez4gcxandClaude Opus 5.5 8af4b8a61b DIVIDE: take a whole number as typed for the number of segments
The count was read as a number with no fraction, so 5.0, 5. and 1e1 were
taken; a point gave its distance from the pick as the count; and Enter ended
DIVIDE. AutoCAD 2024 takes +5, 05 and 2 to 32767, and refuses all of those,
and 4.5, 1, 32768 and x, with "Requires an integer between 2 and 32767, or
option keyword." ("...32767." once Block has been chosen) and asks again
(measured). DIVIDE now does the same. MEASURE, which shares the prompt
machine, is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 19:05:56 +07:00
2ez4gcxandClaude Opus 5.5 223beb2fb8 SPLINEDIT: take a whole number as typed for Elevate order
"Enter new order" took a number with no fraction from 1 to 1000, so 5.0 and
1e1 were taken, and a point went back to the vertex menu without a word.
AutoCAD 2024 takes +5 and 05, keeps the order on 4 (a cubic's), and refuses
5.0, 5., 1e1, 4.5, 3, 27 and a point with "Requires an integer between 4
and 26."; the range starts at the spline's own order (measured at orders 4
and 5). The prompt now does the same, and the JSON form's elevate uses the
same wording. The prompt's logic moves to input_order(), which keeps
SplineditM::input under clippy's complexity limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 19:02:20 +07:00
2ez4gcxandClaude Opus 5.5 20463574de COPY: MAXARRAY doesn't limit Array; refuse a point at the count
AutoCAD 2024 doesn't apply MAXARRAY to COPY's Array: with MaxArray 100000,
four lines and 26000 items made 104000 lines. The count is now 2 to 32767
whatever the selection, as AutoCAD asks it. A point at "Enter number of
items to array:" was ignored; AutoCAD refuses it with "Requires an integer
between 2 and 32767." (measured with a LISP point), and so does COPY now.

So that a large selection can't run out of memory, the copies (items after
the first, times the objects) stay within MAX_ARRAY_ITEMS, ARRAY's own limit
whatever MAXARRAY says, checked before anything is made.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 17:35:30 +07:00
2ez4gcxandClaude Opus 5.5 b44d5c3588 ARRAYPATH: refuse a JSON count or spacing it can't use
The JSON form read `count` with as_u64 and `spacing` with as_f64 and quietly
dropped what didn't fit: a count of 4.5, "8" or -3 made the default 6 items,
0 made 1, and a spacing of 0, -5 or "10" fell back to the count. They are now
refused as the other arrays' JSON forms refuse them: the count goes through
count_or (a whole number of at least 1) and the spacing through size_param (a
positive number). Missing or null keeps the defaults.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 16:50:40 +07:00
2ez4gcxandClaude Opus 5.5 35462869e6 SPLINEDIT: take a whole number as typed for the polyline precision
"Specify a precision <10>:" read a number from 0 to 99 and rounded it, so
5.0, 5. and 4.5 were taken. AutoCAD 2024 refuses those, and 1e1, 8/2, 100,
-1 and a point, with "Requires an integer between 0 and 99." and takes +5
and 05 (measured). A point used to convert with precision 10; it is now
refused too.

The JSON form clamped `precision` to 99 and read any other value as 10. It
now refuses a precision that isn't a whole number from 0 to 99; absent or
null is still 10.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 16:15:17 +07:00
2ez4gcxandClaude Opus 5.5 cf90a60626 MINSERT: take a whole number as typed for the rows and columns
The row and column counts were read as a number with no fraction, so 5.0,
5. and 1e1 were taken. AutoCAD 2024 refuses those with "Requires an integer
between 1 and 32767." and asks again, and takes +3 and 03 (measured at the
rows, and 5.0 and +3 at the columns). A point at these prompts was ignored
without a message; AutoCAD refuses it with the same message (measured with
a LISP point at the rows).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 15:39:35 +07:00
2ez4gcxandClaude Opus 5.5 81f8032255 OPTIONS: a refused change puts the same drawing back
Writing the header entries back went through doc_mut, whose copy on
write gave a clean drawing a new Arc, so a refused OPTIONS call marked
it changed. apply now keeps the drawing's Arc when SNAPUNIT or GRIDUNIT
is among the values and puts that same Arc back on a refusal; a call
that names neither never touches the drawing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 13:43:33 +07:00
2ez4gcxandClaude Opus 5.5 1d16e82a49 ARRAYPATH: the item count takes a whole number as AutoCAD 2024 does
"Enter number of items along path" read the count as a distance and cut
it to an integer, so 4.5 gave 4 items and 1e1, 8/2 and 3' were taken.
AutoCAD 2024 takes a whole number from 1 to 32767 in plain decimals
there (5, +5, 05, 5., 5.0) and refuses 4.5, 1e1, 8/2, 3', 0 and 32768
(measured); the count is now read the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 13:02:19 +07:00
2ez4gcxandClaude Opus 5.5 8ecf3e6cac ARRAY: counts take a whole number as typed, as AutoCAD 2024 does
The ARRAYRECT, ARRAYPOLAR, -ARRAY and ARRAYEDIT count prompts read a
number with no fraction, so they took 5.0, 4. and 1e1. AutoCAD 2024
refuses those, and 8/2, 3' and 4.5, and takes +3 and 03 (measured at
ARRAYRECT's rows and columns, ARRAYPOLAR's items and rows, and -ARRAY's
rows and items). The count is now read as a whole number.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 12:22:19 +07:00
2ez4gcxandClaude Opus 5.5 ab71b353d5 OPTIONS: reset puts every profile variable back; a refused change leaves the drawing's snap and grid
options::reset missed 15 profile variables (the Dynamic Input, selection
preview and area, grip, PICKSTYLE and MEASUREINIT settings), so a reset
left them as they were. It now restores all of them; SNAPUNIT and
GRIDUNIT, which the drawing keeps in its header, are still left alone.

apply is all or nothing, but a refused value left SNAPUNIT and GRIDUNIT
written to the drawing's header. Their raw header entries are now put
back as they were, or removed when the drawing didn't have them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 11:54:04 +07:00
2ez4gcxandClaude Opus 5.5 02dfd37d14 Merge main into fix/linetype-dash-layout
main added SHX shapes to complex linetypes in linetype_text.rs; this
branch lays linetype elements out with Layout and phase. Both are kept:
shapes go where texts and dashes go (centred on an open run), and
main's point budget counts only the elements placed. main's shape test
now expects the centred positions, as the text test does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:35:44 +07:00
2ez4gcxandClaude Opus 5.5 43207db68e QLEADER: refuse a width that overflows; name an unreadable JSON point
A width given by a point far enough away to overflow is refused with the
message typed text gets, and the width is asked again. In the JSON form, a
point that can't be read says so instead of saying `points` is missing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 05:02:43 +07:00
2ez4gcxandClaude Opus 5.5 69b214743d COPY: pin +3 and 03 at the array count, as AutoCAD 2024 takes them
AutoCAD 2024 takes "+3" and "03" at "Enter number of items to array:"
(measured: three items each), which the count's integer parse already
does. Say so in the comment and test it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 04:38:00 +07:00
2ez4gcxandClaude Opus 5.5 3c9b4be339 JOIN: whole objects by their ends, the circle question, the source's space
Measured in AutoCAD 2024's core console:
- Objects join whole, by their end points; a polyline is never split, and
  one met only at an inner vertex stays as it is. The source is the first
  pick JOIN can take (a circle picked first is passed over).
- Where an object meeting the chain at more than one place goes: a
  polyline by its first vertex if it can, before the chain rather than
  after; a line or an arc turned round if it can. A source that already
  ends where it starts still takes more; a join that closes the chain
  stops it; a source of no length takes nothing; a lone polyline whose
  ends meet stays open.
- Arcs that come round make a circle with no tolerance at the source's
  start, and the command line asks "Combined arc segments form a circle.
  Convert to circle? [Yes/No] <Yes>:" first; No leaves the arcs. The JSON
  form takes the default.
- A new polyline keeps another polyline's widths, and what JOIN makes
  goes in the source's space.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 04:36:45 +07:00
2ez4gcxandClaude Opus 5.5 762b64268b QLEADER at the command line, as AutoCAD 2024 runs it with its default settings
Up to three leader points, a text width (not remembered; a point gives its
distance from the leader's end), then lines of multiline text. The text
sits DIMGAP past the end: with the middle of its first line level with it
when the leader runs right (attachment 1), of its last line when it runs
left (attachment 9), whatever DIMTAD. A hook line DIMASZ long is added when
the last segment slopes and text follows. Enter at the first line leaves
the leader alone. Measured in AutoCAD 2024's core console. Alias LE, and a
JSON form.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 03:32:55 +07:00
2ez4gcxandClaude Opus 5.5 c2b2545d0a COPY: the array count takes digits only; mOde Enter keeps the mode shown; reset COPYMODE
AutoCAD 2024 refuses 4.0, 1e1, 8/2, 1' and 3" at "Enter number of items
to array:" (measured), so the count is read as digits, not as a number
with no fraction. Enter at the mOde prompt now runs COPY in the mode the
prompt shows, and OPTIONS reset puts COPYMODE back to 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 02:55:48 +07:00
2ez4gcxandClaude Opus 5.5 c36cc6af34 SPLINE: a closed spline keeps its seam and its tangent where it closes
Review of #2705: REVERSE turned a closed spline's whole fit list round
while the curve still started at the old first fit point. The DXF
writer, which writes a closed spline's fit points from the first one,
then wrote another seam, and the next fit-point edit moved it.

Measured with AutoCAD 2024 (accoreconsole) on SPLINE (0,0) (4,0) (6,3)
(1,4) Close:
- REVERSE keeps the first fit point first and turns the others round
  ([f0, f3, f2, f1]); it turns the tangent where the curve closes
  (12/13) round and reverses the control points and knots;
- SPLINEDIT Fit data Move, Delete (of the first fit point too) and
  Open keep that tangent instead of working it out again from the
  points.

So a closed fit spline with chord-length knots now keeps its tangent
where it closes as both end tangents, as AutoCAD keeps 12/13:
- refits, grips and SPLINEDIT take it;
- `Spline::reversed` keeps the seam first and turns the tangent round;
- the DXF reader keeps it for such a spline, and drops the curve's own
  tangents that the writer gives the others (periodic knots, a fit
  tolerance, a kink);
- SPLINEDIT Close still gives the closed curve its own tangent.
A new closed spline still ignores the tangents given with it.

Also:
- a closed kinked fit stores its fit points from the kink where the
  curve starts;
- the closing tangent is divided by its length, not normalised, so a
  short one is not a zero tangent;
- AutoCAD's 44 = 1e-10 (no fit tolerance) is read as 0, and a tolerance
  too tight to approximate with gives AutoCAD's chord-length build, as
  for an open spline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 01:54:22 +07:00
2ez4gcxandClaude Opus 5.5 03c8bac609 SPLINE: two fit points with a fit tolerance make the same cubic
AutoCAD 2024 builds a chord-length spline through two points as the cubic
with control points at the thirds whatever the fit tolerance (measured with
tolerance 1: the same control points and knots as with 0, only group 44
differs). The tolerance no longer turns it into a line. The comment on the
interpolation fallback now says what was measured, and the test compares
the result with the tolerance-0 fit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 01:36:48 +07:00
2ez4gcxandClaude Opus 5.5 a9a3b35c91 feat(engine): COPY with COPYMODE, Multiple/mOde, Array and Fit as AutoCAD 2024
COPYMODE (profile, 0 copies until Exit, 1 makes one copy) and the base point
options mOde (sets it) and Multiple (this command only). Enter at the first
second point copies by the base point taken as a displacement. Array asks for
2 to 32767 items, the original included, and spaces them a second point apart
or, with Fit, up to it; Undo takes back the last placement, an array at once.
MAXARRAY caps an array's copies as it caps ARRAY's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 23:38:46 +07:00
2ez4gcxandClaude Opus 5.5 6c81995e03 fix(engine): JOIN onto the source object as AutoCAD 2024 does
Lines on the source's line make it one longer line and arcs on its circle
join counterclockwise from its start, both keeping the source's handle;
arcs that come round to within 1e-6 rad of its start make a circle on the
source's layer. An open polyline source keeps its handle, its own vertices,
elevation, PLINEGEN and (with only lines and arcs) constant width; other
polylines keep their bulges and widths, lines and arcs take the widths of
the source's vertex at that end. The tolerance is AutoCAD's measured 1e-6,
absolute at any coordinate size. The message names a line, arc or circle.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 23:23:26 +07:00
2ez4gcxandClaude Opus 5.5 99ae84f39c SPLINE: the preview adds no fit point with the cursor on the last one
A click on the last fit point adds nothing, but the preview still added
the cursor there, so it showed a corner the command would not make.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 21:34:08 +07:00
2ez4gcxandClaude Opus 5.5 04b56c4f4a Test the fit-option DXF roundtrip over the whole spline
Chord-length knots now run to the fit points' length rather than 1, so the
roundtrip check sampled only the first part of those splines. It now
samples the spline's own domain and checks the domain survives the file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 20:53:28 +07:00
2ez4gcxandClaude Opus 5.5 cbf79599e2 STRETCH: a fit-point spline moves its fit points and is fitted again
AutoCAD 2024 (accoreconsole, entget after STRETCH of a spline stored with
fit points only) moves the fit points inside the area and fits the spline
through them again, keeping its fit data (70 = 1064, 74 = 4); with all of
them inside, it moves whole. Here such a spline moved whole by its first
grip, or not at all. The test pins AutoCAD's fit points for three windows:
the last fit point, a middle one, and the whole spline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 20:38:34 +07:00
2ez4gcxandClaude Opus 5.5 de9f9ccc93 RECTANG: test corners at the limit where they still fit
AutoCAD 2024 (accoreconsole, entget of a 4 by 2 rectangle) keeps corners
exactly as long as the shorter side allows: fillet 1, and chamfer 1 + 1 or
1.2 + 0.8, still fit. A hair longer (fillet 1.0001, chamfer 1.2 + 0.81) and
the corners stay square, each still written twice. The rule already matches;
this pins the six measured rectangles, including which way the two chamfer
distances run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 20:35:08 +07:00
2ez4gcxandClaude Opus 5.5 25afec0fa9 Merge main into fix/stretch-arcs-bulges-splines
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 19:53:36 +07:00
2ez4gcxandClaude Opus 5.5 1b16f3caeb Merge branch 'fix/spline-file-tangent-length' into fix/spline-closed-autocad
Stacks the closed fit-spline change on the DXF tangent-length one (#2703).
Both change the SPLINE reader; the merged reader keeps both rules:

- an open spline keeps a file's 12/13 tangents with their length and is
  rebuilt from fit data with them as the end derivatives (#2703);
- a closed spline drops AutoCAD's closing fit point and takes its
  closing tangent from the curve, not from 12/13.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 18:48:24 +07:00
2ez4gcxandClaude Opus 5.5 8178e578c2 SPLINE: a small uniform scale keeps a spline's end tangents
`transform` dropped a tangent that the map shrank to under EPS of the
tangent's own length. So SCALE 1e-10 lost a (100, 0) tangent, although
the map is invertible.

The check now compares with the map's largest axis scale. An invertible
uniform scale, however small, keeps the tangent. A singular map, or one
that squashes the direction to under EPS of that scale, still drops it.
`scale_factor` (sqrt |det|) would not do: it is 0 for a singular map, so
rounding noise would survive as a direction.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 18:46:22 +07:00
2ez4gcxandClaude Opus 5.5 fe1c3eeeab SPLINE: a tangent too short to normalise is dropped, not zero
`sanitized` kept tangents longer than 1e-12, but `Vec2::normalized`
returns zero up to 1e-9, so a direction between the two was stored as
Some(ZERO): a zero end derivative instead of no tangent. Such a direction
is now dropped.

`transform` scales a tangent by the lengths instead of going through
`normalized`, so a short tangent from a file survives MOVE, ROTATE, SCALE
and MIRROR. A map that flattens its direction still drops it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 18:00:43 +07:00
2ez4gcxandClaude Opus 5.5 93e2255722 SPLINE: closed fit-point splines built as AutoCAD 2024 builds them
A closed spline through fit points with chord-length knots and no fit
tolerance is now the cubic AutoCAD 2024 builds (measured with
accoreconsole): the open chord-length interpolation through the fit
points and back to the first, clamped, with the same unit first
derivative at both ends. That tangent is the derivative at the first
point of the cubic through the first four points of the loop, with
square-root-of-chord parameters.

AutoCAD flags this spline periodic (group 70 bit 2) although its knots
are clamped: it sets the bit from the curve, the same first derivative
where it closes. `Spline::is_periodic` now means that (closed and smooth
where it closes); the knot shape it meant before is `Spline::wraps`
(unclamped knots, control points wrapping round), which SPLINEDIT uses
for its control-point edits.

DXF: AutoCAD rebuilds a spline with fit data from its fit points and end
tangents, and opened a closed spline written with its fit points once
as an open spline. The writer now adds the first fit point again at the
end and the tangent where the curve closes as 12 and 13, as AutoCAD
writes it; the reader drops the closing point and takes the tangent from
the curve. AutoCAD reads the written spline back as its own (70 = 1067,
the same control points).

Closed splines with square-root or uniform knots, or a fit tolerance,
are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 17:44:41 +07:00
2ez4gcxandClaude Opus 5.5 5513565da9 SPLINE: a file's end tangents count with their length, as in AutoCAD 2024
A DXF SPLINE stored with fit points and 12/13 tangents only is rebuilt
with each stored vector as its end derivative, length included: AutoCAD
2024 does so (12 = (0, 3) gives control points 2.67 from those of the
unit (0, 1)). The spline keeps the vector, so it is written back as read.
Refits (grips, SPLINEDIT, STRETCH) use it as stored, and transforms turn
it and keep its length, as AutoCAD's MOVE, ROTATE, SCALE, MIRROR and
SPLINEDIT Fit data Move do.

SPLINE, SPLINEDIT and the JSON options still take tangents as unit
directions: fit_with normalises them, and SPLINEDIT's input is already
normalised.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 17:13:41 +07:00
2ez4gcxandClaude Opus 5.5 9a6f025c47 SPLINE: open fit-point splines built as AutoCAD 2024 builds them
An open spline through fit points with chord-length knots and no fit
tolerance is now the cubic AutoCAD 2024 builds (measured with
accoreconsole, `entget` of the control points and knots):

- the knots are the running chord length, not normalised, with the fit
  points' own parameters as the interior knots;
- there are two control points more than fit points: an end with a
  tangent has it as its first derivative, an end without one has no
  second derivative (with one tangent too);
- two fit points without tangents make a cubic with its control points
  at the thirds, no longer a line.

SPLINE also leaves out a click on the point before, as AutoCAD does,
instead of storing a repeated fit point (a kink).

Closed splines, the other knot parametrisations and fit tolerance are
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 16:28:16 +07:00
Aldo ZarateandClaude Opus 5.5 06491fc757 Merge upstream/main into perf/cjk-text
ttf.rs keeps both test modules: the thread cache's and main's font
directory scan.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 22:03:34 -06:00
2ez4gcxandClaude Opus 5.5 897f53c7b3 Merge main into fix/linetype-dash-layout
After #2603, dashes are laid out only with Options::linetypes on: the
runs stroked with a layout (open, or closed from an anchor) and the
polyline centre line keep that check, so hit tests still draw lines
whole.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 07:40:25 +07:00
2ez4gcxandClaude Opus 5.5 97b531eaae RECTANG: Area with cut corners, oversized corners, Rotation as AutoCAD takes it
Three rules measured in AutoCAD 2024 that main's RECTANG does not follow:

- Area sizes the rectangle so that its outline, corners cut, encloses the
  area: _C 1.5 2.5 ... _A 1442.93 _W 35.535 has length 40.817, the
  area plus 2 x 1.5 x 2.5 over the width; a fillet adds (4 - pi) r^2.
  When the corners then don't fit, they stay square and the area is
  the full rectangle's.
- A fillet or chamfer too large for the shorter side leaves each corner
  as two coincident vertices, eight in all, as AutoCAD stores them.
- A typed Rotation is an amount turned in the ANGDIR sense from +X,
  ANGBASE aside: with ANGBASE 90 and ANGDIR 1, 30 turns the rectangle
  30 degrees clockwise. The modes line and the prompt's default show it
  as the drawing shows angles: "Rotation=120.00", "30d30'" with AUNITS 1.

The fit test is one function, shared by the vertices and Area. Of the
40 measured cases that set every mode, main's RECTANG matches 33; this
matches all 40.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 10:59:37 +07:00
2ez4gcxandClaude Opus 5.5 b872742e42 Merge main into the RECTANG fix, keeping #2554's RECTANG
#2554, now in main, rewrote RECTANG's vertex order, corners and
remembered modes along the same measurements as this branch. The
conflicts are resolved by taking main's RECTANG as it is. The next commit
brings back, on top of it, the rules this branch measured that #2554
left out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 10:59:30 +07:00
2ez4gcxandClaude Opus 5.5 b91fa88224 Linetypes: a plot or export keeps the dashes of a run over 50,000 periods
The 50,000-period guard is for a display zoomed out a lot, so it now applies only where there
is a level of detail (min_pattern above 0). A plot or export has none and keeps the pattern on a
run of any length, bounded by the two-million-element work limit; linetype text follows, through
phase. This is the plot exemption of #1277 (#1069) in the new layout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-31 08:41:26 +07:00
2ez4gcxandClaude Opus 5.5 3e8f468fe3 Linetypes: anchor a closed PLINEGEN run at its second vertex when it coincides with the first
The anchor was the length of the first drawn segment, so when the first two
vertices coincide (Polyline::segments leaves that pair out) the pattern was
anchored at the third vertex. It is now the chord length from the first
vertex to the second (wide::second_vertex_at), 0 for that pair, and the
thin run and the wide band share it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 22:57:33 +07:00
2ez4gcxandClaude Opus 5.5 cc69082a85 PLINE test: check PLINEWID after Width before Halfwidth
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 19:46:51 +07:00
2ez4gcxandClaude Opus 5.5 e6f2ea0405 Linetypes: keep the cap on pattern elements laid out
The rewritten layout capped runs at 50,000 periods but dropped the
earlier limit of 2,000,000 pattern elements, so a long pattern repeated
that often could produce millions of ranges. A run past either limit is
drawn continuous again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 19:21:33 +07:00
2ez4gcxandClaude Opus 5.5 d56ead7ca4 PLINE: the JSON form starts at PLINEWID too
A JSON pline without a width now takes PLINEWID, as the command does,
unless its vertices give their own widths; an explicit width, 0
included, is kept. FILLET and CHAMFER's JSON forms already fall back on
their variables the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 18:49:00 +07:00
2ez4gcxandClaude Opus 5.5 dc07a1032d Linetypes: anchor a closed run at its second vertex as it is drawn
The anchor of a closed PLINEGEN polyline is now the length of its first
segment tessellated at the drawing tolerance, as the run is measured,
not the arc length. With an arc first, a dash now starts right at the
second vertex, matching the filled band, which already measured it so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 18:46:54 +07:00
2ez4gcxandClaude Opus 5.5 6c2d37983e Linetypes: a wide polyline's centre line is dashed as a thin one
With fill off, a polyline with width draws its centre line. It now goes
through the same layout as a polyline without width: stretched around a
closed PLINEGEN one from its second vertex, along the whole of an open
PLINEGEN one, and restarted at each vertex otherwise.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 18:15:45 +07:00
2ez4gcxandClaude Opus 5.5 45f9b5653e Merge main into fix/pline-undo-plinewid
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 17:46:30 +07:00
2ez4gcxandClaude Opus 5.5 d79185ed8d RECTANG: take Rotation as AutoCAD does and show it in the drawing's units
Measured in AutoCAD 2024 with ANGBASE 90 and ANGDIR 1: Rotation 30 turns
the rectangle 30 degrees clockwise from +X (ANGBASE aside), and the next
RECTANG shows "Current rectangle modes:  Rotation=120.00", the rotation
from ANGBASE in the ANGDIR sense; the rotation prompt's default reads
<120.00>. With AUNITS 1, 30.5 shows as "Rotation=30d30'". The typed
rotation is now an amount turned in the ANGDIR sense, and both the
modes line and the default use the drawing's angle settings and units.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 17:17:16 +07:00
2ez4gcxandClaude Opus 5.5 6d3f63752b Linetypes: one ranges function that takes the layout
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 15:28:29 +07:00
2ez4gcxandClaude Opus 5.5 3944717ca2 Merge main into fix/linetype-dash-layout
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:54:02 +07:00
2ez4gcxandClaude Opus 5.5 c319cd7ae4 Linetypes: closed wide bands and gap-first phase follow the dashes
A closed PLINEGEN polyline with width now lays its pattern out like a
thin one: stretched around the run from the second vertex
(linetype::ranges_as with Layout::Closed), not centred as an open run.

phase() now gives where the periods of a gap-first pattern start when
the run leaves room for a piece of dash at its start: a gap before the
second element at x, as gap_first lays them, so text in the linetype
sits with its dashes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:54:01 +07:00
2ez4gcxandClaude Opus 5.5 a303ff433c Linetypes: lay dashes out as AutoCAD does
Patterns were laid out from the start of every run with the first dash
whole. AutoCAD 2024 plots, read back stroke by stroke, show otherwise:
an open run is drawn continuous when shorter than one period, and
otherwise the pattern is centred (n = floor(L / period),
p0 = (n·period + first − L) / 2), the first dash starting at the run's
start and the last ending at its end; a pattern opening with a dot puts
dots at both ends, and one opening with a gap has a rule of its own. A
closed run (a circle, a whole ellipse, a closed PLINEGEN polyline) is
stretched to round(L / period) periods from its anchor (angle 0, or the
second vertex).

linetype::layout makes the drawn stretches for both; apply, apply_as
and ranges use it, the draw code picks the closed layout for circles,
whole ellipses and closed PLINEGEN polylines, and text in complex
linetypes follows the same phase. The measured lines, dots, circle,
rectangles and 33 gap-first cases are pinned in the linetype tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 13:11:38 +07:00
2ez4gcxandClaude Opus 5.5 f126a24c42 Merge main into the RECTANG fix
Picks up #2302, which formats crates/render/src/dim/linear.rs; the
gate's fmt step failed on that file, not on this branch's changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 09:06:54 +07:00
2ez4gcxandClaude Opus 5.5 55d8db69dc STRETCH: an arc with both ends inside moves whole
A full-sweep arc (start = end) has a zero chord, so rebuilding it from
the moved ends gave nothing and STRETCH left it in place even when the
window held all of it. When both ends move, translate the arc instead;
rebuild from the ends only when one of them moves.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 09:06:34 +07:00
2ez4gcxandClaude Opus 5.5 b3ff5505c5 Merge main into the STRETCH fix; import Arc explicitly
#2239 replaced stretch.rs's glob import with an explicit list, and the
new arc rule names cadcraft_geom::Arc, which only the glob brought in, so
the branch no longer compiled on main. `use cadcraft_geom::Arc;` after
the use super::{…} block is the only change the merge needs. Reported in
review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 08:45:45 +07:00
2ez4gcxandClaude Opus 5.5 bc36b99152 Merge main into the RECTANG fix; drop the rect_with_corners import
#2239 replaced rect.rs's glob import with an explicit list that names
rect_with_corners, which this PR removes (the new vertex builder replaces
it), so the branch no longer compiled on main. Dropping the name from the
list is the only change the merge needs. Reported in review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 08:41:55 +07:00
Aldo ZarateandClaude Opus 5.5 d8c37cc6c1 Format dim/linear.rs as rustfmt does
Main's fmt check fails on it since #2302; this keeps the PR's gate green.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:40:18 -06:00
Aldo Zarate 8391c1f0de Merge remote-tracking branch 'upstream/main' into perf/cjk-text 2026-10-29 19:39:48 -06:00
Aldo ZarateandClaude Opus 5.5 7941757ed3 Check every placed glyph corner before building its bounds
Bounds2 skips non-finite points, so a glyph with one overflowing corner
could be culled from the few corners left. Any non-finite corner now
leaves the glyph to the mesh code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:36:45 -06:00
Aldo Zarate d325681051 Merge remote-tracking branch 'upstream/main' into perf/cjk-text
# Conflicts:
#	crates/render/src/text.rs
2026-10-29 19:25:42 -06:00
Aldo ZarateandClaude Opus 5.5 e5dd7290e9 Cull glyphs by their own ink box, not a fixed em margin
Screen builds left out a filled glyph when a fixed font-unit box
(-1000..2000) placed by its transform missed the view, so ink reaching
more than an em past its box (flourishes, long ligatures, tall stacks,
large operators) vanished when the view saw only that part. Each
outline now records its font-unit bounds once as it is built, exposed
as ttf::glyph_bounds through the same per-thread and shared outline
caches, and may_show places those four corners instead: exact, and
still four points per glyph however long its outline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 10:53:41 -06:00
Aldo Zarate 000dbb4383 Merge remote-tracking branch 'upstream/main' into perf/cjk-text 2026-10-29 10:41:47 -06:00
2ez4gcxandClaude Opus 5.5 508c28654d STRETCH: pin the spline selection AutoCAD makes, and note the collapsed arc
Two review questions, answered by measuring AutoCAD 2024 (accoreconsole,
read back with entget):

- A crossing window that holds a spline's control point but misses the
  drawn curve selects nothing in AutoCAD ("0 found"), so the spline stays
  put; CADCraft does the same. Only a window that also crosses the curve
  moves the control point, (10,100) to (15,103). Both cases join the test.
- An arc end stretched onto the other end: AutoCAD collapses the arc into
  a zero-radius arc at that point (radius 6e-16). CADCraft keeps the arc
  rather than make an object nothing can draw or pick; the code says so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:59:07 +07:00
2ez4gcxandClaude Opus 5.5 b57647de0a PLINEWID is an ordinary system variable
PLINE now starts at PLINEWID and stores its widths back, but the
variable itself was out of reach: typing PLINEWID was an unknown command
and GETVAR an unknown variable until a Width answer happened to set it.
It joins the header-variable table (a real of at least 0, default 0, as
in AutoCAD), so GETVAR reports 0, SETVAR and the typed name set it, and
SETVAR ? lists it. Suggested in review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:45:54 +07:00
2ez4gcxandClaude Opus 5.5 12e56da913 RECTANG names the modes it carries over, as AutoCAD does
With chamfer, fillet, width, elevation, thickness and rotation carried
over, a plain RECTANG can draw something its own command never asked for,
and nothing said so. It now opens with AutoCAD's line, in AutoCAD's words
and order: "Current rectangle modes:  Chamfer=1.6574 x 2.8497  Rotation=50.50",
"Current rectangle modes:  Elevation=7.5000  Thickness=2.2500  Rotation=30.96"
(both from AutoCAD 2024's log for the same inputs); no line when every
mode is off. POINT already echoes its modes the same way. Suggested in
review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:39:33 +07: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) <[email protected]>
2026-10-27 19:58:37 +01:00
2ez4gcxandClaude Opus 5.5 a819d82028 Merge main (the module layout of #2220) into the STRETCH fix
#2220 moved STRETCH to cmd/modify/stretch.rs; keep_height and the arc,
polyline-bulge and spline rules move with it, unchanged, below the doc
comment #2220 gave stretch_entity.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 11:51:12 +07:00
2ez4gcxandClaude Opus 5.5 9ce57972c8 Merge main (the module layout of #2220) into the PLINE fix
#2220 moved PLINE's prompt machine to cmd/draw/line_pline.rs; the fix
(PLINEWID as the starting width, Undo returning to the last segment's
mode) moves with it, unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 10:52:10 +07:00
2ez4gcxandClaude Opus 5.5 f49355f6c2 Merge main (the module layout of #2220) into the RECTANG fix
#2220 moved RECTANG from cmd/draw2.rs to cmd/draw2/rect.rs and LastUsed
from lib.rs to last_used.rs. The fix moves with them: rect.rs carries the
AutoCAD vertex rules, draw2 re-exports RectangModes, and LastUsed keeps
the remembered RECTANG options.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 10:28:32 +07:00
2ez4gcxandClaude Opus 5.5 99e973f71f RECTANG: Area adds the corner cut back only when the corners fit
Area sized the rectangle so that its cut corners take nothing off the
area asked for, but it did so even when the fillet or chamfer turned out
too large for the resulting sides and the corners stayed square: Area 4,
length 4, fillet 2 drew a square-cornered 4 x 1.858 rectangle. When the
corners don't fit, the sides now come from the area alone (4 x 1), in the
JSON form and at the prompt. Pointed out in review.

The fit test now lives in one place (corners_fit, with corner_cuts) and
is shared by the vertex builder and the Area sizing. All 64 measured
AutoCAD cases still match vertex for vertex.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:54:20 +07:00
2ez4gcxandClaude Opus 5.5 230d5107fb STRETCH: a collapsed arc segment loses its bulge
When a stretch brings both ends of a polyline arc segment together, the
chord is zero and there is no arc height left to keep; keep_height still
returned the old bulge, which then sat on a zero-length segment. It now
returns 0 (also for a NaN chord). Pointed out in review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:40:33 +07:00
2ez4gcxandClaude Opus 5.5 23a973edfa STRETCH: arcs and polyline arc segments keep their height; spline control points move
STRETCH was checked against AutoCAD 2024 black-box: 36 crossing-window
cases run in accoreconsole (lines, polylines, arcs, circles, text,
ellipses, splines, points, block references), each object read back with
entget. Lines, straight polylines, circles, text, full ellipses, points
and block references already matched; three kinds of object did not.

- Arcs moved whole when their centre was inside the window and were left
  alone otherwise. AutoCAD moves the ends that are inside and keeps the
  arc's height, bulge x chord / 2: the arc (0,0) r20 0-90 deg with its
  start stretched by (5,3) becomes centre (3.1798, -2.2061), radius
  22.4326. The centre alone moves nothing.
- Polyline arc segments kept their bulge, so they ballooned or flattened
  as a vertex moved. AutoCAD keeps their height too: bulge 0.5 over a
  chord of 25 becomes 0.6338 when the chord shrinks to 19.72 (and -1.5
  becomes -1.2303 over a longer one).
- Splines moved whole when their first grip was inside, and stayed put
  otherwise. AutoCAD moves the control points inside the window. Splines
  built from fit points keep the old behaviour, which was not measured.

An elliptical arc with one end inside is still left as it was: AutoCAD
changes the whole ellipse there by a rule one measurement does not pin.

The new test stretch_arcs_bulges_and_splines_match_autocad pins nine of
the measured cases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:22:43 +07:00
2ez4gcxandClaude Opus 5.5 95429bb286 PLINE: Undo returns to the last segment's mode, and PLINEWID is the width
PLINE was checked against AutoCAD 2024 black-box: 76 typed inputs run in
accoreconsole, read back with entget and GETVAR. 72 matched; with this
change all 76 do.

- Undo after an arc segment stayed in arc mode, so a following `_L` was
  arc mode's Line instead of line mode's Length and the point became a
  plain vertex. AutoCAD returns to the mode of the segment now last:
  `_A` point `_U` `_L` point continues the last line by the point's
  distance, ending at (64.48701958199356, 48.21692560701169) in the
  measured case.
- PLINEWID was ignored: AutoCAD starts every polyline at that width
  ("Current line-width is 0.7500") and stores the ending width of the
  last Width or Halfwidth answer back into it (`_H 0.5 0.5` leaves
  PLINEWID 1).

The new test pline_undo_mode_and_plinewid_match_autocad pins both with
the measured numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 15:55:12 +07:00
2ez4gcxandClaude Opus 5.5 54e34b02ba RECTANG draws the vertices AutoCAD stores
RECTANG was checked against AutoCAD 2024 black-box: 64 typed inputs run
in accoreconsole, each polyline read back with entget. 18 matched; with
this change all 64 match vertex for vertex.

- Vertex order: AutoCAD starts at the first corner and runs along the
  first axis towards the other corner, so a rectangle is clockwise when
  the corners are picked down-right or up-left. CADCraft always started at
  the lower-left corner and ran counterclockwise.
- Chamfer: the first distance is cut on the edge into each corner and the
  second on the edge out of it, in drawing order. CADCraft cut the first
  along x and the second along y, which mirrors the corners whenever the
  two distances differ.
- Fillet bulges follow the drawing direction: negative on a clockwise
  rectangle.
- A fillet or chamfer too large for the shorter side leaves each corner
  as two coincident vertices (8 vertices, no arcs), not 4 vertices.
- Chamfer and Fillet replace each other: the option set last wins.
  CADCraft kept the fillet when a chamfer was set after it.
- Area sizes the rectangle so that the outline, with its corners cut
  off, encloses the area given: L = (A + 2*d1*d2) / W for a chamfer and
  (A + (4 - pi)*r^2) / W for a fillet. This applies to the JSON form too.
- Chamfer, fillet, width, elevation, thickness and rotation carry over to
  the next RECTANG (AutoCAD opens it with "Current rectangle modes:
  Fillet=2.0000" or "Elevation=7.5000  Thickness=2.2500  Rotation=30.96").
  They are kept in LastUsed; the JSON form stays stateless.

The new test rectang_vertices_match_autocad pins 12 of the measured
cases, one or more per rule. Three older tests change with the measured
behaviour: an oversized fillet now gives 8 coincident-pair vertices, and
two tests that draw several rectangles in one session set the remembered
rotation or fillet back explicitly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 15:43:58 +07:00
Aldo ZarateandClaude Opus 5.5 9a1bd48a26 Per-thread glyph outlines: bound them by points
Each thread kept up to 8192 glyph outlines in front of the shared cache with no size limit, and
held them after the shared cache let them go. They are now held within MAX_SHAPED_POINTS / 16
points per thread, and an outline above a quarter of that is read from the shared cache instead.
The generation test reads the cache before checking the generation, so another test's change in
between can't fail it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 08:10:30 -06:00
Aldo ZarateandClaude Opus 5.5 e57786e726 Per-thread caches: bound meshes by bytes; don't keep a stale font lookup
Each thread's text meshes were capped at 4096 entries but not by size; CJK text at full detail
could hold hundreds of MB per core. They are now capped at 16 MiB per thread (with the shared
cache's size estimate), and a mesh above a quarter of that is read from the shared cache instead.

A font lookup that ran while a font was being registered could keep the old answer (a "not
found") on that thread until the next change. The generation is read before the lookup, and the
answer is kept only under that generation, so a lookup overtaken by a change starts over.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 07:44:08 -06:00
Aldo ZarateandClaude Opus 5.5 4d3ceea73b Merge upstream/main into perf/cjk-text
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 19:41:29 -06:00
Aldo ZarateandClaude Opus 5.5 38e98e43c0 Faster CJK-heavy drawings: per-thread font caches, offscreen glyphs left out
Display lists are built on all cores, but every text looked its font up,
and every character its font lacks (all of a CJK text's) its fallback
font, glyph outline and glyph mesh, through shared tables behind global
locks; text-heavy drawings spent most of the build waiting on them.
Font lookups, fallback faces, FONTALT, glyph outlines and glyph meshes
now have per-thread caches in front of the shared ones (a generation
counter empties them when fonts or FONTALT/FONTFALLBACK change).

On screen, filled glyphs outside the area being looked at are left out,
as hatch patterns already are (the canvas builds again when the view
leaves that area); plots and exports keep every glyph. Zoomed in, every
glyph of every text was filled at that zoom's detail and drawn each
frame, i.e. on every mouse move.

Synthetic 3.8 MB drawing (24,000 TEXT and 2,500 MTEXT in Chinese, 30,000
lines), macOS, Apple silicon: display list at fit 335 -> 103 ms;
triangles at 16x zoom 11.2 M -> 0.44 M, at 64x 19.0 M -> 45 k.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 09:58:53 -06:00
411 changed files with 33506 additions and 4375 deletions
+17 -7
View File
@@ -2,13 +2,13 @@
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/cadcraft",
"repository_id": 1408289866,
"producer_workflow_id": null,
"producer_workflow_id": 429719786,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"producer_tooling_revision": "main",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"signer_tooling_revision": "main",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
@@ -83,7 +83,9 @@
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"automatic_signer_actors": [
"github-actions[bot]"
],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
@@ -95,7 +97,15 @@
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"package_formats": [
"appimage",
"arch",
"deb",
"flatpak",
"oci",
"rpm"
]
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
+72
View File
@@ -0,0 +1,72 @@
name: Dispatch release-ref nightly
# Transport only, never authorization. No checkout, payload parsing or release environment.
on:
workflow_run:
workflows: [CADCraft unsigned nightly]
types: [completed]
branches: [main]
permissions: {}
jobs:
dispatch:
# Actual context guards: official repository and completed workflow_run only.
if: >-
github.repository == 'storytold/cadcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Dispatch only the exact completed producer run and attempt
shell: python
env:
GH_TOKEN: ${{ github.token }}
run: |
import json
import os
import urllib.request
def require(value, message):
if not value:
raise RuntimeError(message)
# These filters reduce noise; the protected signer-branch validator repeats admission
# against authenticated API metadata and required attestation/quality evidence.
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/cadcraft', 'wrong repository')
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
event = json.load(stream)
require(event.get('action') == 'completed', 'producer is not complete')
require(event.get('repository', {}).get('full_name') == 'storytold/cadcraft', 'wrong event repository')
producer = event.get('workflow_run', {})
require(producer.get('head_repository', {}).get('full_name') == 'storytold/cadcraft', 'foreign producer')
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
require(producer.get('head_branch') == 'main', 'wrong producer branch')
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
run_id, attempt = producer.get('id'), producer.get('run_attempt')
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
}}).encode('utf-8')
request = urllib.request.Request(
'https://api.github.com/repos/storytold/cadcraft/actions/workflows/nightly-sign.yml/dispatches',
data=body, method='POST', headers={
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'cadcraft-nightly-dispatch'
})
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise RuntimeError('dispatch redirects are forbidden')
# One bounded request, no retry: duplicate transport is not publication authority.
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
require(response.status == 204, 'dispatch was not accepted')
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
+24 -7
View File
@@ -1,7 +1,8 @@
name: CADCraft release-ref nightly signer
# Enabled for supervised manual dispatch on release. Main/release contents must match.
# A reusable callee does not change context; this must be a real top-level release dispatch.
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
on:
workflow_dispatch:
inputs:
@@ -22,21 +23,37 @@ concurrency:
jobs:
release:
# Actual context guards: official repository, manual dispatch, real release branch.
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
if: >-
github.repository == 'storytold/cadcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
tooling-revision: main
app-name: cadcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment and export keys in its signing step.
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
+9 -6
View File
@@ -1,8 +1,10 @@
name: CADCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
# Automated nightly builds at 00:30 UTC (paired with nightly-dispatch.yml for automatic
# Stage 2 signer dispatch) plus supervised manual runs by the reviewed manual actors.
on:
schedule:
- cron: '30 0 * * *'
workflow_dispatch:
permissions:
@@ -22,13 +24,14 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
tooling-revision: main
app-name: cadcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
+20
View File
@@ -0,0 +1,20 @@
name: Notify Services on Release Change
on:
release:
types:
- published
- unpublished
- created
- edited
- deleted
- prereleased
- released
permissions: {}
jobs:
notify:
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
secrets:
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+1 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
+2
View File
@@ -72,6 +72,8 @@ Layout:
Checks for the crates you changed: `cargo test -p <crate>`, `cargo clippy -p <crate> --all-targets -- -D warnings`, `cargo xtask layers`, `cargo xtask assets`, `cargo xtask wasm`, `cargo xtask parity` (regenerates `docs/parity-checklist.md`).
Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a covered menu item `headless: yes` because its command is in the engine registry that `cadcraft-cli` and the MCP server load. An uncovered item takes `no`/`partial` and a `reach` (`window`, `os`, `engine-gap`) from `HEADLESS` in `xtask/src/parity.rs` (a path ending in ` > ` covers its submenu), or reads `unknown`. Never write `yes` there. A covered leaf is `yes` whatever its marks say, so a submenu mark stays while any leaf under it is uncovered; drop a mark only once commands cover every leaf it matches (the check then fails on it as stale).
Paths and conventions:
- No crate allows `unsafe` (`unsafe_code = "forbid"` in the workspace).
+2 -1
View File
@@ -25,6 +25,7 @@ Generated-in-code assets are original and have no file to list:
| Asset | Author | Source | Licence | Notes |
|---|---|---|---|---|
| `crates/ui-egui/src/i18n/zh_shared.tsv` | @V1dalTheAbidal | [craft-i18n #444](https://github.com/storytold/craft-i18n/pull/444), [pinned Simplified Chinese CADCraft catalog](https://github.com/storytold/craft-i18n/blob/9fa32aecf2759cd61bb216a958df68da619798f3/locales/zh-hans/cadcraft.tsv#L201) | MIT OR Apache-2.0 | Exact generated one-row projection for offline builds; AI-assisted, not native-speaker reviewed. |
| `licenses/jpeg-encoder-0.6.1/` | jpeg-encoder contributors and Independent JPEG Group | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1) | (MIT OR Apache-2.0) AND IJG | Dependency license and SIMD notices; source hashes in SOURCE.json. |
| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 173cc737](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full monochrome fallback. Registered by the production default font definitions; dependency assets unmodified here, no font file copied into this repository. |
| `krilla 0.8.2 / icc/sGrey-v2-magic.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v2-magic.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v2-magic.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `4110169287e5f1b5149ca9f1da1814d32943905bba8030e849d1a3b729a19481`. |
@@ -87,7 +88,7 @@ Generated-in-code assets are original and have no file to list:
| `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/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 chosen with a native speaker, full proofreading 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) |
| `crates/ui-egui/src/i18n/ta.tsv` | @newsbaba24x7 (AI-assisted) | Original Tamil translations of CADCraft English strings, shared with storytold/craft-i18n `locales/ta/` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings; the 1,289 rows from craft-i18n reviewed there for language and terminology by native speakers, and the whole Tamil interface reviewed in the running app by native speakers Radhika and Mohan Raj (2026-11-14); no font assets added (Tamil comes from an installed font or the craft-fonts face) |
Generated
+1288 -92
View File
File diff suppressed because it is too large Load Diff
+37 -32
View File
@@ -14,11 +14,12 @@ repository = "https://github.com/storytold/cadcraft"
# internal
cadcraft-geom = { path = "crates/geom" }
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "219c1d0b14177af6f291395d6587f61a5e09043a" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "8945bdb09b36245a1d442438ce8876377ef430d0" }
cadcraft-color = { path = "crates/color" }
cadcraft-doc = { path = "crates/doc" }
cadcraft-constraints = { path = "crates/constraints" }
@@ -28,19 +29,19 @@ cadcraft-io = { path = "crates/io" }
cadcraft-engine = { path = "crates/engine" }
cadcraft-ui-egui = { path = "crates/ui-egui" }
cadcraft-mcp = { path = "crates/mcp" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# SVG/SVGZ import and export geometry (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# Which paths stored in a drawing (xrefs, data links) may be opened.
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
# Delimited text (CSV/TSV) parsing (shared Craft library).
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4.6.11"
clap_mangen = { version = "0.3.3", features = ["env"] }
@@ -74,8 +75,12 @@ encoding_rs = "0.8.35"
quick-xml = "0.42"
# ui
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["serde"] }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
@@ -85,7 +90,7 @@ egui-wgpu = "0.37"
# Monotonic time on native and web (performance.now on wasm).
web-time = "1.1"
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
rfd = "0.17"
arboard = { version = "3.6", default-features = false }
@@ -117,23 +122,23 @@ debug = 0
# PDF backends for craft-pdf: pinned to the same reviewed craft-libs revision as craft-pdf itself
# (Cargo ignores dependency-local patches).
[patch.crates-io]
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# Keep the complete egui family and native event bridge on reviewed fork commits.
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+10 -4
View File
@@ -89,9 +89,15 @@
line, prompts with clickable `[Keywords]`, AutoComplete, object snaps, polar tracking, ortho,
direct distance entry, window and crossing selection, grips, and right-click-to-repeat behave
the way decades of drafting habit expect.
- **Open files.** DXF is read and written natively (ASCII and binary, R12 through 2018), and DWG
files (R13 through 2018) open and save through the open-source acadrust library. Export to SVG
and PNG today.
- **Open files.** DXF is read natively (R12 through 2018, with binary support from R13) and
written as 2000 through 2018 (ASCII and binary). DWG files (R13 through 2018; R13 and R14
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
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.
- **Built for agents.** Every menu item, tool and prompt is a command. Agents can type at the
@@ -114,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, ASCII and binary) and write (R2000), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library) and write (R2000); 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) |
| 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 |
| 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 |
+1 -1
View File
@@ -66,7 +66,7 @@ fn convert_long_about() -> &'static str {
/// cadcraft-cli: headless CADCraft
#[derive(Parser)]
#[command(name = "cadcraft-cli", version = cadcraft_engine::build_version(), arg_required_else_help = true)]
#[command(name = "cadcraft-cli", version = cadcraft_engine::build_version(), propagate_version = true, arg_required_else_help = true)]
pub(crate) struct Cli {
#[command(subcommand)]
pub(crate) command: Command,
+7
View File
@@ -45,6 +45,12 @@ fn install_io() {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
cadcraft_engine::cmd::file::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())
@@ -60,6 +66,7 @@ fn install_io() {
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
}
/// `path` as text, for the engine and io calls that take a file name as a string.
+8 -1
View File
@@ -145,15 +145,22 @@ pub(crate) fn export(s: &Session, out: &Path, io: &mut Streams) -> Result {
pub(crate) fn export_framed(s: &Session, out: &Path, window: Option<Bounds2>, io: &mut Streams) -> Result {
let d = s.doc()?;
let bytes = cadcraft_io::write_framed(d, out, window)?;
let (bytes, notes) = cadcraft_io::write_framed_noted(d, out, window)?;
let folder = write_atomic(out, &bytes)?;
report_new_folder(folder, io);
io.errln(format_args!("wrote {} ({} bytes)", out.display(), bytes.len()));
// What the image draws short of the drawing (dashed runs past a dash limit drawn continuous).
for note in notes {
io.errln(format_args!("{}: {note}", out.display()));
}
if cadcraft_engine::cmd::file::drops_unknown(out) {
let lost = cadcraft_engine::cmd::file::not_saved(d);
if let Some(m) = cadcraft_engine::cmd::file::not_saved_message(&lost) {
io.errln(format_args!("{m}"));
}
for note in cadcraft_engine::cmd::file::dwg_notes(d) {
io.errln(format_args!("{note}"));
}
}
Ok(())
}
@@ -0,0 +1,144 @@
//! `convert` to an image says how many dashed runs it drew continuous because of a dash limit
//! (#1069): a line whose DASHED pattern repeats past what one run may be laid out over. A line of
//! 50,001 periods, which an export keeps dashed, gets no note.
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A DXF of one line `periods` DASHED (0.5, -0.25) periods long.
fn dashed_line(periods: f64) -> String {
format!(
"0
SECTION
2
TABLES
0
TABLE
2
LTYPE
70
1
0
LTYPE
2
DASHED
70
0
3
Dashed
72
65
73
2
40
0.75
49
0.5
74
0
49
-0.25
74
0
0
ENDTAB
0
ENDSEC
0
SECTION
2
ENTITIES
0
LINE
8
0
6
DASHED
10
0
20
0
11
{}
21
0
0
ENDSEC
0
EOF
",
periods * 0.75
)
}
#[test]
fn convert_to_an_image_notes_dashed_runs_drawn_continuous_past_the_dash_limit() {
let dir = std::env::temp_dir().join(format!("cc-cli-dash-limit-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
// (1,000,001 + 2) periods × 2 elements: past the two million one run may be laid out over.
let long = dir.join("long.dxf");
std::fs::write(&long, dashed_line(1_000_001.0)).unwrap();
let control = dir.join("control.dxf");
std::fs::write(&control, dashed_line(50_001.0)).unwrap();
let notes = |out: &Output| {
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stderr).lines().filter(|l| l.contains("drawn continuous")).map(str::to_string).collect::<Vec<_>>()
};
for ext in ["png", "svg", "pdf"] {
let image = dir.join(format!("long.{ext}"));
let image = image.to_str().unwrap();
let got = notes(&cli(&["convert", long.to_str().unwrap(), image]));
assert!(matches!(got.as_slice(), [note] if note.starts_with(&format!("{image}: 1 dashed run "))), "{ext}: {got:?}");
let got = notes(&cli(&["convert", control.to_str().unwrap(), dir.join(format!("control.{ext}")).to_str().unwrap()]));
assert!(got.is_empty(), "{ext}: {got:?}");
}
// A DXF copy draws nothing, so there is nothing to note.
assert!(notes(&cli(&["convert", long.to_str().unwrap(), dir.join("copy.dxf").to_str().unwrap()])).is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
/// The engine's commands that write an image say it too, on the command line and in the result's
/// `warnings`: EXPORT, PLOT (PDF, PNG, SVG, to a file or as data), QSAVE and SAVEAS to an image and
/// `document.bytes`.
#[test]
fn image_commands_warn_about_dashed_runs_drawn_continuous() {
let dir = std::env::temp_dir().join(format!("cc-cli-dash-limit-cmds-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let out = |name: &str| serde_json::to_string(dir.join(name).to_str().unwrap()).unwrap();
let cmds = [
format!("export {{\"path\": {}}}", out("export.png")),
format!("plot {{\"path\": {}}}", out("plot.pdf")),
format!("plot {{\"path\": {}, \"output\": \"png\", \"resolution\": 50}}", out("plot.png")),
format!("plot {{\"path\": {}, \"output\": \"svg\"}}", out("plot.svg")),
format!("saveas {{\"path\": {}}}", out("saved.svg")),
format!("qsave {{\"path\": {}}}", out("saved.pdf")),
"plot {\"output\": \"svg\"}".to_string(),
"document.bytes {\"format\": \"pdf\"}".to_string(),
format!("saveas {{\"path\": {}, \"version\": 2018}}", out("versioned.png")),
];
for (periods, warned) in [(1_000_001.0, true), (50_001.0, false)] {
let input = dir.join(format!("line-{periods}.dxf"));
std::fs::write(&input, dashed_line(periods)).unwrap();
let mut args = vec!["run".to_string(), input.to_str().unwrap().to_string()];
for c in &cmds {
args.extend(["--cmd".to_string(), c.clone()]);
}
let run = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(&args).output().unwrap();
assert!(run.status.success(), "{:?}: {}", run.status, String::from_utf8_lossy(&run.stderr));
let results: Vec<serde_json::Value> = String::from_utf8_lossy(&run.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(results.len(), cmds.len(), "{results:?}");
for (c, r) in cmds.iter().zip(&results) {
let notes: Vec<&str> = r["warnings"].as_array().into_iter().flatten().filter_map(|w| w.as_str()).collect();
let noted = matches!(notes.as_slice(), [n] if n.starts_with("1 dashed run ") && n.contains("drawn continuous"));
assert_eq!(noted, warned, "{periods} periods, {c}: {r}");
assert_eq!(r.get("warnings").is_some(), warned, "{periods} periods, {c}: {r}");
}
// Said on the command line once for each command.
let echoed = String::from_utf8_lossy(&run.stderr).lines().filter(|l| l.starts_with("1 dashed run ")).count();
assert_eq!(echoed, if warned { cmds.len() } else { 0 }, "{}", String::from_utf8_lossy(&run.stderr));
}
let _ = std::fs::remove_dir_all(&dir);
}
+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}");
}
@@ -0,0 +1,41 @@
//! `convert` to DWG says, in one warning, how many linetypes the DWG keeps with only their first
//! 255 dash elements (#1923, F-05); converting to DXF keeps them whole and says nothing.
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A DXF with a 256-element linetype and a line drawn with it.
fn dxf() -> String {
let mut s = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLTYPE\n70\n1\n0\nLTYPE\n2\nLONG\n70\n0\n3\nLong\n72\n65\n73\n256\n40\n192\n");
for i in 0..256 {
s.push_str(if i % 2 == 0 { "49\n1\n74\n0\n" } else { "49\n-0.5\n74\n0\n" });
}
s.push_str("0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n6\nLONG\n10\n0\n20\n0\n11\n10\n21\n0\n0\nENDSEC\n0\nEOF\n");
s
}
#[test]
fn convert_to_dwg_notes_the_linetypes_it_cuts() {
let dir = std::env::temp_dir().join(format!("cc-cli-ltype-dwg-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let source = dir.join("long.dxf");
std::fs::write(&source, dxf()).unwrap();
let source = source.to_str().unwrap();
let notes =
|out: &Output| String::from_utf8_lossy(&out.stderr).lines().filter(|l| l.contains("dash elements")).map(str::to_string).collect::<Vec<_>>();
let out = cli(&["convert", source, dir.join("long.dwg").to_str().unwrap()]);
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
assert!(
matches!(notes(&out).as_slice(), [note] if note.contains("1 linetype") && note.contains("255")),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let out = cli(&["convert", source, dir.join("copy.dxf").to_str().unwrap()]);
assert!(out.status.success() && notes(&out).is_empty(), "{}", String::from_utf8_lossy(&out.stderr));
let _ = std::fs::remove_dir_all(&dir);
}
+5
View File
@@ -1,6 +1,11 @@
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;
mod mcp_connect;
mod pdf_import;
mod skipped_records;
+15 -2
View File
@@ -188,12 +188,25 @@ fn subcommand_help_requests() {
),
case("help after an extra argument", &["info", "{b}", "extra", "-h"], 0, Line("Print a drawing's summary as JSON"), Empty),
case("--help after -- is a file name", &["run", "--", "--help"], 1, Empty, Starts("error: invalid parameters for `open`: --help:")),
case("run --version", &["run", "--version"], 2, Empty, Line("error: unexpected argument '--version' found")),
case("info --version", &["info", "--version"], 2, Empty, Line("error: unexpected argument '--version' found")),
],
);
}
/// RFC-0018 rule 1.1: `--version` and `-V` work on every subcommand, print one line on stdout and
/// return without running it (`mcp` would otherwise wait for a client).
#[test]
fn every_subcommand_prints_the_version() {
for sub in ["info", "convert", "run", "commands", "mcp", "perf", "sample", "roundtrip"] {
for flag in ["--version", "-V"] {
let top = invoke(&[flag]);
let release = top.stdout.strip_prefix("cadcraft-cli ").unwrap_or_else(|| panic!("{:?}", top.stdout));
let got = invoke(&[sub, flag]);
assert_eq!((got.code, got.stderr.as_str()), (0, ""), "{sub} {flag}");
assert_eq!(got.stdout, format!("cadcraft-cli-{sub} {release}"), "{sub} {flag}");
}
}
}
#[test]
fn unknown_flags_on_every_subcommand() {
run_cases(
+2 -2
View File
@@ -21,8 +21,8 @@ cadcraft-io = { workspace = true }
cadcraft-fonts = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
# The page command API (storytold/craft-libs#413): window.cadcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
+11 -2
View File
@@ -54,11 +54,12 @@ mod web {
if let Some(bridge) = &self.2 {
bridge.report_dirty(&self.0);
}
self.0.close_path(ctx);
}
/// Forward raw input to the web `CadApp` and capture Tab at the command line.
/// Forward raw input to the web `CadApp` and hand the frame's root values to the UI runtime.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(ctx, raw);
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
self.0.before_input(ctx);
}
/// Preferences and validated panel placement survive reloads; egui memory is not kept.
fn save(&mut self, storage: &mut dyn eframe::Storage) {
@@ -119,6 +120,12 @@ mod web {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
cadcraft_engine::cmd::file::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())
@@ -134,6 +141,7 @@ mod web {
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
let Some(canvas) = app_canvas() else {
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
return;
@@ -166,6 +174,7 @@ mod web {
canvas,
options,
Box::new(move |cc| {
cadcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
// Embedded, the host sends the drawing: start on the Start tab, not Drawing1.
let session = if app_bridge.is_some() { Session::empty() } else { Session::new() };
let control = crate::api::install(cc.egui_ctx.clone());
+1 -1
View File
@@ -94,7 +94,7 @@ mod tests {
let mut ui = UiState::default();
let before = serde_json::to_value(&ui).unwrap();
let mut invalid = ui.clone();
invalid.docking.layout.root = None;
invalid.docking = cadcraft_ui_egui::docking::Workspace::default();
assert!(save(&invalid).is_err());
let mut record: Value = serde_json::from_str(&save(&ui).unwrap()).unwrap();
record["docking"] = serde_json::to_value(&invalid.docking).unwrap();
+8 -10
View File
@@ -24,11 +24,16 @@ serde_json = { workspace = true }
serde = { workspace = true }
log = { workspace = true }
clap = { workspace = true }
craft-nightly = { workspace = true }
thiserror = { workspace = true }
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"
@@ -41,27 +46,20 @@ winit = { version = "0.30", default-features = false, features = ["x11"] }
zbus = { version = "=5.19.0", default-features = false, features = ["async-io", "blocking-api"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# Floating panels open in their own OS windows on the desktop; the web build keeps them in the page.
craft-ui = { workspace = true, features = ["native-windows"] }
craft-update = { workspace = true }
rfd = { workspace = true }
sys-locale = "0.3"
[target.'cfg(target_os = "macos")'.dependencies]
# `title_bar::sync_movable`: AppKit's title-band drag leaves the window still under the row's
# controls and under floating panels.
craft-window = { workspace = true }
muda = { version = "0.21", default-features = false }
# Quit CADCraft as a close request of the main window, so the unsaved-changes question runs (#2157).
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: the system's Reduce motion
# (system_animations.rs). Already in Cargo.lock through muda.
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility"] }
# The same winit eframe uses (the storytold fork, patched in the workspace): its opt-in that turns
# AppKit's terminate (Cmd+Q, Dock Quit) into a close request, so unsaved changes are asked about.
# 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.
+4 -29
View File
@@ -1,23 +1,11 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub use craft_nightly::BuildFlavor;
pub const COMPILED: BuildFlavor = if cfg!(cadcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open CADCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable CADCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
@@ -35,7 +23,8 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
#[cfg(test)]
mod tests {
use super::*;
use super::{BuildFlavor, needs_native_error, version, version_query};
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
@@ -44,20 +33,6 @@ mod tests {
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.23.1"), "0.23.1");
+78 -4
View File
@@ -4,8 +4,9 @@
//! The server only reads requests: a line that is not a JSON object with a string `method` (an
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
//! closed, so nothing sent after it runs. Every resource a client can hold is bounded
//! ([`Limits`]): simultaneous connections, request line length, queued requests, and how long a
//! socket may sit idle or blocked on a write.
//! ([`Limits`]): simultaneous connections, request line length (shorter until a request on the
//! connection has carried the token), queued requests, and how long a socket may sit idle or
//! blocked on a write.
use std::io::{BufRead, BufReader, ErrorKind, Write};
use std::net::{TcpListener, TcpStream};
@@ -24,6 +25,9 @@ struct Limits {
max_clients: usize,
/// Longest request line in bytes (newline excluded); a longer one closes the connection.
max_line: usize,
/// Longest request line until a request on the connection has carried the right token; a
/// longer one closes the connection (#1925).
preauth_line: usize,
/// Request-line bytes buffered at once across all connections; a request that would pass it
/// is refused with an error reply.
total_bytes: usize,
@@ -43,6 +47,7 @@ impl Default for Limits {
max_clients: 16,
// Generous, so requests that carry whole drawings or images as base64 still fit.
max_line: 256 * 1024 * 1024,
preauth_line: cadcraft_mcp::control_token::MAX_UNAUTHENTICATED_LINE,
// Room for one maximal request plus smaller ones, not `max_clients` maximal ones.
total_bytes: 512 * 1024 * 1024,
queue: 64,
@@ -344,12 +349,21 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
let mut reader = BufReader::new(read);
let mut buf = Vec::new();
let mut held = Held::new(budget);
// The token is checked only after the whole line is read, so until a request here has carried
// it a line is kept short: a peer without it can't make the app buffer `max_line` (#1925).
let mut authenticated = false;
loop {
let reject = match read_bounded_line(&mut reader, &mut buf, limits.max_line, &mut held) {
let max = if authenticated { limits.max_line } else { limits.preauth_line.min(limits.max_line) };
let reject = match read_bounded_line(&mut reader, &mut buf, max, &mut held) {
Ok(false) => break,
// Nothing of a line arrived (idle timeout, or the peer is gone): close without a word.
// A line nobody asked for would be read as the reply to the client's next request.
Err(_) if buf.is_empty() => break,
// Only an overlong line leaves more than `max` bytes buffered.
Err(_) if !authenticated && buf.len() > max => format!(
"request line longer than {max} bytes before a request with the control token on this connection; \
send a short request with the token (such as `ping`) first; closing the connection"
),
Err(e) => e,
Ok(true) => match parse_line(&buf) {
Line::Blank => continue,
@@ -366,6 +380,7 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
let _ = writeln!(out, "{r}");
break;
}
authenticated = true;
// Absent `params` is `{}`; ones that cannot be decoded (an unpaired surrogate escape) are an
// error, not a request run with defaults.
let params = match params.map(|r| serde_json::from_str::<Value>(r.get())) {
@@ -499,7 +514,12 @@ mod tests {
/// The control server on a loopback port, with a stand-in UI that echoes each method.
fn serve_echo() -> std::net::SocketAddr {
let (addr, rx) = serve_with(Limits::default());
serve_echo_with(Limits::default())
}
/// [`serve_echo`] under `limits`.
fn serve_echo_with(limits: Limits) -> std::net::SocketAddr {
let (addr, rx) = serve_with(limits);
std::thread::spawn(move || {
for req in rx {
let _ = req.reply.send(json!({"ok": true, "method": req.method}));
@@ -612,6 +632,60 @@ mod tests {
drop(first);
}
/// Small bounds for the pre-authentication tests: lines up to 1000 bytes until the connection
/// has shown the token, up to 100 000 after.
fn preauth() -> Limits {
Limits { max_line: 100_000, preauth_line: 1000, idle_timeout: Duration::from_secs(5), ..short() }
}
/// A request line carrying the test token whose parameters make it `len` bytes or longer.
fn long_req_line(id: i64, len: usize) -> String {
json!({"id": id, "method": "long", "params": {"text": "x".repeat(len)}, "token": TEST_TOKEN}).to_string() + "\n"
}
/// A peer without the token is refused once its line passes the pre-authentication bound,
/// while it is still sending: the app doesn't buffer the rest of the line to find the token
/// at its end (#1925).
#[test]
fn an_unauthenticated_long_line_is_refused_at_the_preauth_bound() {
let (addr, rx) = serve_with(preauth());
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
// Well under `max_line`, and unfinished: without the pre-authentication bound the server
// keeps reading and waiting for the rest of it. One write, so it all reaches the server's
// buffer at once and the close after the refusal leaves nothing unread to reset the reply.
let unfinished = format!(r#"{{"id":1,"method":"m","params":"{}"#, "x".repeat(5000));
c.write_all(unfinished.as_bytes()).unwrap();
let mut line = String::new();
BufReader::new(&mut c).read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!(v["ok"], json!(false));
assert!(v["error"].as_str().unwrap_or("").contains("longer than 1000 bytes before a request with the control token"), "{line}");
assert!(rx.try_recv().is_err(), "nothing was dispatched");
}
/// A long request with the token is taken once a shorter request with the token has been
/// answered on the same connection; as a connection's first line it is refused, since its
/// token comes only at the end.
#[test]
fn a_long_request_is_taken_once_the_connection_has_shown_the_token() {
let addr = serve_echo_with(preauth());
let long = long_req_line(2, 5000);
let first = exchange(addr, long.as_bytes());
assert_eq!(first.len(), 1, "{first:?}");
assert!(first[0]["error"].as_str().unwrap_or("").contains("before a request with the control token"), "{first:?}");
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
c.write_all(format!("{}{long}", req_line(1, "ping")).as_bytes()).unwrap();
let mut r = BufReader::new(c);
for (id, method) in [(1, "ping"), (2, "long")] {
let mut line = String::new();
r.read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!((v["id"].as_i64(), v["ok"].as_bool(), v["method"].as_str()), (Some(id), Some(true), Some(method)), "{line}");
}
}
#[test]
fn the_budget_is_given_back_when_the_connection_ends() {
let budget = Budget::new(100);
+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))]
+64 -174
View File
@@ -1,211 +1,101 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
//! Nightly-v1 bootstrap powered by `craft-nightly`: selected before logging, updates, fonts, or
//! saved state. Direct nightly launches self-isolate into `craft_nightly::canonical_profile_root`,
//! while explicit `--launch-profile nightly-v1 --profile-root <dir>` invocations keep their
//! launcher-supplied root. Stable launches retain their original arguments and directory policy.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions};
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
craft_nightly::current().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old portable/config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::portable::probe)
pub fn prepare(flavor: BuildFlavor, args: impl IntoIterator<Item = OsString>) -> Result<Launch, ProfileError> {
craft_nightly::prepare_launch(flavor, &crate::profile_root::spec(), args, &StartupOptions::new())
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
use std::ffi::OsString;
use std::path::PathBuf;
use craft_nightly::{BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup};
use crate::profile_root::{APP_ID, spec};
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\cadcraft" } else { "/nightly-data/profiles/cadcraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
#[test]
fn direct_nightly_launch_self_isolates_into_canonical_root_and_preserves_user_args() {
let expected_root = canonical_profile_root(APP_ID).unwrap();
let launch = parse_startup(BuildFlavor::NightlyV1, &spec(), args(&["--sample", "plan.dxf"]), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert!(launch.profile.is_nightly());
assert_eq!(launch.passthrough_args, args(&["--sample", "plan.dxf"]));
assert!(!launch.is_version_query());
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["--new-window", "a.dxf"]), args(&["--", "--launch-profile", "file.dxf"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
}
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "drawing with spaces.dxf"]));
let launch = parse(argv).unwrap();
fn explicit_launcher_flags_override_canonical_root_and_forward_passthrough_args() {
let argv = args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--", "drawing with spaces.dxf"]);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec(), argv, &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "drawing with spaces.dxf"]));
assert_eq!(launch.passthrough_args, args(&["drawing with spaces.dxf"]));
assert!(!launch.is_version_query());
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() {
for argv in [args(&[]), args(&["--new-window", "a.dxf"]), args(&["--", "--launch-profile", "file.dxf"])] {
let launch = parse_startup(BuildFlavor::Stable, &spec(), argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::Stable);
assert_eq!(launch.passthrough_args, argv);
}
let nightly = args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]);
assert!(matches!(parse_startup(BuildFlavor::Stable, &spec(), nightly, &StartupOptions::new()), Err(ProfileError::NightlyFlagsInStableBuild)));
}
#[test]
fn malformed_nightly_flags_are_refused() {
let s = spec();
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-window", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
args(&["--new-window", "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]),
] {
assert!(parse(argv).is_err());
assert!(parse_startup(BuildFlavor::NightlyV1, &s, argv, &StartupOptions::new()).is_err());
}
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
fn launcher_and_direct_version_queries_are_recognized() {
let s = spec();
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-window", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
let direct = parse_startup(BuildFlavor::NightlyV1, &s, args(&[flag]), &StartupOptions::new()).unwrap();
assert!(direct.is_version_query(), "direct {flag}");
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
let launcher = parse_startup(
BuildFlavor::NightlyV1,
&s,
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), flag]),
&StartupOptions::new(),
)
.unwrap();
assert!(launcher.is_version_query(), "launcher {flag}");
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
let file_named_version = parse_startup(BuildFlavor::NightlyV1, &s, args(&["--", "--version"]), &StartupOptions::new()).unwrap();
assert!(!file_named_version.is_version_query());
}
}
+137 -97
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;
@@ -61,9 +62,6 @@ struct App {
/// `CADCRAFT_NO_NATIVE_MENU`: the menus stay inside the window.
#[cfg(target_os = "macos")]
menus_in_window: bool,
/// The `movable` flag last set on the main window.
#[cfg(target_os = "macos")]
movable: Option<bool>,
/// Drawings and quit requests from Finder, the Dock and `open -a` (see `apple_events`).
#[cfg(target_os = "macos")]
apple_events: fmv_macos_events::Inbox,
@@ -141,17 +139,18 @@ impl eframe::App for App {
if std::mem::take(&mut self.cad.quit_requested) {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
self.cad.close_path(ctx);
}
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and capture Tab at the command line.
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and hand the frame's root values to the UI
/// runtime.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
follow_desktop(raw, self.desktop_theme.current());
self.cad.raw_input_hook(ctx, raw);
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
self.cad.before_input(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
cadcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
self.cad.guarded_ui(ui);
#[cfg(target_os = "macos")]
craft_window::title_bar::sync_movable(ui.ctx(), &mut self.movable);
}
/// A normal exit: the workspace is saved, and this run's autosave files are not needed (a
/// crash leaves them for recovery).
@@ -184,6 +183,12 @@ pub fn install_io() {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
cadcraft_engine::cmd::file::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())
@@ -199,6 +204,7 @@ pub fn install_io() {
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
}
fn services() -> Services {
@@ -234,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),
@@ -301,18 +336,16 @@ 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`]).
fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
/// 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()))
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size(MIN_INNER_SIZE)
.with_drag_and_drop(true)
.with_app_id(os_window::app_id());
eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title(os_window::name_for(os_window::identity()))
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size(MIN_INNER_SIZE)
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false)
.with_app_id(os_window::app_id()),
viewport: cadcraft_ui_egui::framework::apply_frame(viewport, frame),
// The size, position and maximized state are kept between sessions (#2595); eframe keeps a
// restored window on the monitors that are connected now.
persist_window: true,
@@ -332,17 +365,6 @@ fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
/// 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"))]
@@ -390,14 +412,23 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1))
}
/// A refused launch profile ends with a native dialog on a desktop, and with the reason on standard
/// error everywhere else (a headless runner must never wait for a modal).
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
/// A refused launch profile ends with a native dialog where a modal renders without the app's run
/// loop (Windows, X11/Wayland), and with the reason on standard error everywhere else: a headless
/// runner must never wait for a modal, and on macOS one opened before the event loop never appears.
fn report_launch_profile_error(error: &str) {
eprintln!("CADCraft launch profile: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("CADCraft launch profile: {error}");
return;
@@ -416,35 +447,30 @@ fn report_launch_profile_error(error: &str) {
/// should return success without opening a window.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, logging, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
{
// Plain `--version` or `-V`: answered before resolving a home directory, root validation,
// process identity, logging, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "{}", nightly_version_line());
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| {
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
})
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable };
if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
let launch = launch_profile::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| {
report_launch_profile_error(&error.to_string());
std::process::exit(2)
});
// Launcher's `--launch-profile nightly-v1 --profile-root <dir> --version` (or `-V`):
// `craft_nightly::prepare_launch` leaves the filesystem untouched and installs no profile.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && launch.is_version_query() {
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "{}", nightly_version_line());
return None;
}
let identity = if launch.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable };
if let Err(error) = initialize_nightly_process_identity().map_err(|e| e.to_string()).and_then(|()| os_window::select_identity(identity)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
Some(launch.passthrough_args)
}
/// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe.
@@ -538,12 +564,9 @@ 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);
let persistence_path = vars
.portable_storage_file
.clone()
@@ -553,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)
..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);
@@ -576,22 +599,12 @@ fn main() -> eframe::Result {
// manager showed a "no" cursor. Run through XWayland when it's there; CADCRAFT_WAYLAND=1
// keeps the native Wayland backend.
#[cfg(all(unix, not(target_os = "macos")))]
if std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On {
if forced_x11 {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
}));
}
// macOS: Quit CADCraft (Cmd+Q), the Dock's Quit and logout end the app through AppKit's
// terminate, which would skip the unsaved-changes prompt (#2157). winit turns each into a
// close request for the window instead, so it asks first, as the close button does.
#[cfg(target_os = "macos")]
{
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::macos::EventLoopBuilderExtMacOS;
b.with_close_requested_on_terminate(true);
}));
}
// Registered before the event loop starts, so it catches the Finder event that launched us as
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
#[cfg(target_os = "macos")]
@@ -600,10 +613,14 @@ 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
// it, so nothing after `run_native` can be relied on there.
@@ -617,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;
@@ -666,13 +690,12 @@ fn main() -> eframe::Result {
}
app.session.set_lisp_support_dir(Some(support));
}
app.integrated_titlebar = cfg!(target_os = "macos");
app.integrated_titlebar = cadcraft_ui_egui::framework::draws_title_row(frame.as_ref());
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);
@@ -717,8 +740,6 @@ fn main() -> eframe::Result {
#[cfg(target_os = "macos")]
menus_in_window: vars.no_native_menu == Switch::On,
#[cfg(target_os = "macos")]
movable: None,
#[cfg(target_os = "macos")]
apple_events,
}))
}),
@@ -732,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() {
@@ -756,7 +775,7 @@ mod tests {
/// #1129: the first launch opens centred, not cascaded from the top-left corner.
#[test]
fn the_first_launch_opens_centred() {
let o = window_options(false, STENCIL_BITS);
let o = window_options(false, STENCIL_BITS, None);
assert!(o.centered, "centred on launch");
assert!(o.persist_window, "the window state is saved for the next launch");
}
@@ -764,24 +783,31 @@ mod tests {
/// #2595: a saved window state (size, position, maximized) is restored, not centred over.
#[test]
fn a_saved_window_reopens_where_it_was() {
let o = window_options(true, STENCIL_BITS);
let o = window_options(true, STENCIL_BITS, None);
assert!(!o.centered, "centring would move a restored window");
assert!(o.persist_window);
}
/// `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");
}
}
@@ -789,8 +815,8 @@ mod tests {
#[test]
fn the_window_carries_the_chosen_stencil_bits() {
for bits in [0, STENCIL_BITS] {
assert_eq!(window_options(false, bits).stencil_buffer, bits);
assert_eq!(window_options(true, bits).stencil_buffer, bits);
assert_eq!(window_options(false, bits, None).stencil_buffer, bits);
assert_eq!(window_options(true, bits, None).stencil_buffer, bits);
}
let format = |bits| eframe::egui_wgpu::depth_format_from_bits(0, bits);
assert_eq!(format(0), None, "no stencil: the canvas builds no clip pipelines");
@@ -844,3 +870,17 @@ mod tests {
assert_eq!(raw.system_theme, None);
}
}
#[cfg(test)]
mod refusal_dialog_tests {
use super::refusal_dialog;
use crate::build_flavor::BuildFlavor;
#[test]
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
}
}
+10 -2
View File
@@ -15,6 +15,9 @@ pub struct NativeMenu {
items: HashMap<String, (String, String, MenuItem)>,
submenus: Vec<(String, Submenu)>,
predefined: Vec<(&'static str, PredefinedMenuItem)>,
/// Quit CADCraft: a close request of the main window, so unsaved drawings are asked about first.
/// muda's predefined Quit ends the process through `terminate:` without asking.
quit: MenuItem,
language: &'static str,
/// Monotonic time of the last enablement refresh. `NEG_INFINITY` makes the first poll refresh
/// immediately: `now_ms` starts near zero, so the old `0.0` sentinel suppressed the first
@@ -58,7 +61,6 @@ impl NativeMenu {
("Hide CADCraft", PredefinedMenuItem::hide(Some(i18n::tr(language, "Hide CADCraft")))),
("Hide Others", PredefinedMenuItem::hide_others(Some(i18n::tr(language, "Hide Others")))),
("Show All", PredefinedMenuItem::show_all(Some(i18n::tr(language, "Show All")))),
("Quit CADCraft", PredefinedMenuItem::quit(Some(i18n::tr(language, "Quit CADCraft")))),
];
// The Mac place for preferences: CADCraft ▸ Settings… (⌘,) opens the Options dialog.
let settings = MenuItem::with_id("cc-settings", i18n::tr(language, "Settings..."), true, accel("Cmd+Comma"));
@@ -69,6 +71,8 @@ impl NativeMenu {
let _ = app_menu.append(&PredefinedMenuItem::separator());
}
}
let quit = MenuItem::with_id(craft_quit::QUIT_MENU_ID, i18n::tr(language, "Quit CADCraft"), true, accel("Cmd+Q"));
let _ = app_menu.append(&quit);
items.insert("cc-about".into(), ("ui.dialog.about".into(), "About CADCraft".into(), about));
items.insert("cc-discord".into(), ("ui.discord".into(), "Join the ArtCraft Discord…".into(), discord));
items.insert("cc-settings".into(), ("options".into(), "Settings...".into(), settings));
@@ -85,6 +89,7 @@ impl NativeMenu {
items,
submenus,
predefined,
quit,
language,
last_refresh: f64::NEG_INFINITY,
recent: app.ui.recent_files.clone(),
@@ -114,7 +119,9 @@ impl NativeMenu {
/// Drain queued menu events into commands (Discord opens externally), rebuild Open Recent, retranslate on a language change and refresh enablement when 300 ms have elapsed.
pub fn poll(&mut self, app: &mut CadApp, ctx: &egui::Context) {
while let Ok(ev) = self.events.try_recv() {
if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
if craft_quit::on_menu_event(ctx, ev.id.as_ref()) {
ctx.request_repaint();
} else if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
if cmd == "ui.discord" {
ctx.open_url(egui::OpenUrl::new_tab("https://discord.gg/artcraft"));
} else {
@@ -133,6 +140,7 @@ impl NativeMenu {
for (label, item) in &self.predefined {
item.set_text(i18n::tr(language, label));
}
self.quit.set_text(i18n::tr(language, "Quit CADCraft"));
for (label, submenu) in &self.submenus {
submenu.set_text(i18n::tr_menu(language, label));
}
+167 -556
View File
@@ -1,607 +1,218 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
//! CADCraft's `craft-nightly` isolation specification: stable paths, environment fence,
//! portable-mode markers, folder-only entries, and platform-specific forbidden roots.
use std::ffi::OsString;
use std::path::PathBuf;
use crate::portable::{PORTABLE_DATA_DIR, portable_marker};
use std::path::{Component, Path, PathBuf};
use craft_nightly::AppProfileSpec;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
use crate::portable::PORTABLE_MARKER;
pub const APP_ID: &str = "cadcraft";
/// The app id eframe derives stable's storage folder from (`main.rs` `persistence_path`).
const STABLE_PACKAGE_ID: &str = "ai.storyteller.cadcraft";
/// The app id of the nightly bundle (`packaging/linux/flatpak-bundle.sh`).
const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.cadcraft.nightly";
const STABLE_DIR_NAMES: &[&str] = &["CADCraft", "cadcraft"];
const FORBIDDEN_ENV_VARS: &[&str] = &["CADCRAFT_CONFIG_DIR"];
const PORTABLE_MARKERS: &[&str] = &[PORTABLE_MARKER];
const FOLDER_ONLY_ENTRIES: &[&str] = &["autosave", "logs", "support", "single-instance", "plotters", "crash-reports"];
/// Builds CADCraft's `craft-nightly` isolation specification from the current process environment.
pub fn spec() -> AppProfileSpec {
spec_with_env(|key| std::env::var_os(key))
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
// CADCraft also builds for the BSDs (packaging/freebsd): nightly-v1 is Windows, macOS and
// Linux only, as the shared nightlies publish.
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
fn spec_with_env(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
AppProfileSpec {
app_id: APP_ID,
display_name: "CADCraft",
stable_dir_names: STABLE_DIR_NAMES,
stable_package_id: STABLE_PACKAGE_ID,
nightly_package_id: NIGHTLY_PACKAGE_ID,
profile_root_env: None,
forbidden_env_vars: FORBIDDEN_ENV_VARS,
portable_markers: PORTABLE_MARKERS,
folder_only_entries: FOLDER_ONLY_ENTRIES,
extra_forbidden_roots: extra_forbidden_roots(&env),
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
fn extra_forbidden_roots(env: &impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
let mut roots = Vec::new();
#[cfg(target_os = "windows")]
{
// The MSI's per-machine install folder (`cadcraft.wxs`).
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = non_empty_abs(env, key) {
roots.push(base.join("ArtCraft").join("CADCraft"));
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
// A component that is not valid UTF-8 keeps its exact bytes: a lossy comparison would fold two
// different names into the same replacement character and call them one folder.
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str();
match (platform.ignores_case(), value.to_str()) {
(true, Some(text)) => OsString::from(text.to_lowercase()),
_ => value.to_os_string(),
}
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
#[cfg(all(unix, not(target_os = "macos")))]
{
roots.extend(["/usr/bin/cadcraft", "/usr/local/bin/cadcraft", "/opt/cadcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
if let Some(home) = non_empty_abs(env, "HOME") {
roots.push(home.join(".var/app/ai.storyteller.cadcraft"));
}
}
Ok(parent.to_path_buf())
}
/// Every stable CADCraft data root of this platform, plus the install folders and the running
/// install ([`installation_boundary`]).
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("CADCraft")))
.collect::<Result<Vec<_>, _>>()?;
// Stable's eframe storage folder (`eframe::storage_dir`: `app.ron` under
// `%APPDATA%\ai.storyteller.cadcraft\data`), outside the roaming `CADCraft` folder.
roots.push(required_base(env, "APPDATA")?.join(EFRAME_APP_ID));
// The MSI's per-machine folder (cadcraft.wxs). A custom install folder is not known
// here; the executable's own folder is fenced below.
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("CADCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("cadcraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.extend(["/usr/bin/cadcraft", "/usr/local/bin/cadcraft", "/opt/cadcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.cadcraft"));
// Stable's eframe storage folder (`eframe::storage_dir`: window state, Options profile,
// UI and autosave prefs in `app.ron`), which is not the XDG settings folder above.
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(EFRAME_APP_ID));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
#[cfg(target_os = "macos")]
{
if let Some(home) = non_empty_abs(env, "HOME") {
let library = home.join("Library");
vec![
library.join("Application Support/CADCraft"),
library.join("Caches/CADCraft"),
library.join("Caches/ai.storyteller.cadcraft"),
// Stable's eframe storage folder (`eframe::storage_dir`: `app.ron` in Application
// Support), beside the settings folder env.rs uses.
library.join("Application Support").join(EFRAME_APP_ID),
library.join("Preferences/CADCraft"),
library.join("Preferences/ai.storyteller.cadcraft.plist"),
library.join("Saved Application State/ai.storyteller.cadcraft.savedState"),
home.join("Applications/CADCraft.app"),
PathBuf::from("/Applications/CADCraft.app"),
]
roots.push(library.join("Preferences/ai.storyteller.cadcraft.plist"));
roots.push(library.join("Saved Application State/ai.storyteller.cadcraft.savedState"));
roots.push(home.join("Applications/CADCraft.app"));
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
roots.push(PathBuf::from("/Applications/CADCraft.app"));
}
roots
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
// A regular file in a folder's place is not a folder: the readers and sweepers that follow would
// fail halfway, so refuse it while the profile is still being validated.
match std::fs::symlink_metadata(&child) {
Ok(metadata) if !metadata.file_type().is_dir() => {
return Err(format!("the nightly {label} must be a directory, not a file or an alias"));
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
}
Ok(child)
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
let value = env(key).filter(|v| !v.is_empty())?;
let path = PathBuf::from(value);
path.is_absolute().then_some(path)
}
/// Every existing entry directly in the profile (logs, settings and so on) must resolve inside it,
/// so a link there cannot point Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
Ok(())
}
/// Recognise the shared portable data namespace in both the supplied and resolved path.
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
// A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a
// marker only counts beside a CADCraft executable, so an unrelated portable.txt higher up
// (in a user folder or at a drive root) does not refuse the profile.
path.ancestors().enumerate().any(|(depth, ancestor)| {
portable_marker(ancestor).is_some() && (depth == 0 || ["cadcraft.exe", "cadcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
}) || path.components().any(|component| match component {
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
Component::Normal(name) => name == PORTABLE_DATA_DIR,
_ => false,
})
}
/// The writable hook is the app's existing exclusive probe (`portable::probe`). Keeping it injected
/// lets filesystem boundary tests exercise the real policy without starting the app or changing
/// global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
let chosen = canonical_future(root)?;
// The deb/rpm CLI wrapper exports CADCRAFT_CONFIG_DIR at the folder this launch already owns (the
// GUI wrappers name the profile through `--profile-root` instead), so that value is inert:
// `env::apply_profile` sets the settings folder from the profile, not from the variable. Any
// other value would redirect Nightly's settings folder, so it is refused.
if let Some(configured) = env("CADCRAFT_CONFIG_DIR").filter(|v| !v.is_empty()) {
let configured = canonical_future(&absolute(PathBuf::from(configured), "CADCRAFT_CONFIG_DIR")?)?;
if !configured.starts_with(&chosen) {
return Err("nightly-v1 cannot be combined with CADCRAFT_CONFIG_DIR outside its own profile".into());
}
}
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
{
// A Flatpak's data folder and runtime socket namespace belong to its app id. The nightly
// bundle has an id of its own ([`NIGHTLY_FLATPAK_ID`], named by
// `packaging/linux/flatpak-bundle.sh`), so its profile is already the sandbox's own; any
// other instance is the stable app's (or another app's), whose socket this profile must
// not inherit.
if id.to_string_lossy() != NIGHTLY_FLATPAK_ID {
return Err("nightly-v1 cannot inherit another Flatpak app's instance; launch through the native Launcher".into());
}
}
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
return Err("the nightly root must not use a portable CADCraft installation or its CADCraftData settings folder".into());
}
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
entries_stay_inside(&chosen)?;
// Drawing Recovery reads, adopts, overwrites and sweeps entries. Never let its alias leave this
// private profile, including toward a stable portable directory not in our known roots.
private_subdirectory(&chosen, AUTOSAVE, "recovery folder")?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
private_subdirectory(&confirmed, AUTOSAVE, "recovery folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
/// The app id of the nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`): the one Flatpak
/// instance whose sandbox is this channel's own. The window identity ([`crate::os_window`]) and the
/// bundle id differ on purpose, as they do for stable.
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.cadcraft.nightly";
/// The app id eframe derives stable's storage folder from ([`crate::main`]'s `persistence_path`).
/// A profile that sits there would overwrite stable's `app.ron`, so its folder is fenced too.
const EFRAME_APP_ID: &str = "ai.storyteller.cadcraft";
/// The subfolder autosave and Drawing Recovery write ([`crate::main`], `<settings>/autosave`).
pub const AUTOSAVE: &str = "autosave";
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
use craft_nightly::{ProfileError, validate_and_prepare_root};
impl Fixture {
fn new() -> Self {
use super::{
APP_ID, FOLDER_ONLY_ENTRIES, FORBIDDEN_ENV_VARS, NIGHTLY_PACKAGE_ID, PORTABLE_MARKERS, STABLE_DIR_NAMES, STABLE_PACKAGE_ID, spec,
spec_with_env,
};
struct TempDir(PathBuf);
impl TempDir {
fn new(label: &str) -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("cadcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let candidate = std::env::temp_dir().join(format!(
"cadcraft-profile-spec-{}-{}-{label}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
Err(error) => panic!("cannot create temp dir: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/cadcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
|dir| {
let probe = dir.join("exclusive-test-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
},
)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
Self(root)
}
}
impl Drop for Fixture {
impl Drop for TempDir {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn portable_settings_from_another_install_are_refused_before_any_probe() {
let fixture = Fixture::new();
let stable_install = fixture.root.join("stable portable install");
let stable_data = stable_install.join(PORTABLE_DATA_DIR);
std::fs::create_dir_all(&stable_data).unwrap();
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "a different portable install is not a private Nightly profile");
assert!(!probed.get(), "reject portable data before a writable probe");
assert!(!stable_data.join("nested nightly").exists());
assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change");
assert_eq!(std::fs::read_dir(&stable_data).unwrap().count(), 1);
}
}
let private = fixture.root.join("CADCraftData-backup-name/nightly");
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component");
}
fn spec_preserves_cadcraft_isolation_constants_and_extra_forbidden_roots() {
let mut env = BTreeMap::<String, OsString>::new();
#[cfg(target_os = "windows")]
env.insert("ProgramFiles".into(), OsString::from(r"C:\Program Files"));
#[cfg(not(target_os = "windows"))]
env.insert("HOME".into(), OsString::from("/home/tester"));
#[cfg(unix)]
#[test]
fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
let fixture = Fixture::new();
let stable = fixture.home().join(".local/state/cadcraft/autosave");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join(AUTOSAVE)).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
let s = spec_with_env(|key| env.get(key).cloned());
assert_eq!(s.app_id, APP_ID);
assert_eq!(s.display_name, "CADCraft");
assert_eq!(s.stable_dir_names, STABLE_DIR_NAMES);
assert_eq!(s.stable_package_id, STABLE_PACKAGE_ID);
assert_eq!(s.nightly_package_id, NIGHTLY_PACKAGE_ID);
assert_eq!(s.profile_root_env, None);
assert_eq!(s.forbidden_env_vars, FORBIDDEN_ENV_VARS);
assert_eq!(s.portable_markers, PORTABLE_MARKERS);
assert_eq!(s.folder_only_entries, FOLDER_ONLY_ENTRIES);
#[cfg(target_os = "windows")]
assert!(s.extra_forbidden_roots.contains(&PathBuf::from(r"C:\Program Files\ArtCraft\CADCraft")));
#[cfg(all(unix, not(target_os = "macos")))]
{
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/usr/bin/cadcraft")));
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/usr/local/bin/cadcraft")));
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/opt/cadcraft")));
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/.var/app/ai.storyteller.cadcraft")));
}
#[cfg(target_os = "macos")]
{
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/Library/Preferences/ai.storyteller.cadcraft.plist")));
assert!(
s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/Library/Saved Application State/ai.storyteller.cadcraft.savedState"))
);
assert!(result.is_err(), "autosave must not escape the private profile or follow a dangling alias");
assert!(!probed.get());
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/Applications/CADCraft.app")));
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/Applications/CADCraft.app")));
}
let private = fixture.root.join("nightly-self");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&private, private.join(AUTOSAVE)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_err(), "autosave cannot treat all profile settings as recovery entries");
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
}
#[test]
fn nightly_profile_reopens_with_saved_state_and_enforces_folder_only_entries() {
let temp = TempDir::new("reopen");
let private = temp.0.join("nightly-profile");
let s = spec();
let canonical = validate_and_prepare_root(&private, &s).unwrap();
assert_eq!(canonical, private);
for name in ["app.ron", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in FOLDER_ONLY_ENTRIES {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(validate_and_prepare_root(&private, &s).unwrap(), private);
for name in ["app.ron", "nightly-session.lock", "nightly-session.json"] {
assert_eq!(std::fs::read(private.join(name)).unwrap(), b"saved profile data", "{name} changed when reopening");
}
for name in FOLDER_ONLY_ENTRIES {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(matches!(validate_and_prepare_root(&private, &s), Err(ProfileError::ExpectedDirectoryEntry(_))), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
#[test]
fn a_non_directory_profile_stops_startup_without_installing_a_profile() {
let temp = TempDir::new("invalid-root");
let root = temp.0.join("ordinary-file");
std::fs::write(&root, b"existing file").unwrap();
let argv = craft_nightly::launch_arguments(&root, &[]);
assert!(craft_nightly::current().is_none());
let result = crate::launch_profile::prepare(craft_nightly::BuildFlavor::NightlyV1, argv);
assert!(matches!(result, Err(ProfileError::NotADirectory(_))));
assert!(craft_nightly::current().is_none());
assert_eq!(std::fs::read(root).unwrap(), b"existing file");
}
#[cfg(unix)]
#[test]
fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let recovery = private.join("private-recovery");
std::fs::create_dir_all(&recovery).unwrap();
std::os::unix::fs::symlink(&recovery, private.join(AUTOSAVE)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
assert_eq!(std::fs::canonicalize(private.join(AUTOSAVE)).unwrap(), recovery);
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/cadcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join(AUTOSAVE), platform));
assert!(overlaps(&root.join(AUTOSAVE), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("cadcraft-other"), platform));
}
}
#[test]
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("cadcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
// Stable's eframe storage folder holds `app.ron`, so a profile may not sit at or inside it.
let storage = data.join(EFRAME_APP_ID);
std::fs::create_dir_all(&storage).unwrap();
std::fs::write(storage.join("app.ron"), b"stable window state").unwrap();
for candidate in [storage.clone(), storage.join("nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"), "{}", candidate.display());
}
assert_eq!(std::fs::read(storage.join("app.ron")).unwrap(), b"stable window state");
let nightly = data.join("ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/CADCraft Nightly.app/Contents/MacOS/CADCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/CADCraft",
"Application Support/ai.storyteller.cadcraft",
"Caches/CADCraft",
"Caches/ai.storyteller.cadcraft",
"Preferences/CADCraft",
"Saved Application State/ai.storyteller.cadcraft.savedState",
] {
let stable = library.join(suffix);
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
// The bundle path and the Library fences fold case on macOS.
let cased = library.join("application support/cadcraft/nightly");
assert!(fixture.check(Platform::Mac, &cased).is_err());
}
#[test]
fn windows_fences_roaming_local_and_both_install_folders() {
let mut fixture = Fixture::new();
fixture.env.insert("ProgramFiles".into(), fixture.root.join("program files").into_os_string());
for stable in [
fixture.root.join("roaming/CADCraft"),
fixture.root.join("roaming/ai.storyteller.cadcraft"),
fixture.root.join("local/CADCraft"),
fixture.root.join("program files/ArtCraft/CADCraft"),
] {
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly")] {
assert!(fixture.check(Platform::Windows, &candidate).unwrap_err().contains("overlap"), "{}", candidate.display());
}
// Windows folder names ignore case.
assert!(fixture.check(Platform::Windows, &stable.with_file_name("cadcraft")).is_err());
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let valid = fixture.root.join("local/ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Windows, &valid).unwrap(), valid);
}
#[test]
fn config_dir_and_flatpak_are_refused() {
let mut fixture = Fixture::new();
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), fixture.root.join("custom").into_os_string());
let private = fixture.root.join("nightly-config");
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("CADCRAFT_CONFIG_DIR"));
assert!(!private.exists());
fixture.env.remove("CADCRAFT_CONFIG_DIR");
for inherited in ["ai.storyteller.cadcraft", "org.freedesktop.other"] {
fixture.env.insert("FLATPAK_ID".into(), inherited.into());
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("Flatpak"), "{inherited}");
assert!(!private.exists());
}
}
/// The nightly bundle runs under an app id of its own, so its sandbox data folder is this
/// channel's data root; that one instance is accepted, and its profile stays inside it.
#[test]
fn the_nightly_flatpaks_own_instance_accepts_its_own_profile() {
let mut fixture = Fixture::new();
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
let private = fixture.home().join(".var/app/ai.storyteller.cadcraft.nightly/data/cadcraft-nightly");
assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private);
// Stable's Flatpak folder is still fenced even inside the nightly instance.
let stable = fixture.home().join(".var/app/ai.storyteller.cadcraft");
assert!(fixture.check(Platform::Linux, &stable).unwrap_err().contains("overlap"));
}
/// A Linux Launcher wrapper exports `CADCRAFT_CONFIG_DIR` at the profile it launches; that is
/// the folder this launch already owns, so it must not refuse the profile. Anything else is
/// still a redirect.
#[test]
fn a_wrapper_naming_the_profile_in_config_dir_is_accepted() {
let mut fixture = Fixture::new();
let private = fixture.root.join("nightly-wrapper");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), private.clone().into_os_string());
assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private);
let inside = private.join("nested");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), inside.clone().into_os_string());
assert!(fixture.check(Platform::Linux, &inside).is_ok(), "a folder inside the profile is the profile's own");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), fixture.root.join("elsewhere").into_os_string());
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("CADCRAFT_CONFIG_DIR"));
}
#[test]
fn a_profile_that_cannot_be_written_is_refused_without_a_stable_fallback() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-unwritable");
let result = validate_for(Platform::Linux, &private, |key| fixture.get(key), Some(&fixture.exe), |_| Err(std::io::Error::other("read-only")));
assert!(result.unwrap_err().contains("not writable"));
assert!(private.exists(), "the profile was created before the probe, and nothing was written into stable");
assert!(!fixture.home().join(".config/cadcraft").exists());
}
#[cfg(unix)]
#[test]
fn a_dangling_entry_inside_the_profile_is_refused_before_writes() {
let fixture = Fixture::new();
let outside = fixture.root.join("outside");
fn symlinks_inside_profile_root_are_refused() {
let temp = TempDir::new("symlink");
let outside = temp.0.join("outside");
let private = temp.0.join("nightly-profile");
std::fs::create_dir_all(&outside).unwrap();
let private = fixture.root.join("nightly-dangling");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(outside.join("missing"), private.join("logs")).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err());
assert!(!probed.get());
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
std::fs::create_dir_all(&private).unwrap();
std::os::unix::fs::symlink(outside.join("target"), private.join("autosave")).unwrap();
let err = validate_and_prepare_root(&private, &spec()).unwrap_err();
assert!(matches!(err, ProfileError::SymlinkEntry(_)), "unexpected error: {err}");
}
}
+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());
}
}
+58
View File
@@ -428,4 +428,62 @@ mod tests {
received.sort();
assert_eq!(received, handed);
}
/// A Nightly profile on Windows keeps its single-instance AF_UNIX socket under
/// `<profile>\single-instance\*.sock`. Both a live socket (while a first Nightly copy is
/// running and a second document launch prepares to hand off) and a leftover/stale socket
/// (after the first copy exits, or from an earlier Nightly build) must pass profile
/// validation, and the next launch must reclaim the stale socket and accept subsequent
/// document handoffs.
#[cfg(windows)]
#[test]
fn nightly_profile_allows_live_and_stale_single_instance_socket_for_handoff_and_reopen() {
use std::ffi::OsString;
use craft_nightly::{BuildFlavor, Profile, StartupOptions, launch_arguments, parse_startup, validate_and_prepare_root};
let profile = std::env::temp_dir().join(format!("cc-ni-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&profile);
std::fs::create_dir_all(&profile).unwrap();
let _cleanup = Cleanup(profile.clone());
let spec = crate::profile_root::spec();
let prepare_profile = |doc: &str| {
let argv = launch_arguments(&profile, &[OsString::from(doc)]);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
let Profile::NightlyV1(root) = launch.profile else {
panic!("expected NightlyV1 profile");
};
validate_and_prepare_root(&root, &spec).unwrap();
launch.passthrough_args
};
let sock_path = socket_path(Some(&profile)).unwrap();
std::fs::create_dir_all(sock_path.parent().unwrap()).unwrap();
if !can_bind(&sock_path) {
return;
}
// 1. Live socket in `<profile>\single-instance\*.sock`: second-document launch must not
// be refused by profile validation before handoff.
let listener = uds_windows::UnixListener::bind(&sock_path).unwrap();
assert_eq!(prepare_profile("second.dwg"), [OsString::from("second.dwg")]);
// 2. First instance exits leaving a leftover/stale socket behind: reopening must pass
// profile validation and reclaim the socket as the new primary instance.
drop(listener);
assert!(sock_path.exists(), "stale socket remains after exit");
assert_eq!(prepare_profile("reopen.dwg"), [OsString::from("reopen.dwg")]);
let Claim::Primary(server) = claim(&[], false, Some(&profile)) else {
panic!("failed to reclaim stale single-instance socket in nightly profile");
};
// 3. While the reclaimed primary instance is running (socket + election lock both live in
// `<profile>\single-instance`), launching a second document passes profile validation
// and hands off to the running instance.
let second_doc = profile.join("second.dwg").to_string_lossy().into_owned();
assert_eq!(prepare_profile(&second_doc), [OsString::from(&second_doc)]);
assert!(matches!(claim(std::slice::from_ref(&second_doc), true, Some(&profile)), Claim::HandedOff));
assert_eq!(server.take_paths(), [PathBuf::from(&second_doc)]);
}
}
+5 -5
View File
@@ -252,7 +252,7 @@ mod tests {
app.run("ui.dock", json!({"operation":"move", "panel":"layers", "target":"properties", "zone":"left"})).unwrap();
app.run("ui.dock", json!({"operation":"float", "panel":"properties", "rect":[120,90,340,410]})).unwrap();
ui.docking = app.ui.docking;
ui.docking.set_visible(Panel::ToolSets, false, None, permissions).unwrap();
ui.docking.set_visible(Panel::ToolSets, false, None, false, permissions).unwrap();
ui.show_toolsets = false;
store.save_if_changed(&ui, Instant::now()).unwrap();
let saved: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
@@ -263,9 +263,9 @@ mod tests {
assert_eq!(serde_json::to_value(&reloaded.docking).unwrap(), serde_json::to_value(&ui.docking).unwrap());
assert!(!reloaded.show_toolsets);
reveal_panel(&mut reloaded.docking, Panel::ToolSets).unwrap();
let tools = reloaded.docking.layout.location(&Panel::ToolSets).unwrap();
let tools = reloaded.docking.layout().location(&Panel::ToolSets).unwrap();
assert_eq!(serde_json::to_value(&tools.group).unwrap()["column"]["side"], json!("Start"), "{tools:?}");
assert_eq!(reloaded.docking.layout.floating[0].rect, [120.0, 90.0, 340.0, 410.0]);
assert_eq!(reloaded.docking.layout().floating[0].rect, egui::Rect::from_min_size(egui::pos2(120.0, 90.0), egui::vec2(340.0, 410.0)));
fs::remove_dir_all(directory).unwrap();
}
@@ -293,8 +293,8 @@ mod tests {
assert_eq!(ui.toolset_tab, "Modeling");
assert_eq!(ui.history_lines, 4);
assert!(!ui.show_toolsets && ui.show_palettes && !ui.show_toolbar);
assert_eq!(ui.docking.layout, default_workspace().layout);
assert!(ui.docking.hidden.is_empty(), "{:?}", ui.docking.hidden);
assert_eq!(ui.docking.layout(), default_workspace().layout());
assert!(ui.docking.hidden().is_empty(), "{:?}", ui.docking.hidden());
fs::remove_dir_all(directory).unwrap();
}
-3
View File
@@ -2,7 +2,4 @@ allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
allow-indexing-slicing-in-tests = true
disallowed-types = [
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
]
cognitive-complexity-threshold = 30
+1
View File
@@ -0,0 +1 @@
9fa32aecf2759cd61bb216a958df68da619798f3
+4 -3
View File
@@ -238,8 +238,9 @@ mod tests {
assert!(f.t.near(g.t, 1e-3), "{f:?} {g:?}");
assert!((f.k - g.k).abs() < 1e-2, "{f:?} {g:?}");
}
// An unclamped (periodic) spline has no ends.
let closed = GSpline::from_fit_points_closed(&[Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)]);
assert!(spline_end(&closed, false).is_none());
// An unclamped spline has no ends: one whose control points wrap round.
let fit = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)];
let closed = GSpline::fit_with(&fit, true, cadcraft_geom::FitOptions { knots: cadcraft_geom::KnotParam::Uniform, ..Default::default() });
assert!(closed.wraps() && spline_end(&closed, false).is_none());
}
}
+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();
+6 -3
View File
@@ -47,7 +47,7 @@ mod proxy;
mod text;
mod wipeout;
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, mtext_literal};
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};
@@ -399,7 +399,9 @@ impl EntityKind {
t3(p);
}
if let DimKind::Linear { rotation } = &mut d.kind {
*rotation = cadcraft_geom::norm_angle(*rotation + rot);
// A mirror reflects the dimension line's direction about the mirror line:
// `rot` is twice the mirror line's angle, so `a` lands at `rot - a`.
*rotation = cadcraft_geom::norm_angle(if mirror { rot - *rotation } else { *rotation + rot });
}
d.marks.transform(&t3, rot, s, mirror);
d.block = None;
@@ -617,7 +619,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()
}
+67
View File
@@ -1,3 +1,6 @@
use std::cmp::Ordering;
use std::collections::BTreeMap;
use super::common::{Common, Lineweight};
use super::text::{MText, Text};
use super::{Color, Deserialize, EntityKind, Mat3, Serialize, Vec2, Vec3};
@@ -142,6 +145,43 @@ impl AttribProps {
}
}
/// An attribute tag as attributes are matched to their definitions and to each other: ASCII
/// letters in either case are the same tag, other characters must be equal. As an ordered map key
/// it finds the match in a logarithmic number of comparisons, where comparing each attribute with
/// each definition costs their product on a block with many of both (#1923). It orders, rather
/// than hashes, so the cost doesn't depend on hash keys a crafted file could predict (the web
/// build's `RandomState`), as in the layer and block name index.
#[derive(Clone, Copy, Debug)]
pub struct TagKey<'a>(pub &'a str);
impl TagKey<'_> {
/// 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> + '_ {
self.0.bytes().map(|b| b.to_ascii_lowercase())
}
}
impl PartialEq for TagKey<'_> {
fn eq(&self, other: &Self) -> bool {
self.0.eq_ignore_ascii_case(other.0)
}
}
impl Eq for TagKey<'_> {}
impl Ord for TagKey<'_> {
fn cmp(&self, other: &Self) -> Ordering {
self.folded().cmp(other.folded())
}
}
impl PartialOrd for TagKey<'_> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Insert {
@@ -204,4 +244,31 @@ impl Insert {
.then_before(Mat3::scale(self.scale.x, self.scale.y))
.then_before(Mat3::translate(-base))
}
/// The reference's attributes by tag: of several with one tag (in any ASCII case), the first.
/// Built once, it tells whether the reference carries a definition's tag, and its value, in
/// one lookup instead of a pass over the attributes per definition (#1923).
pub fn attribs_by_tag(&self) -> BTreeMap<TagKey<'_>, &Attrib> {
let mut by_tag = BTreeMap::new();
for a in &self.attribs {
by_tag.entry(TagKey(a.tag.as_str())).or_insert(a);
}
by_tag
}
}
impl crate::Block {
/// The block's attribute definitions by tag: of several with one tag (in any ASCII case), the
/// first in the block's order, the one an attribute of that tag takes its properties from.
/// Built once for all of a reference's attributes, it matches each in one lookup instead of a
/// pass over the block per attribute (#1923).
pub fn attdefs_by_tag(&self) -> BTreeMap<TagKey<'_>, &crate::Entity> {
let mut by_tag = BTreeMap::new();
for e in self.entities.iter() {
if let EntityKind::AttDef(a) = &e.kind {
by_tag.entry(TagKey(a.tag.as_str())).or_insert(e.as_ref());
}
}
by_tag
}
}
+3 -1
View File
@@ -100,7 +100,9 @@ impl DimMarks {
/// Transform the points and angles (part of [`super::EntityKind::transform`]).
pub(super) fn transform(&mut self, t3: &dyn Fn(&mut Vec3), rot: f64, s: f64, mirror: bool) {
if let Some(a) = &mut self.oblique {
*a = cadcraft_geom::norm_angle(if mirror { rot - (*a - rot) } else { *a + rot });
// A mirror reflects a direction about the mirror line: `rot` is the transformed X
// axis (twice the mirror line's angle), so a direction `a` lands at `rot - a`.
*a = cadcraft_geom::norm_angle(if mirror { rot - *a } else { *a + rot });
}
if let Some(j) = &mut self.jog_line {
t3(j);
+448 -46
View File
@@ -1,10 +1,10 @@
//! Approximate entity bounds (used for extents, zoom and selection pre-filtering).
use std::collections::HashMap;
use std::collections::{BTreeMap, HashMap};
use cadcraft_geom::{Arc, Bounds2, EPS, Polyline, Vec2, bulge_to_arc};
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim};
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim, TagKey};
/// Nested block references deeper than this are ignored (cyclic or hostile files).
pub const MAX_BLOCK_DEPTH: usize = 16;
@@ -246,23 +246,68 @@ pub fn ole_frame_accepts(m: &cadcraft_geom::Mat3) -> bool {
/// the same way the renderer places it (the stroke font is about 0.88 of the height per character).
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;
let natural = t.height * 0.9 * t.width_factor.abs().max(0.01) * len.max(1) 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.max(1) 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.max(1) as f64;
// The fonts leave a line of next to no width as it is, neither stretched nor scaled.
let no_width = shaped * MARGIN <= 1e-12;
let (w, h, rotation) = match (span, second) {
(Some(_), Some(p)) if no_width => (shaped, 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, origin.angle_to(p)),
(Some(d), Some(p)) if t.halign == HAlign::Fit => (d, height, origin.angle_to(p)),
// Shrunk into a span shorter than its width, Aligned text is no taller than its own height,
// however narrow its characters are.
(Some(d), Some(p)) => (d, (height * d / shaped).max(height), origin.angle_to(p)),
_ => (natural, 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,
(HAlign::Middle, _) => -h / 2.0,
(_, VAlign::Baseline) => 0.0,
(_, VAlign::Bottom) => t.height / 3.0,
(_, VAlign::Middle) => -t.height / 2.0,
(_, VAlign::Top) => -t.height,
(_, VAlign::Bottom) => h / 3.0,
(_, VAlign::Middle) => -h / 2.0,
(_, VAlign::Top) => -h,
};
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, dy), Vec2::new(dx + w, dy), Vec2::new(dx + w, dy + h), Vec2::new(dx, dy + h)];
Bounds2::from_points(local.map(|p| origin + p.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,60 +315,76 @@ 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
/// definition's (layer "0" being the insert's).
fn attrib_layer<'a>(d: &'a Drawing, ins: &crate::Insert, a: &'a crate::Attrib) -> &'a str {
a.props.layer.as_deref().unwrap_or_else(|| {
d.block(&ins.block)
.and_then(|blk| blk.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag))))
.map_or("0", |be| be.common.layer.as_str())
})
/// definition's, from the block's definitions by tag `defs` (layer "0" being the insert's).
fn attrib_layer<'a>(defs: Option<&BTreeMap<TagKey<'a>, &'a Entity>>, a: &'a crate::Attrib) -> &'a str {
a.props.layer.as_deref().unwrap_or_else(|| defs.and_then(|defs| defs.get(&TagKey(&a.tag))).map_or("0", |be| be.common.layer.as_str()))
}
/// The bounds of a block's contents, in block coordinates: its geometry, which every reference to
/// the block shows, and the value of each constant attribute definition ATTMODE shows, by tag, which
/// only a block reference draws (a dimension's block does not), and only when the reference
/// carries no attribute of that tag. They are kept apart so that the one cache serves every
/// reference, whichever asks first.
/// reference, whichever asks first. Also the block's attribute definitions by tag, for the layer
/// of an attribute that has none of its own.
struct Contents<'a> {
geometry: Bounds2,
constants: Vec<(&'a str, Bounds2)>,
defs: BTreeMap<TagKey<'a>, &'a Entity>,
}
impl Contents<'_> {
/// What reference `ins` shows of the block: its geometry and the constant values `ins` has
/// no attribute for (that attribute is drawn instead, and counted with the attributes).
fn in_reference(&self, ins: &crate::Insert) -> Bounds2 {
self.constants
.iter()
.filter(|(tag, _)| !ins.attribs.iter().any(|r| r.tag.eq_ignore_ascii_case(tag)))
.fold(self.geometry, |b, (_, c)| b.union(c))
if self.constants.is_empty() {
return self.geometry;
}
// The reference's tags are gathered once, not scanned again for each constant (#1923).
let carried = ins.attribs_by_tag();
self.constants.iter().filter(|(tag, _)| !carried.contains_key(&TagKey(tag))).fold(self.geometry, |b, (_, c)| b.union(c))
}
}
/// [`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) {
let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new() };
let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new(), defs: blk.attdefs_by_tag() };
// ATTMODE, as the renderer applies it to a constant value: 0 shows none, 1 the visible
// ones, 2 all of them.
let attmode = d.header.i64("ATTMODE", 1);
@@ -334,11 +395,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,6 +410,20 @@ 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 {
@@ -394,13 +471,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 +495,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 +593,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,8 +602,20 @@ 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,
@@ -487,9 +636,21 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
// one draws nothing, so it contributes nothing: ZOOM Extents must not fly off to its
// insertion point. Attributes below still count.
let mut b = Bounds2::EMPTY;
let mut defs = None;
if let Some(blk) = d.block(&ins.block) {
let m = ins.transform(blk.base.xy());
let inner = contents(d, blk, depth, blocks, off_counts).map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
let c = contents(d, blk, depth, blocks, in_drawing, off_counts, frozen);
defs = c.map(|c| &c.defs);
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).
@@ -511,7 +672,7 @@ 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(d, ins, 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()),
@@ -548,7 +709,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();
@@ -567,7 +728,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
}
@@ -587,7 +748,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() {
@@ -871,6 +1032,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]
+76
View File
@@ -113,6 +113,43 @@ impl Foreign {
&& self.appids.is_empty()
}
/// Re-key what is kept for the record named `from` under each of `kinds` (e.g. `["LAYER"]`, or
/// `["BLOCK_RECORD", "BLOCK", "ENDBLK"]` for a block) to the name `to`, after a rename: its
/// extras ([`Foreign::records`]) and the roles of its file handles ([`Foreign::targets`]), so
/// saving writes its xdata, extension dictionary and reactors on the renamed record. Names
/// compare trimmed and upper-case, as the reader keys them, so a rename that only changes case
/// changes nothing.
pub fn rename(&mut self, kinds: &[&str], from: &str, to: &str) {
let (from, to) = (from.trim().to_ascii_uppercase(), to.trim().to_ascii_uppercase());
if from == to {
return;
}
for kind in kinds {
let old: ForeignKey = ((*kind).to_string(), from.clone());
let new: ForeignKey = ((*kind).to_string(), to.clone());
if let Some(extra) = self.records.remove(&old) {
self.records.insert(new.clone(), extra);
}
self.targets.values_mut().filter(|k| **k == old).for_each(|k| *k = new.clone());
}
}
/// Whether anything is kept for the record named `from` under one of `kinds`: what
/// [`Foreign::rename`] would re-key.
pub fn names(&self, kinds: &[&str], from: &str) -> bool {
let from = from.trim().to_ascii_uppercase();
let hit = |k: &ForeignKey| k.1 == from && kinds.contains(&k.0.as_str());
self.records.keys().any(hit) || self.targets.values().any(hit)
}
/// [`Foreign::rename`] on a drawing's shared copy, which is cloned only when it keeps
/// something for the renamed record and the name really changes (not only its case).
pub fn rename_shared(this: &mut std::sync::Arc<Foreign>, kinds: &[&str], from: &str, to: &str) {
if !from.trim().eq_ignore_ascii_case(to.trim()) && this.names(kinds, from) {
std::sync::Arc::make_mut(this).rename(kinds, from, to);
}
}
/// The entities with a geometry record in the data store: an `ACDSRECORD` naming the entity
/// (320) that holds its `ASM_Data`. A 320 without one doesn't keep an entity's geometry.
pub fn data_store_entities(&self) -> std::collections::BTreeSet<Handle> {
@@ -390,3 +427,42 @@ pub fn class_number<S: AsRef<str>>(groups: impl IntoIterator<Item = (i32, S)> +
pub fn class_index(number: Option<i64>) -> Option<usize> {
usize::try_from(number?.checked_sub(500)?).ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn key(k: &str, n: &str) -> ForeignKey {
(k.to_string(), n.to_string())
}
#[test]
fn rename_rekeys_records_and_targets_of_the_given_kinds_only() {
let mut f = Foreign::default();
let xdict = ForeignExtra { xdict: Some(Handle(0x40)), ..ForeignExtra::default() };
f.records.insert(key("BLOCK_RECORD", "DOOR"), xdict.clone());
f.records.insert(key("LAYER", "DOOR"), ForeignExtra { reactors: vec![Handle(0x41)], ..ForeignExtra::default() });
f.targets.insert(Handle(0x10), key("BLOCK_RECORD", "DOOR"));
f.targets.insert(Handle(0x11), key("BLOCK", "DOOR"));
f.targets.insert(Handle(0x12), key("LAYER", "DOOR"));
f.rename(&["BLOCK_RECORD", "BLOCK", "ENDBLK"], "Door", "Gate");
assert_eq!(f.records.get(&key("BLOCK_RECORD", "GATE")), Some(&xdict));
assert!(!f.records.contains_key(&key("BLOCK_RECORD", "DOOR")));
assert!(f.records.contains_key(&key("LAYER", "DOOR")), "another kind with the same name stays");
assert_eq!(f.targets.get(&Handle(0x10)), Some(&key("BLOCK_RECORD", "GATE")));
assert_eq!(f.targets.get(&Handle(0x11)), Some(&key("BLOCK", "GATE")));
assert_eq!(f.targets.get(&Handle(0x12)), Some(&key("LAYER", "DOOR")));
}
#[test]
fn rename_shared_leaves_an_unrelated_drawing_shared() {
let mut f = Foreign::default();
f.records.insert(key("LAYER", "A"), ForeignExtra { xdict: Some(Handle(0x40)), ..ForeignExtra::default() });
let mut a = std::sync::Arc::new(f);
let snapshot = a.clone();
Foreign::rename_shared(&mut a, &["LAYER"], "B", "C");
assert!(std::sync::Arc::ptr_eq(&a, &snapshot));
Foreign::rename_shared(&mut a, &["LAYER"], "a", "c");
assert!(a.records.contains_key(&key("LAYER", "C")) && snapshot.records.contains_key(&key("LAYER", "A")));
}
}
+42 -25
View File
@@ -14,6 +14,7 @@ mod format;
mod gdt;
mod header;
pub mod library;
mod names;
mod plotstyle;
mod plotter;
mod raster;
@@ -30,16 +31,17 @@ 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::*;
pub use header::{HVal, Header};
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};
@@ -101,19 +103,26 @@ pub struct Drawing {
pub header: Header,
/// File data CADCraft does not model, written back on save.
pub foreign: std::sync::Arc<foreign::Foreign>,
pub layers: Vec<Layer>,
pub linetypes: Vec<Linetype>,
pub text_styles: Vec<TextStyle>,
pub dim_styles: Vec<DimStyle>,
/// Layers in table order; [`Drawing::layer`] looks them up by name.
pub layers: NamedList<Layer>,
/// Linetypes in table order; [`Drawing::linetype`] looks them up by name.
pub linetypes: NamedList<Linetype>,
/// Text styles in table order; [`Drawing::text_style`] looks them up by name.
pub text_styles: NamedList<TextStyle>,
/// Dimension styles in table order; [`Drawing::dim_style`] looks them up by name.
pub dim_styles: NamedList<DimStyle>,
pub mleader_styles: Vec<MLeaderStyle>,
pub table_styles: Vec<TableStyle>,
/// Table styles in table order; looked up by name with [`NamedList::by_name`].
pub table_styles: NamedList<TableStyle>,
/// Multiline styles (MLSTYLE); STANDARD is always there.
pub mline_styles: Vec<MLineStyle>,
pub blocks: BTreeMap<String, std::sync::Arc<Block>>,
/// Block definitions by name; [`Drawing::block`] looks them up.
pub blocks: NamedMap<std::sync::Arc<Block>>,
pub model: EntityStore,
/// Model layout's page setup, or the default extents-to-fit setup for a new drawing.
pub model_page: Option<PageSetup>,
pub layouts: Vec<Layout>,
/// 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`),
/// written active again. `None`, or a layout that no longer exists: the first by tab order.
pub active_layout: Option<String>,
@@ -187,7 +196,7 @@ impl Drawing {
d.scales = metric_scales();
d.dim_styles.push(DimStyle::iso25());
d.mleader_styles = vec![MLeaderStyle::metric()];
d.table_styles = vec![TableStyle::metric()];
d.table_styles = vec![TableStyle::metric()].into();
d.header.set_str("DIMSTYLE", "ISO-25");
d
}
@@ -195,21 +204,22 @@ impl Drawing {
Drawing {
header: Header::default(),
foreign: std::sync::Arc::default(),
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }],
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }].into(),
linetypes: vec![
Linetype { name: "ByBlock".into(), description: String::new(), pattern: Vec::new() },
Linetype { name: "ByLayer".into(), description: String::new(), pattern: Vec::new() },
Linetype::continuous(),
],
text_styles: vec![TextStyle::default()],
dim_styles: vec![DimStyle::default()],
]
.into(),
text_styles: vec![TextStyle::default()].into(),
dim_styles: vec![DimStyle::default()].into(),
mleader_styles: vec![MLeaderStyle::default()],
table_styles: vec![TableStyle::default()],
table_styles: vec![TableStyle::default()].into(),
mline_styles: vec![MLineStyle::default()],
blocks: BTreeMap::new(),
blocks: NamedMap::default(),
model: EntityStore::new(),
model_page: None,
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)].into(),
active_layout: None,
views: Vec::new(),
vports: Vec::new(),
@@ -313,20 +323,25 @@ impl Drawing {
}
}
/// The first layer named `name`, without case.
pub fn layer(&self, name: &str) -> Option<&Layer> {
self.layers.iter().find(|l| l.name.eq_ignore_ascii_case(name))
self.layers.by_name(name)
}
/// The first layer named `name`, without case, to change.
pub fn layer_mut(&mut self, name: &str) -> Option<&mut Layer> {
self.layers.iter_mut().find(|l| l.name.eq_ignore_ascii_case(name))
self.layers.by_name_mut(name)
}
/// The first linetype named `name`, without case.
pub fn linetype(&self, name: &str) -> Option<&Linetype> {
self.linetypes.iter().find(|l| l.name.eq_ignore_ascii_case(name))
self.linetypes.by_name(name)
}
/// The first text style named `name`, without case.
pub fn text_style(&self, name: &str) -> Option<&TextStyle> {
self.text_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
self.text_styles.by_name(name)
}
/// The first dimension style named `name`, without case.
pub fn dim_style(&self, name: &str) -> Option<&DimStyle> {
self.dim_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
self.dim_styles.by_name(name)
}
/// The DIM* variables in the header that differ from the current dimension style, as
@@ -394,11 +409,13 @@ impl Drawing {
}
}
}
/// The block named exactly `name`, else the first by name order named `name` without case.
pub fn block(&self, name: &str) -> Option<&std::sync::Arc<Block>> {
self.blocks.get(name).or_else(|| self.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v))
self.blocks.by_name(name)
}
/// The first layout named `name`, without case.
pub fn layout(&self, name: &str) -> Option<&Layout> {
self.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(name))
self.layouts.by_name(name)
}
/// Add a layer if missing; returns whether it was created.
+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 {
+575
View File
@@ -0,0 +1,575 @@
//! The drawing's tables of named entries (layers, blocks, linetypes, text styles, dimension styles,
//! table styles and layouts), whose names are looked up without case through an index instead of a
//! scan once a table is large and looked up often.
//!
//! [`Drawing::layer`](crate::Drawing::layer), [`Drawing::block`](crate::Drawing::block) and the
//! other lookups by name run for every entity while a drawing is read, measured and drawn, and
//! every layout is looked up on each change. Scanning the table on each made a file of N layers,
//! or of N blocks, linetypes or styles and N objects naming ones it does not have, cost N² name
//! comparisons: tens of seconds to open or draw at a few tens of thousands (#1924, F-04).
//!
//! Each table keeps an index from a name with its ASCII letters lower-cased to the table's first
//! entry of that name, so a lookup returns what a scan in table order returns. The index is ordered
//! by those bytes, not hashed: a lookup costs a logarithmic number of name comparisons whatever
//! the names are, also where a file could predict a hash's keys (the web build's `RandomState`).
//! Every change to a table goes through `DerefMut`, which drops the index, so it can never be
//! stale. The index is built only once a table has been scanned [`SCANS_BEFORE_INDEX`] times since
//! it last changed: a table changed between every few hundred lookups costs at most about 2.5 times
//! what scanning it always did, and one looked up many times in between is indexed once.
use std::collections::{BTreeMap, btree_map};
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, OnceLock};
/// Tables with fewer entries than this are always scanned: a search of the index costs about what a
/// scan of 100 names does (measured), so a smaller table gains nothing from one.
const MIN_INDEXED: usize = 128;
/// Lookups that scan a table after it changed before its index is built. A build costs about 100
/// to 350 scans (measured on tables of 100 to 40 000 names), so a table changed after every few
/// hundred lookups costs at most about 2.5 times what scanning it always did.
const SCANS_BEFORE_INDEX: u32 = 256;
/// From a name with its ASCII letters lower-cased to the first entry, in table order, of that name.
struct Index<V>(BTreeMap<Box<[u8]>, V>);
impl<V> Index<V> {
fn build<'a>(entries: impl Iterator<Item = (&'a str, V)>) -> Self {
let mut map = BTreeMap::new();
for (name, v) in entries {
map.entry(name.to_ascii_lowercase().into_bytes().into_boxed_slice()).or_insert(v);
}
Index(map)
}
/// The first entry named `name`, without case.
fn get(&self, name: &str) -> Option<&V> {
with_folded(name, |folded| self.0.get(folded))
}
}
/// `f` of the bytes of `name` with its ASCII letters lower-cased, which are equal for the names
/// `eq_ignore_ascii_case` finds equal. A short name is folded on the stack.
fn with_folded<R>(name: &str, f: impl FnOnce(&[u8]) -> R) -> R {
let mut buf = [0u8; 64];
match buf.get_mut(..name.len()) {
Some(short) => {
short.copy_from_slice(name.as_bytes());
short.make_ascii_lowercase();
f(short)
}
None => f(name.to_ascii_lowercase().as_bytes()),
}
}
/// A table's index: built on demand, shared by copies of the unchanged table (an undo snapshot),
/// dropped when the table changes.
struct Lazy<V> {
index: OnceLock<Arc<Index<V>>>,
/// Lookups that scanned the table since it last changed.
scans: AtomicU32,
}
impl<V> Lazy<V> {
/// The index of a table of `len` entries, built with `build` once the table has been scanned
/// often enough since it changed; `None` while it is to be scanned.
fn get(&self, len: usize, build: impl FnOnce() -> Index<V>) -> Option<&Index<V>> {
if let Some(ix) = self.index.get() {
return Some(ix);
}
if len < MIN_INDEXED || self.scans.fetch_add(1, Ordering::Relaxed) < SCANS_BEFORE_INDEX {
return None;
}
Some(self.index.get_or_init(|| Arc::new(build())))
}
/// Forget the index: the table may change.
fn clear(&mut self) {
self.index = OnceLock::new();
*self.scans.get_mut() = 0;
}
}
impl<V> Default for Lazy<V> {
fn default() -> Self {
Lazy { index: OnceLock::new(), scans: AtomicU32::new(0) }
}
}
impl<V> Clone for Lazy<V> {
fn clone(&self) -> Self {
Lazy { index: self.index.clone(), scans: AtomicU32::new(0) }
}
}
/// An entry of a [`NamedList`]: what it is looked up by.
pub trait Named {
fn name(&self) -> &str;
}
/// Entries named by their `name` field.
macro_rules! named_by_field {
($($t:ty),*) => {$(
impl Named for $t {
fn name(&self) -> &str {
&self.name
}
}
)*};
}
named_by_field!(crate::Layer, crate::Linetype, crate::TextStyle, crate::DimStyle, crate::TableStyle, crate::Layout);
/// A list of named entries in their own order (the drawing's layers, linetypes, text styles,
/// dimension styles, table styles and layouts). It reads and changes as a `Vec`;
/// [`NamedList::by_name`] finds the first entry of a name without case.
pub struct NamedList<T> {
list: Vec<T>,
index: Lazy<usize>,
}
impl<T: Named> NamedList<T> {
/// The position of the first entry named `name`, without case.
pub fn position_by_name(&self, name: &str) -> Option<usize> {
match self.index.get(self.list.len(), || Index::build(self.list.iter().enumerate().map(|(i, t)| (t.name(), i)))) {
Some(ix) => ix.get(name).copied(),
None => self.list.iter().position(|t| t.name().eq_ignore_ascii_case(name)),
}
}
/// The first entry named `name`, without case.
pub fn by_name(&self, name: &str) -> Option<&T> {
self.position_by_name(name).and_then(|i| self.list.get(i))
}
/// The first entry named `name`, without case, to change (which drops the index).
pub fn by_name_mut(&mut self, name: &str) -> Option<&mut T> {
let i = self.position_by_name(name)?;
self.get_mut(i)
}
}
impl<T> Deref for NamedList<T> {
type Target = Vec<T>;
fn deref(&self) -> &Vec<T> {
&self.list
}
}
impl<T> DerefMut for NamedList<T> {
fn deref_mut(&mut self) -> &mut Vec<T> {
self.index.clear();
&mut self.list
}
}
impl<T> Default for NamedList<T> {
fn default() -> Self {
Vec::new().into()
}
}
impl<T: Clone> Clone for NamedList<T> {
fn clone(&self) -> Self {
NamedList { list: self.list.clone(), index: self.index.clone() }
}
}
impl<T: std::fmt::Debug> std::fmt::Debug for NamedList<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.list.fmt(f)
}
}
impl<T: PartialEq> PartialEq for NamedList<T> {
fn eq(&self, other: &Self) -> bool {
self.list == other.list
}
}
impl<T> From<Vec<T>> for NamedList<T> {
fn from(list: Vec<T>) -> Self {
NamedList { list, index: Lazy::default() }
}
}
impl<T> From<NamedList<T>> for Vec<T> {
fn from(l: NamedList<T>) -> Self {
l.list
}
}
impl<T: serde::Serialize> serde::Serialize for NamedList<T> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
self.list.serialize(s)
}
}
impl<T> FromIterator<T> for NamedList<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
Vec::from_iter(iter).into()
}
}
impl<T> IntoIterator for NamedList<T> {
type Item = T;
type IntoIter = std::vec::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.list.into_iter()
}
}
impl<'a, T> IntoIterator for &'a NamedList<T> {
type Item = &'a T;
type IntoIter = std::slice::Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.list.iter()
}
}
impl<'a, T> IntoIterator for &'a mut NamedList<T> {
type Item = &'a mut T;
type IntoIter = std::slice::IterMut<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.deref_mut().iter_mut()
}
}
/// Entries by name, in name order (the drawing's block definitions). It reads and changes as a
/// `BTreeMap`; [`NamedMap::by_name`] finds an entry by its exact name, else the first in name
/// order whose name matches without case.
pub struct NamedMap<V> {
map: BTreeMap<String, V>,
index: Lazy<Box<str>>,
}
impl<V> NamedMap<V> {
/// The entry named exactly `name`, else the first in name order named `name` without case.
pub fn by_name(&self, name: &str) -> Option<&V> {
if let Some(v) = self.map.get(name) {
return Some(v);
}
match self.index.get(self.map.len(), || Index::build(self.map.keys().map(|k| (k.as_str(), Box::from(k.as_str()))))) {
Some(ix) => ix.get(name).and_then(|k| self.map.get(&**k)),
None => self.map.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v),
}
}
}
impl<V> Deref for NamedMap<V> {
type Target = BTreeMap<String, V>;
fn deref(&self) -> &BTreeMap<String, V> {
&self.map
}
}
impl<V> DerefMut for NamedMap<V> {
fn deref_mut(&mut self) -> &mut BTreeMap<String, V> {
self.index.clear();
&mut self.map
}
}
impl<V> Default for NamedMap<V> {
fn default() -> Self {
BTreeMap::new().into()
}
}
impl<V: Clone> Clone for NamedMap<V> {
fn clone(&self) -> Self {
NamedMap { map: self.map.clone(), index: self.index.clone() }
}
}
impl<V: std::fmt::Debug> std::fmt::Debug for NamedMap<V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.map.fmt(f)
}
}
impl<V: PartialEq> PartialEq for NamedMap<V> {
fn eq(&self, other: &Self) -> bool {
self.map == other.map
}
}
impl<V> From<BTreeMap<String, V>> for NamedMap<V> {
fn from(map: BTreeMap<String, V>) -> Self {
NamedMap { map, index: Lazy::default() }
}
}
impl<V> FromIterator<(String, V)> for NamedMap<V> {
fn from_iter<I: IntoIterator<Item = (String, V)>>(iter: I) -> Self {
BTreeMap::from_iter(iter).into()
}
}
impl<V> IntoIterator for NamedMap<V> {
type Item = (String, V);
type IntoIter = btree_map::IntoIter<String, V>;
fn into_iter(self) -> Self::IntoIter {
self.map.into_iter()
}
}
impl<'a, V> IntoIterator for &'a NamedMap<V> {
type Item = (&'a String, &'a V);
type IntoIter = btree_map::Iter<'a, String, V>;
fn into_iter(self) -> Self::IntoIter {
self.map.iter()
}
}
impl<'a, V> IntoIterator for &'a mut NamedMap<V> {
type Item = (&'a String, &'a mut V);
type IntoIter = btree_map::IterMut<'a, String, V>;
fn into_iter(self) -> Self::IntoIter {
self.deref_mut().iter_mut()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::{MIN_INDEXED, Named, NamedList};
use crate::{Block, DimStyle, Drawing, Layer, Layout, Linetype, TextStyle};
/// Names to look up: each given name as it is, upper-cased, lower-cased and with a character
/// added (a miss).
fn probes<'a>(names: impl Iterator<Item = &'a str>) -> Vec<String> {
names.flat_map(|n| [n.to_string(), n.to_ascii_uppercase(), n.to_ascii_lowercase(), format!("{n}?")]).collect()
}
fn layers_indexed(d: &Drawing) -> bool {
d.layers.index.index.get().is_some()
}
fn indexed<T>(list: &NamedList<T>) -> bool {
list.index.index.get().is_some()
}
/// Every lookup through `find` finds what a scan of `list` in table order finds (the first of a
/// name without case), by pointer, for the list's names and `extra`.
fn check_list<'a, T: Named>(list: &'a NamedList<T>, find: impl Fn(&str) -> Option<&'a T>, extra: &[&str]) {
let names: Vec<String> = list.iter().map(|t| t.name().to_string()).collect();
for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) {
let want = list.iter().find(|t| t.name().eq_ignore_ascii_case(&p)).map(std::ptr::from_ref);
assert_eq!(find(&p).map(std::ptr::from_ref), want, "{p}");
}
}
/// The linetype, text style, dimension style and layout lookups each find what a scan in table
/// order finds (the first of a name without case): while they scan, once the table is indexed,
/// and after `by_name_mut` (RENAME, STYLE, DIMSTYLE, a .lin file reloaded, a layout's UCS)
/// changed the first of a name and dropped the index.
#[test]
fn linetype_style_and_layout_lookups_find_the_first_of_a_name() {
let names: Vec<String> = (0..150).map(|i| format!("N{i}")).chain(["n7", "Dash", "DASH"].map(String::from)).collect();
let mut d = Drawing::new_imperial();
d.linetypes = names.iter().map(|n| Linetype::simple(n, "", &[0.5, -0.25])).collect();
d.text_styles = names.iter().map(|n| TextStyle { name: n.clone(), ..TextStyle::default() }).collect();
d.dim_styles = names.iter().map(|n| DimStyle { name: n.clone(), ..DimStyle::default() }).collect();
d.layouts = names.iter().zip(1..).map(|(n, tab)| Layout::new(n, tab)).collect();
let check = |d: &Drawing, extra: &[&str]| {
check_list(&d.linetypes, |n| d.linetype(n), extra);
check_list(&d.text_styles, |n| d.text_style(n), extra);
check_list(&d.dim_styles, |n| d.dim_style(n), extra);
check_list(&d.layouts, |n| d.layout(n), extra);
};
let all_indexed = |d: &Drawing| indexed(&d.linetypes) && indexed(&d.text_styles) && indexed(&d.dim_styles) && indexed(&d.layouts);
// The first round scans until the index is built; the second reads only the index.
check(&d, &["dash", "missing"]);
assert!(all_indexed(&d));
check(&d, &["dash", "missing"]);
// The first of a name changes, and the later one of that name is found after it.
d.linetypes.by_name_mut("n7").unwrap().name = "Seven".into();
d.text_styles.by_name_mut("n7").unwrap().name = "Seven".into();
d.dim_styles.by_name_mut("n7").unwrap().name = "Seven".into();
d.layouts.by_name_mut("n7").unwrap().name = "Seven".into();
assert!(!indexed(&d.linetypes) && !indexed(&d.text_styles) && !indexed(&d.dim_styles) && !indexed(&d.layouts));
assert_eq!(d.linetype("N7").map(|l| l.name.as_str()), Some("n7"));
assert_eq!(d.text_style("N7").map(|s| s.name.as_str()), Some("n7"));
assert_eq!(d.dim_style("N7").map(|s| s.name.as_str()), Some("n7"));
assert_eq!(d.layout("N7").map(|l| (l.name.as_str(), l.tab_order)), Some(("n7", 151)));
assert_eq!(d.linetypes.get(7).map(|l| l.name.as_str()), Some("Seven"));
check(&d, &["SEVEN", "n7"]);
assert!(all_indexed(&d));
// A miss changes nothing and keeps the index.
assert!(d.dim_styles.by_name_mut("none").is_none());
assert!(indexed(&d.dim_styles));
check(&d, &["dash"]);
}
fn blocks_indexed(d: &Drawing) -> bool {
d.blocks.index.index.get().is_some()
}
/// `layer_mut` finds the first layer of a name and drops the index, as the table may change
/// through it. Then every layer lookup finds what a scan in table order finds (the first of a
/// name without case), and a large table looked up this often is left indexed.
fn check_layers(d: &mut Drawing, extra: &[&str]) {
let p = extra.first().copied().unwrap_or("L1");
let want = d.layers.iter().position(|l| l.name.eq_ignore_ascii_case(p)).and_then(|i| d.layers.get(i)).map(std::ptr::from_ref);
assert_eq!(d.layer_mut(p).map(|l| std::ptr::from_ref(&*l)), want, "{p}");
assert!(want.is_none() || !layers_indexed(d));
let names: Vec<String> = d.layers.iter().map(|l| l.name.clone()).collect();
for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) {
let want = d.layers.iter().position(|l| l.name.eq_ignore_ascii_case(&p));
assert_eq!(d.layers.position_by_name(&p), want, "{p}");
let at = want.and_then(|i| d.layers.get(i)).map(std::ptr::from_ref);
assert_eq!(d.layer(&p).map(std::ptr::from_ref), at, "{p}");
}
assert_eq!(layers_indexed(d), d.layers.len() >= MIN_INDEXED);
}
/// Every block lookup finds what `Drawing::block` always found: the block of that exact name,
/// else the first in name order of that name without case. Only names that miss an exact name
/// count towards building the index, so the names are looked up twice.
fn check_blocks(d: &Drawing, extra: &[&str]) {
let names: Vec<String> = d.blocks.keys().cloned().collect();
for p in probes(names.iter().chain(&names).map(String::as_str).chain(extra.iter().copied())) {
let want = d.blocks.get(&p).or_else(|| d.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(&p)).map(|(_, v)| v));
assert_eq!(d.block(&p).map(std::ptr::from_ref), want.map(std::ptr::from_ref), "{p}");
}
assert_eq!(blocks_indexed(d), d.blocks.len() >= MIN_INDEXED);
}
/// The index answers by itself, with no scan to fall back on: every name finds the first entry
/// of its name without case, also names that differ only after a long shared prefix, names
/// that fill the stack buffer or are longer, and names with non-ASCII letters (which keep their
/// case). Names are compared, not hashed, so no two names can share a slot.
#[test]
fn the_index_alone_finds_the_first_entry_of_every_name() {
let long = "x".repeat(100);
let names: Vec<String> = vec![
"Door".into(),
"DOOR".into(),
"door2".into(),
format!("{long}A"),
format!("{long}a"),
format!("{long}B"),
format!("{}b", "P".repeat(63)),
format!("{}B", "p".repeat(63)),
"Ärea".into(),
"ärea".into(),
"ÄREA".into(),
String::new(),
];
let ix = super::Index::build(names.iter().enumerate().map(|(i, n)| (n.as_str(), i)));
for p in names.iter().flat_map(|n| [n.clone(), n.to_ascii_uppercase(), n.to_ascii_lowercase(), format!("{n}?")]) {
let want = names.iter().position(|n| n.eq_ignore_ascii_case(&p));
assert_eq!(ix.get(&p).copied(), want, "{p:?}");
}
assert_eq!(ix.get(&format!("{long}a")), Some(&3));
assert_eq!(ix.get("ärea"), Some(&9));
}
#[test]
fn layer_lookups_find_the_first_of_a_name_through_every_change() {
let mut d = Drawing::new_imperial();
d.layers = (0..200).map(|i| Layer::new(&format!("L{i}"))).chain([Layer::new("l5"), Layer::new("Doors")]).collect();
check_layers(&mut d, &["l5", "missing"]);
// Renamed through layer_mut (RENAME).
d.layer_mut("l7").unwrap().name = "Seven".into();
assert!(!layers_indexed(&d));
assert!(d.layer("L7").is_none());
check_layers(&mut d, &["SEVEN", "L7"]);
// Added (LAYER New, or a file's later record of a name it already has).
d.layers.push(Layer::new("SEVEN"));
assert!(!layers_indexed(&d));
check_layers(&mut d, &["seven"]);
// Removed (PURGE, LAYDEL): the later `l5` becomes the first of that name.
d.layers.retain(|l| l.name != "L5");
assert!(!layers_indexed(&d));
assert_eq!(d.layer("L5").map(|l| l.name.as_str()), Some("l5"));
check_layers(&mut d, &["L5"]);
// Inserted before an earlier layer of the same name.
d.layers.insert(0, Layer::new("l9"));
assert!(!layers_indexed(&d));
assert_eq!(d.layer("L9").map(|l| l.name.as_str()), Some("l9"));
check_layers(&mut d, &["L9"]);
// Changed by position, and by a loop over all of them.
d.layers[3].name = "Third".into();
assert!(!layers_indexed(&d));
check_layers(&mut d, &["third"]);
for l in &mut d.layers {
l.name.make_ascii_uppercase();
}
assert!(!layers_indexed(&d));
check_layers(&mut d, &["doors"]);
// Undo: a snapshot keeps the table it was taken with, and its index.
let names = |d: &Drawing| d.layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();
assert!(layers_indexed(&d));
let (snap, before) = (d.clone(), names(&d));
d.layers.clear();
d.layers.push(Layer::new("Only"));
check_layers(&mut d, &["only", "L1"]);
d = snap;
assert!(layers_indexed(&d));
assert_eq!(names(&d), before);
check_layers(&mut d, &["THIRD"]);
// The whole table replaced (LAYERP, LAYUNISO).
d.layers = vec![Layer::new("0"), Layer::new("A"), Layer::new("a")].into();
check_layers(&mut d, &["a"]);
}
#[test]
fn block_lookups_find_an_exact_name_else_the_first_without_case_through_every_change() {
let block = |name: &str| Arc::new(Block::new(name));
let mut d = Drawing::new_imperial();
for name in (0..150).map(|i| format!("B{i}")).chain(["Door", "DOOR", "door"].map(String::from)) {
d.blocks.insert(name.clone(), block(&name));
}
check_blocks(&d, &["dOOR", "missing"]);
// An exact name wins; otherwise the first in name order ("DOOR" < "Door" < "door").
assert_eq!(d.block("door").map(|b| b.name.as_str()), Some("door"));
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("DOOR"));
// Removed (PURGE, a definition replaced under another name).
d.blocks.remove("DOOR");
assert!(!blocks_indexed(&d));
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("Door"));
check_blocks(&d, &["dOOR"]);
// Added before the first of that name.
d.blocks.insert("DoOr".into(), block("DoOr"));
assert!(!blocks_indexed(&d));
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("DoOr"));
check_blocks(&d, &["dOOR"]);
// Renamed (RENAME takes the definition out and puts it back under the new name).
let b1 = d.blocks.remove("B1").unwrap();
d.blocks.insert("Renamed".into(), b1);
assert!(d.block("b1").is_none() && d.block("RENAMED").is_some());
check_blocks(&d, &["b1", "RENAMED"]);
// Redefined in place, and changed through get_mut: the names stay.
d.blocks.insert("Door".into(), block("Door"));
assert!(!blocks_indexed(&d));
check_blocks(&d, &["DOOR"]);
Arc::make_mut(d.blocks.get_mut("B2").unwrap()).description = "changed".into();
assert!(!blocks_indexed(&d));
check_blocks(&d, &["b2"]);
// Many removed at once.
d.blocks.retain(|k, _| !k.starts_with("B9"));
assert!(!blocks_indexed(&d));
check_blocks(&d, &["b9", "b90"]);
// A loop over all of them.
for (_, b) in &mut d.blocks {
Arc::make_mut(b).description = "looped".into();
}
assert!(!blocks_indexed(&d));
check_blocks(&d, &["b3"]);
// Undo: a snapshot keeps the table it was taken with, and its index.
let snap = d.clone();
d.blocks.clear();
d.blocks.insert("Only".into(), block("Only"));
check_blocks(&d, &["only", "door"]);
d = snap;
assert!(blocks_indexed(&d));
check_blocks(&d, &["DOOR", "only"]);
}
}
+12 -3
View File
@@ -79,15 +79,21 @@ impl Default for DevicePaper {
impl DevicePaper {
/// The paper with hostile values fixed: finite sizes within 1..=[`MAX_PAPER_MM`] mm
/// (portrait), margins 0..=1000 mm that leave a printable area (else none), a name of at
/// most [`MAX_PLOTTER_NAME`] characters.
/// most [`MAX_PLOTTER_NAME`] characters. A sheet wider than tall is stored turned 90° and
/// its margins turn with it, so the printable area the caller measured against the sheet it
/// named is the one the stored portrait paper holds.
pub fn sanitized(mut self) -> DevicePaper {
let side = |v: f64| if v.is_finite() { v.clamp(1.0, MAX_PAPER_MM) } else { 1.0 };
let (w, h) = (side(self.width), side(self.height));
self.width = w.min(h);
self.height = w.max(h);
for m in &mut self.margins {
*m = if m.is_finite() { m.clamp(0.0, 1000.0) } else { 0.0 };
}
if w > h {
let [l, b, r, t] = self.margins;
self.margins = [b, r, t, l];
}
self.width = w.min(h);
self.height = w.max(h);
let [l, b, r, t] = self.margins;
if l + r >= self.width || b + t >= self.height {
self.margins = [0.0; 4];
@@ -243,6 +249,9 @@ mod tests {
assert_eq!(back.papers[1].margins, [0.0, 1000.0, 0.0, 5.0], "hostile margins clamped");
let wide = DevicePaper { margins: [150.0, 0.0, 100.0, 0.0], ..DevicePaper::default() }.sanitized();
assert_eq!(wide.margins, [0.0; 4], "margins wider than the paper are dropped");
let turned = DevicePaper { name: "Banner".into(), width: 400.0, height: 200.0, margins: [150.0, 0.0, 150.0, 0.0] }.sanitized();
assert_eq!((turned.width, turned.height), (200.0, 400.0), "portrait");
assert_eq!(turned.margins, [0.0, 150.0, 0.0, 150.0], "margins turn with the sheet");
assert!(back.paper("a3 BORDERLESS").is_some());
assert!(PlotterConfig::from_file_text("{}").is_err());
assert!(PlotterConfig::from_file_text(r#"{"cadcraftPlotter": 1}"#).is_err(), "needs a name");
+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 {
+8 -2
View File
@@ -728,6 +728,11 @@ pub struct Block {
/// The parameters of an associative array when this is an array block.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub array: Option<crate::ArrayParams>,
/// An xref's file as its loaded objects were read from it: size and modification time (as the
/// system gives it, so a time before 1970 is kept too). Kept per drawing, so an edit in place (REFEDIT) can tell whether
/// the file changed since this drawing loaded it (session state; not saved).
#[serde(skip)]
pub xref_stamp: Option<(u64, std::time::SystemTime)>,
}
/// The load state of an external reference.
@@ -774,6 +779,7 @@ impl Block {
explodable: true,
units: 0,
array: None,
xref_stamp: None,
}
}
}
@@ -1018,8 +1024,8 @@ impl LayerState {
pub const ALL: u32 = 2047;
/// A state of every property of `layers`, with `current` the layer restoring makes current.
pub fn new(name: impl Into<String>, layers: Vec<Layer>, current: impl Into<String>) -> Self {
LayerState { name: name.into(), layers, current: current.into(), ..LayerState::default() }
pub fn new(name: impl Into<String>, layers: impl Into<Vec<Layer>>, current: impl Into<String>) -> Self {
LayerState { name: name.into(), layers: layers.into(), current: current.into(), ..LayerState::default() }
}
}
+258 -1
View File
@@ -29,7 +29,7 @@ fn new_metric_drawing_has_metric_multileader_and_table_styles() {
let i = Drawing::new_imperial();
assert_eq!(i.mleader_styles, vec![MLeaderStyle::default()]);
assert_eq!(i.table_styles, vec![TableStyle::default()]);
assert_eq!(*i.table_styles, vec![TableStyle::default()]);
assert_eq!((i.mleader_styles[0].text_height, i.table_styles[0].text_height), (0.18, 0.18));
}
@@ -271,6 +271,46 @@ fn transform_arc_mirror_keeps_shape() {
}
}
#[test]
fn mirroring_a_rotated_dimension_reflects_its_direction() {
let dim = |kind: DimKind, marks: DimMarks| {
EntityKind::Dimension(Dimension {
kind,
defpt: Vec3::ZERO,
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::new(7.071_067_811_865_475, 7.071_067_811_865_475, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 10.0,
text_rotation: 0.0,
user_text_pos: false,
block: None,
insertion_point: Vec3::ZERO,
overrides: Default::default(),
assoc: vec![],
marks,
})
};
// A dimension line at 45° mirrored across the X axis runs at -45° (315°) and still measures 10.
let mut k = dim(DimKind::Linear { rotation: std::f64::consts::FRAC_PI_4 }, DimMarks::default());
k.transform(&Mat3::mirror(Vec2::ZERO, Vec2::X));
let EntityKind::Dimension(d) = k else { panic!("a dimension") };
let DimKind::Linear { rotation } = d.kind else { panic!("a linear dimension") };
assert!((rotation - 7.0 * std::f64::consts::FRAC_PI_4).abs() < 1e-9, "{rotation}");
let p2 = Vec2::new(7.071_067_811_865_475, -7.071_067_811_865_475);
assert!((p2.dot(Vec2::from_angle(rotation)).abs() - 10.0).abs() < 1e-9, "the mirrored measurement");
// Oblique extension lines reflect about the mirror line too (a 45° line here) instead of
// being double-reflected (120° rather than 30°).
let mut k = dim(DimKind::Aligned, DimMarks { oblique: Some(std::f64::consts::FRAC_PI_3), ..DimMarks::default() });
k.transform(&Mat3::mirror(Vec2::ZERO, Vec2::new(1.0, 1.0)));
let EntityKind::Dimension(d) = k else { panic!("a dimension") };
assert!((d.marks.oblique.unwrap_or(0.0) - (std::f64::consts::FRAC_PI_2 - std::f64::consts::FRAC_PI_3)).abs() < 1e-9, "{:?}", d.marks.oblique);
}
#[test]
fn insert_bounds_with_cyclic_block_terminate() {
let mut d = Drawing::new_imperial();
@@ -890,3 +930,220 @@ fn constant_values_count_in_extents_as_attmode_shows_them() {
assert!(top(1, true) < 40.0);
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
// attribute without a layer of its own (in a third case) lies on the first one's.
let top = |defs: [(&str, &str); 2]| {
let mut d = Drawing::new_imperial();
let mut frozen = Layer::new("AFRZ");
frozen.frozen = true;
d.layers.push(frozen);
let mut blk = Block::new("B");
blk.entities.push(on_layer("0", line((0.0, 0.0), (1.0, 1.0)), 1));
for (h, (layer, tag)) in (2..).zip(defs) {
blk.entities.push(on_layer(layer, EntityKind::AttDef(plain_attrib(tag)), h));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
let mut a = plain_attrib("Tag");
a.text.insert = Vec3::new(0.0, 500.0, 0.0);
ins.attribs.push(a);
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
extents_pair(&d).1.y
};
assert!(top([("AFRZ", "TAG"), ("0", "tag")]) < 100.0, "on the first definition's frozen layer");
assert!(top([("0", "tag"), ("AFRZ", "TAG")]) > 400.0, "on the first definition's layer 0");
}
#[test]
fn constant_definitions_of_one_tag_all_count_unless_the_reference_carries_the_tag() {
// Two constant definitions of one tag, in different case: a reference draws both values,
// unless it carries an attribute of that tag (in a third case), which stands for both.
let max = |attribs: Vec<Attrib>| {
let mut d = Drawing::new_imperial();
let mut blk = Block::new("B");
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
for (h, tag, at) in [(2, "C", Vec3::new(0.0, 5000.0, 0.0)), (3, "c", Vec3::new(7000.0, 0.0, 0.0))] {
let mut a = plain_attrib(tag);
a.text.insert = at;
a.constant = true;
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a)));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
ins.attribs = attribs;
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
extents_pair(&d).1
};
for shown in [max(vec![]), max(vec![plain_attrib("D")])] {
assert!(shown.x > 6000.0 && shown.y > 4000.0, "both values count: {shown:?}");
}
let carried = max(vec![plain_attrib("D"), plain_attrib("Cc"), plain_attrib("C")]);
assert!(carried.x < 100.0 && carried.y < 100.0, "neither value counts: {carried:?}");
}
#[test]
fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() {
// #1923: one reference with N attributes (none with a layer of its own) of a block with N
// constant definitions, the tags N long ones alike up to their last characters, no attribute's
// a definition's. Comparing each attribute with each definition, for its layer and for which
// constant values the reference carries, cost N x N comparisons of whole tags (many seconds
// here); one lookup per attribute or definition costs milliseconds.
const N: usize = 4000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let mut d = Drawing::new_imperial();
let mut blk = Block::new("B");
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
for (h, i) in (2..).zip(0..N) {
let mut a = plain_attrib(&tag('D', i));
a.constant = true;
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a)));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
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());
}
/// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N
/// blocks and N references to blocks it does not have, opened in N² name comparisons (#1924).
#[test]
fn layer_and_block_lookups_by_name_cost_about_the_same_for_any_table_size() {
const N: usize = 60_000;
let mut d = Drawing::new_imperial();
d.layers = (0..N).map(|i| Layer::new(&format!("L{i}"))).collect();
for i in 0..N {
let name = format!("B{i}");
d.blocks.insert(name.clone(), std::sync::Arc::new(Block::new(&name)));
}
let started = std::time::Instant::now();
for i in 0..N {
assert!(d.layer(&format!("l{i}")).is_some() && d.layer(&format!("M{i}")).is_none());
assert!(d.block(&format!("b{i}")).is_some() && d.block(&format!("Z{i}")).is_none());
}
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
}
/// Table entries for the cost tests below.
const NAMED: usize = 40_000;
/// A name of 54 bytes whose first 48 every such name of `kind` shares, so comparing two costs
/// about 50 bytes and not a length check, as in a crafted file.
fn long_name(kind: &str, tail: &str) -> String {
format!("{kind}{}{tail}", "x".repeat(48 - kind.len()))
}
/// The [`NAMED`] names `long_name(kind, "000000")`, `..."000001"`, ...
fn long_names(kind: &str) -> impl Iterator<Item = String> + '_ {
(0..NAMED).map(move |i| long_name(kind, &format!("{i:06}")))
}
/// Each of a table's [`NAMED`] names is looked up in other case (found) and as a missing name of
/// the same length, well within a bound that scanning the table for each lookup misses: a file of
/// N entries and N objects naming one it lacks, or names in other case, drew in N² name
/// comparisons (#1924).
fn lookups_by_name_are_quick(kind: &str, found: impl Fn(&str) -> bool) {
let started = std::time::Instant::now();
for i in 0..NAMED {
assert!(found(&long_name(kind, &format!("{i:06}")).to_ascii_uppercase()), "{kind} {i}");
assert!(!found(&long_name(kind, &format!("z{i:05}"))), "{kind} {i}");
}
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
}
#[test]
fn linetype_lookups_by_name_cost_about_the_same_for_any_table_size() {
let mut d = Drawing::new_imperial();
d.linetypes = long_names("LT").map(|n| Linetype::simple(&n, "", &[0.5, -0.25])).collect();
lookups_by_name_are_quick("LT", |n| d.linetype(n).is_some());
}
#[test]
fn text_style_lookups_by_name_cost_about_the_same_for_any_table_size() {
let mut d = Drawing::new_imperial();
d.text_styles = long_names("S").map(|name| TextStyle { name, ..TextStyle::default() }).collect();
lookups_by_name_are_quick("S", |n| d.text_style(n).is_some());
}
#[test]
fn dim_style_lookups_by_name_cost_about_the_same_for_any_table_size() {
let mut d = Drawing::new_imperial();
d.dim_styles = long_names("D").map(|name| DimStyle { name, ..DimStyle::default() }).collect();
lookups_by_name_are_quick("D", |n| d.dim_style(n).is_some());
}
/// Each change to a drawing looks up every layout of the drawing before it by name (the check for
/// non-finite results), so a drawing of N layouts cost N² name comparisons per command.
#[test]
fn layout_lookups_by_name_cost_about_the_same_for_any_table_size() {
let mut d = Drawing::new_imperial();
d.layouts = long_names("L").zip(1..).map(|(n, tab)| Layout::new(&n, tab)).collect();
lookups_by_name_are_quick("L", |n| d.layout(n).is_some());
}
+6 -3
View File
@@ -7,7 +7,7 @@
//! that contain themselves lose the reference that closes the loop, and objects sharing a handle
//! get new ones.
use std::collections::{BTreeMap, HashMap, HashSet};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::sync::Arc;
use cadcraft_doc::{Block, DimStyle, Drawing, Entity, EntityKind, EntityStore, Handle, Layer, Linetype, MLeaderStyle, TableStyle, TextStyle};
@@ -425,6 +425,9 @@ fn references(d: &mut Drawing, out: &mut Vec<Issue>) {
let all = all_handles(d);
let ok_text = |d: &Drawing, n: &str| d.text_style(n).is_some();
let ok_dim = |d: &Drawing, n: &str| d.dim_style(n).is_some();
// Multileader style names, lower-cased, built once: a scan per multileader made a file of N of
// them naming styles among N quadratic to audit (#1924).
let mleader_styles: BTreeSet<String> = d.mleader_styles.iter().map(|s| s.name.to_ascii_lowercase()).collect();
// Missing names, counted: (what, name) → (objects, first location).
let mut counts: BTreeMap<(&'static str, String), (usize, String)> = BTreeMap::new();
missing_layers(d, out);
@@ -462,12 +465,12 @@ fn references(d: &mut Drawing, out: &mut Vec<Issue>) {
if let Some(t) = &mut m.text {
text_style(&mut t.style);
}
if !has_name(&d.mleader_styles, &m.style, |s| &s.name) {
if !mleader_styles.contains(&m.style.to_ascii_lowercase()) {
note("multileader style", &m.style);
m.style = "Standard".into();
}
}
EntityKind::Table(t) if !has_name(&d.table_styles, &t.style, |s| &s.name) => {
EntityKind::Table(t) if d.table_styles.by_name(&t.style).is_none() => {
note("table style", &t.style);
t.style = "Standard".into();
}
+25 -2
View File
@@ -166,6 +166,9 @@ pub struct Autosaver {
start: std::time::Instant,
#[cfg(not(target_arch = "wasm32"))]
last_beat: Option<f64>,
/// Who-has-it-open locks of the drawings open from files ([`crate::drawlock`]).
#[cfg(not(target_arch = "wasm32"))]
drawing_locks: crate::drawlock::Locks,
/// This app's lock files: one per folder, because SAVEFILEPATH can change while files remain
/// in the old folder. Each with the file it holds open for the system lock, or `None` where
/// locks don't work and only the file's age counts.
@@ -187,6 +190,8 @@ impl Autosaver {
#[cfg(not(target_arch = "wasm32"))]
last_beat: None,
#[cfg(not(target_arch = "wasm32"))]
drawing_locks: crate::drawlock::Locks::default(),
#[cfg(not(target_arch = "wasm32"))]
locks: Vec::new(),
}
}
@@ -456,7 +461,8 @@ mod native {
impl Autosaver {
/// Autosave what is due (writing in the background) and delete files no longer needed.
/// Returns how long until the next autosave is due, so the host can wake up for it.
/// Returns how long until the next autosave or drawing-lock heartbeat is due, so the host
/// can wake up for it.
pub fn tick(&mut self, s: &Session) -> Option<Duration> {
let now = self.start.elapsed().as_secs_f64();
self.reap();
@@ -465,7 +471,23 @@ mod native {
let jobs = self.plan(s, now, minutes, &dir);
self.perform(jobs);
self.heartbeat(&dir, now);
self.next_due(now, minutes).map(Duration::from_secs_f64)
self.drawing_locks.sync(s, &self.instance);
// The drawing locks need their heartbeat even with nothing to autosave (SAVETIME 0,
// every drawing saved): left untouched they go stale and another app takes them over.
let due = self.next_due(now, minutes).map(Duration::from_secs_f64);
due.into_iter().chain(self.drawing_locks.next_beat()).min()
}
/// Keep the drawing locks with `locks` instead of the default ones (e.g. a shorter
/// heartbeat, see [`crate::drawlock::Locks::with_heartbeat`]).
pub fn with_locks(mut self, locks: crate::drawlock::Locks) -> Self {
self.drawing_locks = locks;
self
}
/// What the drawing locks have to tell the user (someone else has a drawing open).
pub fn take_lock_notes(&mut self) -> Vec<String> {
self.drawing_locks.take_notes()
}
/// Autosave every drawing with changes not yet autosaved right away, without waiting for
@@ -641,6 +663,7 @@ mod native {
let _ = h.join();
}
self.busy.clear();
self.drawing_locks.release_all(&self.instance);
for path in self.files() {
discard(&path);
}
+7 -1
View File
@@ -1,5 +1,5 @@
//! Dimensions and leaders: DIMLINEAR, DIMALIGNED, DIMRADIUS, DIMDIAMETER, DIMANGULAR, DIMARC,
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, DIMOVERRIDE,
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, QLEADER, DIMOVERRIDE,
//! DIMREASSOCIATE / DIMDISASSOCIATE, DIMTEDIT, DIMSPACE; DIMEDIT, DIMJOGGED, DIMJOGLINE,
//! DIMBREAK and DIMINSPECT in `annotate_dimedit.rs`.
@@ -19,6 +19,7 @@ mod edit;
mod leader;
mod linear;
mod mleader;
mod qleader;
mod radial;
use angular::{AngularM, ArcLenM, run_angular, run_arclen};
@@ -27,6 +28,7 @@ use common::{DimText, add_dim, assoc_enabled, circle_of, dim, pick_at};
use edit::{DimSpaceM, OverrideM, dims_of, run_dimspace, run_dimtedit, run_disassociate, run_override, run_reassociate, run_tedit, run_update};
use linear::{ChainM, LinearM, MAX_CHAIN, OrdinateM, run_aligned, run_baseline, run_continue, run_linear, run_ordinate};
use mleader::{MLeaderM, run_leader, run_mleader};
use qleader::{QLeaderM, run_qleader};
use radial::{RadialM, run_diameter, run_radius};
pub fn specs() -> Vec<CommandSpec> {
@@ -93,6 +95,10 @@ pub fn specs() -> Vec<CommandSpec> {
.alias(&["lead"])
.params("{points: [[x,y]...], text?}")
.interactive(|_| Ok(Box::new(leader::LeaderM::default()))),
CommandSpec::new("qleader", "Quick Leader", run_qleader)
.alias(&["le"])
.params("{points: [[x,y], [x,y], [x,y]?] (2 or 3), width?: text width (default 0), text?: lines split at \\n}")
.interactive(|_| Ok(Box::new(QLeaderM::default()))),
CommandSpec::new("dimstyle.update", "Update", run_update)
.menu(&["Dimension", "Update"])
.params("{handles?}")
+45 -5
View File
@@ -42,8 +42,13 @@ pub(super) struct LeaderM {
}
/// What follows the leader.
enum Annotation {
pub(super) enum Annotation {
Text(Vec<String>),
/// QLEADER's text: its lines and its width.
Quick {
lines: Vec<String>,
width: f64,
},
/// A copy of a text or multiline text: its contents, height, width and style.
Copy(MText),
None,
@@ -242,14 +247,25 @@ struct Sizes {
text: f64,
above: bool,
text_style: String,
/// An annotative style: the annotation scale takes DIMSCALE's place, as for an annotative
/// dimension, so the sizes are unscaled and the text is annotative.
annotative: bool,
}
fn sizes(s: &Session) -> Sizes {
// The current style with the drawing's DIM* overrides (what SETVAR DIMTXT… sets).
let st = s.doc().ok().and_then(|d| d.dim_style(&style(s)).map(|st| st.with_overrides(&d.dim_overrides()))).unwrap_or_default();
let k = if st.scale > 0.0 { st.scale } else { 1.0 };
let dimscale = s.doc().map_or(1.0, |d| d.header.f64("DIMSCALE", 1.0));
let k = if st.annotative { 1.0 } else { st.effective_scale(dimscale) };
let text_style = if st.text_style.is_empty() { "Standard".to_string() } else { st.text_style.clone() };
Sizes { arrow: st.arrow_size * k, gap: st.text_gap.abs() * k, text: st.text_height * k, above: st.text_above != 0, text_style }
Sizes {
arrow: st.arrow_size * k,
gap: st.text_gap.abs() * k,
text: st.text_height * k,
above: st.text_above != 0,
text_style,
annotative: st.annotative,
}
}
/// LEADER's JSON form: a straight leader with an arrow through `pts`, and `text` (lines split at
@@ -263,13 +279,13 @@ pub(super) fn json_leader(s: &mut Session, pts: &[Vec2], text: Option<&str>) ->
}
/// Draw the leader through `pts` and its annotation, as AutoCAD 2024 places them; their handles.
fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
let (Some(&end), Some(&before)) = (pts.last(), pts.len().checked_sub(2).and_then(|i| pts.get(i))) else { return Ok(Vec::new()) };
let z = sizes(s);
// The side the leader runs to: right unless its last segment runs left.
let dir = if end.x < before.x { -1.0 } else { 1.0 };
let mut vertices = pts.to_vec();
if let Annotation::Text(_) | Annotation::Copy(_) = ann {
if let Annotation::Text(_) | Annotation::Quick { .. } | Annotation::Copy(_) = ann {
let d = end - before;
// A copied text is centred on its line, and with DIMTAD on that line is above the leader:
// the leader ends half the text height lower.
@@ -310,6 +326,23 @@ fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Ann
columns: None,
}))?)
}
Annotation::Quick { lines, width } => {
// The middle of the first line level with the end on the right, of the last line on
// the left, whatever DIMTAD.
let (attach, lift) = if dir > 0.0 { (1, z.text / 2.0) } else { (9, -z.text / 2.0) };
Some(s.add_entity(EntityKind::MText(MText {
insert: v3(end + Vec2::new(dir * z.gap, lift)),
height: z.text,
width,
attach,
rotation: 0.0,
style: z.text_style,
contents: lines.join("\\P"),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
}))?)
}
Annotation::Copy(m) => {
let lift = if z.above { z.gap } else { 0.0 };
let attach = if dir > 0.0 { 4 } else { 6 };
@@ -326,5 +359,12 @@ fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Ann
}
Annotation::None => None,
};
if let (true, Some(t)) = (z.annotative, annotation)
&& matches!(s.doc()?.entity(t).map(|e| &e.kind), Some(EntityKind::MText(_)))
{
let d = s.doc_mut()?;
let cur = d.current_anno_scale();
d.modify_entity(t, |e| cadcraft_doc::set_annotative(e, true, &cur))?;
}
Ok(std::iter::once(leader).chain(annotation).collect())
}
+121
View File
@@ -0,0 +1,121 @@
//! QLEADER at the command line, as AutoCAD 2024 runs it with its default settings (accoreconsole,
//! synthetic drawings): up to three points, a text width, then lines of text.
//!
//! The leader is LEADER's, with an arrow and a hook line DIMASZ long when its last segment is more
//! than 15° off horizontal and text follows. The multiline text sits DIMGAP past the leader's end,
//! as wide as the width given: with the middle of its first line level with the end when the
//! leader runs right, and of its last line when it runs left, whatever DIMTAD. Enter at the first
//! line of text leaves the leader without text. The Settings dialog isn't available yet.
use serde_json::{Value, json};
use super::leader::{Annotation, add_leader};
use super::{Accept, Input, Interactive, Prompt, Result, Session, Step, Vec2, bad, points_param, str_param};
use crate::cmd::size_param;
/// QLEADER's default number of leader points.
const MAX_POINTS: usize = 3;
#[derive(Clone, Copy, Default, PartialEq)]
enum Ask {
#[default]
Points,
Width,
FirstLine,
NextLine,
}
#[derive(Default)]
pub(super) struct QLeaderM {
ask: Ask,
pts: Vec<Vec2>,
width: f64,
lines: Vec<String>,
}
impl Interactive for QLeaderM {
fn name(&self) -> &'static str {
"QLEADER"
}
fn prompt(&self, _s: &Session) -> Prompt {
let last = self.pts.last().copied();
match self.ask {
Ask::Points if self.pts.is_empty() => Prompt::new("Specify first leader point,", Accept::POINT).kw(&["Settings"]).default("Settings"),
Ask::Points => Prompt::new("Specify next point", Accept::POINT).base_opt(last),
// The width isn't remembered: AutoCAD 2024 offers 0 again after a width of 20.
Ask::Width => Prompt::new("Specify text width", Accept::POINT_OR_NUMBER).distance().default("0").base_opt(last),
Ask::FirstLine => Prompt::new("Enter first line of annotation text", Accept::TEXT).default("Mtext"),
Ask::NextLine => Prompt::new("Enter next line of annotation text", Accept::TEXT),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match self.ask {
Ask::Points => match i {
Input::Point(p) => {
self.pts.push(p);
if self.pts.len() == MAX_POINTS {
self.ask = Ask::Width;
}
}
Input::Enter | Input::Keyword(_) if self.pts.is_empty() => s.echo("The QLEADER Settings dialog is not available yet."),
// Enter after one point: no leader.
Input::Enter if self.pts.len() < 2 => return Ok(Step::Done),
Input::Enter => self.ask = Ask::Width,
_ => {}
},
Ask::Width => {
// A point gives the width as its distance from the leader's end; a negative
// width is none.
let width = match i {
Input::Point(p) => self.pts.last().map(|e| e.dist(p)),
Input::Text(t) => crate::units::parse_distance(&t),
Input::Enter => Some(0.0),
_ => return Ok(Step::Continue),
};
let finite = width.filter(|w| w.is_finite());
self.width = finite.ok_or_else(|| crate::EngineError::Other("Requires numeric distance or two points.".into()))?.max(0.0);
self.ask = Ask::FirstLine;
}
// Only typed text and Enter: a click in the drawing is no line of text, as at TEXT's.
Ask::FirstLine | Ask::NextLine => match i {
Input::Text(t) if !t.is_empty() => {
self.lines.push(t);
self.ask = Ask::NextLine;
}
Input::Text(_) | Input::Enter => {
let lines = std::mem::take(&mut self.lines);
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width: self.width } };
add_leader(s, &std::mem::take(&mut self.pts), false, true, ann)?;
return Ok(Step::Done);
}
_ => {}
},
}
Ok(Step::Continue)
}
}
/// QLEADER's JSON form: a leader through 2 or 3 `points`, with `text` (one line per line of it) as wide
/// as `width`, placed as the command line places them. The handles of the leader and its text.
pub(super) fn run_qleader(s: &mut Session, p: &Value) -> Result<Value> {
if p.get("points").is_none_or(Value::is_null) {
return Err(bad("qleader", "`points` is required"));
}
let pts = points_param(p, "points").ok_or_else(|| bad("qleader", "`points` must be a list of [x, y] points"))?;
if !(2..=MAX_POINTS).contains(&pts.len()) {
return Err(bad("qleader", "`points` takes 2 or 3 points"));
}
let width = size_param("qleader", p, "width", true)?.unwrap_or(0.0);
if p.get("text").is_some_and(|t| !t.is_null() && !t.is_string()) {
return Err(bad("qleader", "`text` must be a string"));
}
// Empty lines at the end are dropped, as the command line ends at one: a left-running leader
// would otherwise sit level with a blank last line. Text with nothing left is no text.
let mut lines: Vec<String> = str_param(p, "text").map(|t| t.lines().map(str::to_string).collect()).unwrap_or_default();
while lines.last().is_some_and(String::is_empty) {
lines.pop();
}
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width } };
let hs = add_leader(s, &pts, false, true, ann)?;
Ok(json!({ "handles": hs.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
+7 -5
View File
@@ -386,16 +386,18 @@ fn fmt(v: f64) -> String {
format!("{v:.4}")
}
/// A count typed at a prompt (Enter keeps `cur`); `None` for inputs the prompt ignores.
/// A count typed at a prompt (Enter keeps `cur`); `None` for inputs the prompt ignores. A whole
/// number as typed: AutoCAD 2024 takes +3 and 03 at its array counts and refuses 5.0, 1e1, 8/2
/// and 3' (measured at ARRAYRECT's rows and columns, ARRAYPOLAR's items and rows, and -ARRAY).
fn count(i: &Input, cur: u64, max: u64) -> Result<Option<u64>> {
match i {
Input::Enter => Ok(Some(cur)),
Input::Text(t) => t
.trim()
.parse::<f64>()
.parse::<u64>()
.ok()
.filter(|v| v.fract() == 0.0 && *v >= 1.0 && *v <= max as f64)
.map(|v| Some(v as u64))
.filter(|v| (1..=max).contains(v))
.map(Some)
.ok_or_else(|| other(format!("Requires an integer between 1 and {max} (MAXARRAY limits the size of the array)."))),
_ => Ok(None),
}
@@ -437,7 +439,7 @@ fn run_array(s: &mut Session, p: &Value) -> Result<Value> {
}
/// A count parameter (at least 1); a missing key gives the default, an invalid value is refused.
fn count_or(cmd: &str, p: &Value, key: &str, default: u64) -> Result<u64> {
pub(crate) fn count_or(cmd: &str, p: &Value, key: &str, default: u64) -> Result<u64> {
match p.get(key) {
None | Some(Value::Null) => Ok(default),
Some(v) => v.as_u64().filter(|n| *n >= 1).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of at least 1"))),
+183 -60
View File
@@ -403,13 +403,14 @@ fn run_insert(s: &mut Session, p: &Value) -> Result<Value> {
/// MINSERT's JSON form: INSERT's parameters and the grid.
fn run_minsert(s: &mut Session, p: &Value) -> Result<Value> {
// A whole number, as the array commands' JSON counts are: 2.0 and 1e2 are refused too.
let count = |key: &str| -> Result<u32> {
match p.get(key) {
None | Some(Value::Null) => Ok(1),
Some(v) => v
.as_f64()
.filter(|n| n.fract() == 0.0 && *n >= 1.0 && *n <= f64::from(Grid::MAX))
.map(|n| n as u32)
.as_u64()
.and_then(|n| u32::try_from(n).ok())
.filter(|n| (1..=Grid::MAX).contains(n))
.ok_or_else(|| bad("minsert", format!("`{key}` must be an integer between 1 and {}", Grid::MAX))),
}
};
@@ -833,11 +834,35 @@ enum InsStage {
/// rows).
Cell(Vec2),
ColSpacing,
/// The second of two points a preset or the column spacing takes after a point (AutoCAD 2024
/// asks "Specify second point:"), from the first.
Second(TwoPoints, Vec2),
Attribs,
/// A Verify attribute asked again.
Verify,
}
/// What two points give: a preset scale factor (all axes, or one) or the column spacing by their
/// distance, the preset rotation by their direction.
#[derive(Clone, Copy, Debug, PartialEq)]
enum TwoPoints {
Scale,
Axis(usize),
Rotation,
ColSpacing,
}
// AutoCAD 2024's messages at INSERT's and MINSERT's scale, rotation and spacing prompts (measured):
// a scale factor of 0; anything else that isn't a number where two points give a distance or an
// angle, where a point gives the distance from the insertion point, and where only a number does.
const NONZERO: &str = "Value must be nonzero.";
/// Exploded INSERT's scale factor, which must be positive.
const POSITIVE: &str = "Value must be positive and nonzero.";
const TWO_POINTS: &str = "Requires numeric distance or two points.";
const ANGLE_TWO_POINTS: &str = "Requires valid numeric angle or two points.";
const SECOND_POINT: &str = "Requires numeric distance or second point.";
const NUMERIC: &str = "Requires numeric value.";
#[derive(Default)]
struct InsertM {
stage: InsStage,
@@ -1018,6 +1043,66 @@ impl InsertM {
}
Ok(d)
}
/// The Scale preset `f` for every axis.
fn preset_scale(&mut self, s: &mut Session, f: f64) -> Result<Step> {
self.scale = Some(Vec2::new(f, f));
self.z_scale = Some(f.abs());
// An axis preset after it changes that axis alone (Scale -3 then X 2: 2/-3/3).
self.axes = [Some(f), Some(f), Some(f.abs())];
// Exploded insertion asks its one scale factor after the insertion point.
if self.at.is_some() {
return self.advance(s);
}
self.stage = InsStage::Point;
Ok(Step::Continue)
}
/// One axis preset: the others are 1, and no scale factors are asked after the point.
fn preset_axis(&mut self, ax: usize, f: f64) -> Result<Step> {
if let Some(a) = self.axes.get_mut(ax) {
*a = Some(f);
}
let [x, y, z] = self.axes.map(|a| a.unwrap_or(1.0));
self.scale = Some(Vec2::new(x, y));
self.z_scale = Some(z.abs());
self.stage = InsStage::Point;
Ok(Step::Continue)
}
fn preset_rotation(&mut self, r: f64) -> Result<Step> {
self.rotation = Some(r);
self.stage = InsStage::Point;
Ok(Step::Continue)
}
/// The second of two points (AutoCAD 2024, measured): their distance is a preset scale factor
/// (0 refused) or the column spacing (0 taken), their direction the preset rotation. Enter
/// keeps a preset's default and is refused for the spacing, as anything else is; a refusal asks
/// the first prompt again.
fn second_point(&mut self, s: &mut Session, what: TwoPoints, a: Vec2, i: Input) -> Result<Step> {
let (first, refused) = match what {
TwoPoints::Scale => (InsStage::PresetScale, TWO_POINTS),
TwoPoints::Axis(ax) => (InsStage::PresetAxis(ax), TWO_POINTS),
TwoPoints::Rotation => (InsStage::PresetRotation, ANGLE_TWO_POINTS),
TwoPoints::ColSpacing => (InsStage::ColSpacing, TWO_POINTS),
};
self.stage = first;
match (what, i) {
(TwoPoints::ColSpacing, Input::Point(b)) => {
self.col_spacing = Some(a.dist(b));
self.advance(s)
}
(TwoPoints::Rotation, Input::Point(b)) => self.preset_rotation(a.angle_to(b)),
(TwoPoints::Rotation, Input::Enter) => self.preset_rotation(0.0),
(TwoPoints::Scale | TwoPoints::Axis(_), Input::Point(b)) if a.dist(b) == 0.0 => Err(EngineError::Other(NONZERO.into())),
(TwoPoints::Scale, Input::Point(b)) => self.preset_scale(s, a.dist(b)),
(TwoPoints::Scale, Input::Enter) => self.preset_scale(s, 1.0),
(TwoPoints::Axis(ax), Input::Point(b)) => self.preset_axis(ax, a.dist(b)),
(TwoPoints::Axis(ax), Input::Enter) => self.preset_axis(ax, 1.0),
_ => Err(EngineError::Other(refused.into())),
}
}
}
/// A distance typed at MINSERT's grid prompts: any finite number, negative or 0 too.
@@ -1025,8 +1110,14 @@ fn distance(t: &str) -> Result<f64> {
number(t).filter(|v| v.is_finite()).ok_or_else(|| EngineError::Other("Requires a distance.".into()))
}
fn nonzero(t: &str) -> Result<f64> {
number(t).filter(|v| *v != 0.0).ok_or_else(|| EngineError::Other("Requires a non-zero number.".into()))
/// A scale factor typed at `t`: 0 gets AutoCAD 2024's "Value must be nonzero.", anything that
/// isn't a number the prompt's own message.
fn nonzero(t: &str, not_a_number: &str) -> Result<f64> {
let v = number(t).ok_or_else(|| EngineError::Other(not_a_number.into()))?;
if v == 0.0 {
return Err(EngineError::Other(NONZERO.into()));
}
Ok(v)
}
impl Interactive for InsertM {
@@ -1047,22 +1138,31 @@ impl Interactive for InsertM {
}
InsStage::Point => Prompt::new("Specify insertion point", Accept::POINT).kw(&["Basepoint", "Scale", "X", "Y", "Z", "Rotate"]),
InsStage::BasePoint => Prompt::new("Specify base point", Accept::POINT),
InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).default("1"),
InsStage::PresetAxis(i) => Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::NUMBER).default("1"),
// Exploded, after the insertion point, it takes a number only.
InsStage::PresetScale if self.at.is_some() => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).default("1"),
InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::POINT_OR_NUMBER).default("1"),
InsStage::PresetAxis(i) => {
Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::POINT_OR_NUMBER).default("1")
}
// Typed text is read as before (`<<45` the angle, not an override for a point); a point
// still comes from a click or LISP.
InsStage::PresetRotation => Prompt::new("Specify rotation angle", Accept::NUMBER).default("0"),
// Text is read here, not taken as a distance along the rubber band: the core console
// refuses 5 at this prompt (measured).
InsStage::Second(_, a) => Prompt::new("Specify second point", Accept::POINT_OR_NUMBER).base(a),
InsStage::XScale if self.xyz => Prompt::new("Specify X scale factor", Accept::POINT_OR_NUMBER).kw(&["Corner"]).default("1").base(at),
InsStage::XScale => {
Prompt::new("Enter X scale factor, specify opposite corner", Accept::POINT_OR_NUMBER).kw(&["Corner", "XYZ"]).default("1").base(at)
}
InsStage::Corner => Prompt::new("Specify opposite corner", Accept::POINT).base(at),
InsStage::YScale => Prompt::new("Enter Y scale factor", Accept::NUMBER).default("use X scale factor"),
InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::NUMBER).default("use X scale factor"),
InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::POINT_OR_NUMBER).default("use X scale factor").base(at),
InsStage::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER).default("0").base(at),
InsStage::Rows => Prompt::new("Enter number of rows (---)", Accept::NUMBER).default("1"),
InsStage::Cols => Prompt::new("Enter number of columns (|||)", Accept::NUMBER).default("1"),
InsStage::RowSpacing => Prompt::new("Enter distance between rows or specify unit cell (---)", Accept::POINT_OR_NUMBER),
InsStage::Cell(a) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a),
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::NUMBER),
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::POINT_OR_NUMBER),
InsStage::Attribs => {
let (_, prompt, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
let p = Prompt::new(if prompt.is_empty() { "Enter attribute value".into() } else { prompt }, Accept::TEXT);
@@ -1138,45 +1238,58 @@ impl Interactive for InsertM {
self.stage = InsStage::Point;
}
}
InsStage::PresetScale => {
let f = match i {
Input::Text(t) => nonzero(&t)?,
Input::Enter => 1.0,
_ => return Ok(Step::Continue),
// Exploded, after the insertion point: a positive number only (AutoCAD 2024 refuses a
// point and x with "Requires numeric value.", 0 and -2 with "Value must be positive and
// nonzero.", measured).
InsStage::PresetScale if self.at.is_some() => {
return match i {
Input::Text(t) => {
let f = number(&t).ok_or_else(|| EngineError::Other(NUMERIC.into()))?;
let f = Some(f).filter(|f| *f > 0.0).ok_or_else(|| EngineError::Other(POSITIVE.into()))?;
self.preset_scale(s, f)
}
Input::Enter => self.preset_scale(s, 1.0),
_ => Err(EngineError::Other(NUMERIC.into())),
};
self.scale = Some(Vec2::new(f, f));
self.z_scale = Some(f.abs());
// An axis preset after it changes that axis alone (Scale -3 then X 2: 2/-3/3).
self.axes = [Some(f), Some(f), Some(f.abs())];
// Exploded insertion asks its one scale factor after the insertion point.
if self.at.is_some() {
return self.advance(s);
}
self.stage = InsStage::Point;
}
// One axis preset: the others are 1, and no scale factors are asked after the point.
// A point at a preset is the first of two (AutoCAD 2024, measured).
InsStage::PresetScale => {
return match i {
Input::Point(p) => {
self.stage = InsStage::Second(TwoPoints::Scale, p);
Ok(Step::Continue)
}
Input::Text(t) => self.preset_scale(s, nonzero(&t, TWO_POINTS)?),
Input::Enter => self.preset_scale(s, 1.0),
_ => Err(EngineError::Other(TWO_POINTS.into())),
};
}
InsStage::PresetAxis(ax) => {
let f = match i {
Input::Text(t) => nonzero(&t)?,
Input::Enter => 1.0,
_ => return Ok(Step::Continue),
return match i {
Input::Point(p) => {
self.stage = InsStage::Second(TwoPoints::Axis(ax), p);
Ok(Step::Continue)
}
Input::Text(t) => self.preset_axis(ax, nonzero(&t, TWO_POINTS)?),
Input::Enter => self.preset_axis(ax, 1.0),
_ => Err(EngineError::Other(TWO_POINTS.into())),
};
if let Some(a) = self.axes.get_mut(ax) {
*a = Some(f);
}
let [x, y, z] = self.axes.map(|a| a.unwrap_or(1.0));
self.scale = Some(Vec2::new(x, y));
self.z_scale = Some(z.abs());
self.stage = InsStage::Point;
}
InsStage::PresetRotation => {
self.rotation = Some(match i {
Input::Text(t) => s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other("Requires an angle.".into()))?,
Input::Enter => 0.0,
_ => return Ok(Step::Continue),
});
self.stage = InsStage::Point;
return match i {
Input::Point(p) => {
self.stage = InsStage::Second(TwoPoints::Rotation, p);
Ok(Step::Continue)
}
Input::Text(t) => {
let r = s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other(ANGLE_TWO_POINTS.into()))?;
self.preset_rotation(r)
}
Input::Enter => self.preset_rotation(0.0),
_ => Err(EngineError::Other(ANGLE_TWO_POINTS.into())),
};
}
InsStage::Second(what, a) => return self.second_point(s, what, a, i),
InsStage::XScale => match i {
Input::Keyword(k) if k == "Corner" => self.stage = InsStage::Corner,
Input::Keyword(k) if k == "XYZ" => self.xyz = true,
@@ -1185,7 +1298,7 @@ impl Interactive for InsertM {
return self.corner_scale(s, sc);
}
Input::Text(t) => {
self.x_scale = Some(nonzero(&t)?);
self.x_scale = Some(nonzero(&t, "Requires a non-zero number.")?);
self.stage = InsStage::YScale;
}
Input::Enter => {
@@ -1202,10 +1315,11 @@ impl Interactive for InsertM {
}
InsStage::YScale => {
let x = self.x_scale.unwrap_or(1.0);
// A number only: AutoCAD 2024 refuses a point here (measured).
let y = match i {
Input::Text(t) => nonzero(&t)?,
Input::Text(t) => nonzero(&t, NUMERIC)?,
Input::Enter => x,
_ => return Ok(Step::Continue),
_ => return Err(EngineError::Other(NUMERIC.into())),
};
self.scale = Some(Vec2::new(x, y));
if self.xyz {
@@ -1214,11 +1328,15 @@ impl Interactive for InsertM {
}
return self.advance(s);
}
// A point gives its distance from the insertion point (AutoCAD 2024, measured).
InsStage::ZScale => {
self.z_scale = Some(match i {
Input::Text(t) => nonzero(&t)?,
Input::Text(t) => nonzero(&t, SECOND_POINT)?,
Input::Enter => self.x_scale.unwrap_or(1.0).abs(),
_ => return Ok(Step::Continue),
Input::Point(p) => {
Some(self.at.unwrap_or_default().dist(p)).filter(|d| *d != 0.0).ok_or_else(|| EngineError::Other(NONZERO.into()))?
}
_ => return Err(EngineError::Other(SECOND_POINT.into())),
});
return self.advance(s);
}
@@ -1232,17 +1350,14 @@ impl Interactive for InsertM {
return self.advance(s);
}
InsStage::Rows | InsStage::Cols => {
// A whole number as typed: AutoCAD 2024 takes +3 and 03 here and refuses 5.0, 5.,
// 1e1, 8/2, 3', 4.5 and a point (measured at the rows, and 5.0 and +3 at the columns).
let n = match i {
Input::Text(t) => t
.trim()
.parse::<f64>()
.ok()
.filter(|v| v.fract() == 0.0 && *v >= 1.0 && *v <= f64::from(Grid::MAX))
.map(|v| v as u32)
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 1 and {}.", Grid::MAX)))?,
Input::Enter => 1,
_ => return Ok(Step::Continue),
};
Input::Text(t) => t.trim().parse::<u32>().ok().filter(|v| (1..=Grid::MAX).contains(v)),
Input::Enter => Some(1),
_ => None,
}
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 1 and {}.", Grid::MAX)))?;
if self.stage == InsStage::Rows {
self.rows = Some(n);
} else {
@@ -1264,11 +1379,19 @@ impl Interactive for InsertM {
return self.advance(s);
}
}
// A distance, or two points (AutoCAD 2024, measured): Enter is refused too.
InsStage::ColSpacing => {
if let Input::Text(t) = i {
self.col_spacing = Some(distance(&t)?);
return self.advance(s);
}
return match i {
Input::Text(t) => {
self.col_spacing = Some(number(&t).filter(|v| v.is_finite()).ok_or_else(|| EngineError::Other(TWO_POINTS.into()))?);
self.advance(s)
}
Input::Point(p) => {
self.stage = InsStage::Second(TwoPoints::ColSpacing, p);
Ok(Step::Continue)
}
_ => Err(EngineError::Other(TWO_POINTS.into())),
};
}
InsStage::Attribs => {
let (tag, _, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
+4 -7
View File
@@ -3,7 +3,7 @@
use std::sync::Arc;
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert};
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert, TagKey};
use serde_json::{Value, json};
use crate::cmd::curves::KW;
@@ -102,17 +102,14 @@ impl Interactive for AttdispM {
/// Properties set on single attributes (layer, colour, …) go back to the definitions', as in AutoCAD.
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();
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 = ins
.attribs
.iter()
.find(|a| a.tag.eq_ignore_ascii_case(&ad.tag))
.map(|a| a.text.value.clone())
.unwrap_or_else(|| ad.text.value.clone());
t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
Attrib {
tag: ad.tag.clone(),
text: t,
+8 -8
View File
@@ -2,7 +2,7 @@
//! become text with the values they show instead of the block's attribute definitions.
use cadcraft_color::Color;
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Insert};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, TagKey};
use serde_json::{Value, json};
use crate::cmd::machines::SelectRun;
@@ -28,22 +28,22 @@ fn run_burst(s: &mut Session, p: &Value) -> Result<Value> {
fn burst_pieces(d: &Drawing, e: &Entity) -> Option<Vec<Entity>> {
let EntityKind::Insert(ins) = &e.kind else { return None };
let mut out: Vec<Entity> = explode_kind(d, e)?.into_iter().filter(|p| !matches!(p.kind, EntityKind::AttDef(_))).collect();
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = d.block(&ins.block).map(|b| b.attdefs_by_tag()).unwrap_or_default();
for a in ins.attribs.iter().filter(|a| !a.invisible) {
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
None => EntityKind::Text(a.text.clone()),
};
out.push(Entity { handle: Handle(0), common: attrib_common(d, e, ins, &a.tag, &a.props), kind });
out.push(Entity { handle: Handle(0), common: attrib_common(e, defs.get(&TagKey(&a.tag)).copied(), &a.props), kind });
}
Some(out)
}
/// The properties an attribute is drawn with: its own, else its definition's; layer 0 is the
/// reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the block's
/// objects.
fn attrib_common(d: &Drawing, e: &Entity, ins: &Insert, tag: &str, props: &cadcraft_doc::AttribProps) -> Common {
let def =
d.block(&ins.block).and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(tag))));
/// 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.
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);
+52 -5
View File
@@ -5,7 +5,7 @@
use cadcraft_doc::color::Color;
use cadcraft_doc::dynblock::{self, GripPart, GripShape};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, Transparency};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, TagKey, Transparency};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
@@ -111,11 +111,10 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
.collect();
// An attribute draws with its definition's properties, except those set on it.
let by_block = Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..r.clone() };
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = b.attdefs_by_tag();
out.extend(ins.attribs.iter().filter(|a| !a.invisible).map(|a| {
let def = b.entities.iter().find_map(|e| match &e.kind {
EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag) => Some(&e.common),
_ => None,
});
let def = defs.get(&TagKey(&a.tag)).map(|e| &e.common);
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
@@ -248,3 +247,51 @@ impl Session {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn many_attributes_are_previewed_without_comparing_every_pair_with_the_definitions() {
// #1923: a reference with N attributes of a block with N definitions, the tags N long ones
// alike up to their last characters, no attribute's a definition's. Looking for each
// attribute's definition by comparing it with every one cost N x N comparisons of whole
// tags for each preview (many seconds here); the definitions gathered by tag once cost
// milliseconds.
const N: usize = 4000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let attrib = |tag: String| cadcraft_doc::Attrib {
tag,
text: cadcraft_doc::Text {
insert: cadcraft_geom::Vec3::ZERO,
align_pt: None,
height: 1.0,
value: "v".into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
},
invisible: false,
constant: false,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
};
let mut d = Drawing::new_metric();
let mut blk = cadcraft_doc::Block::new("B");
for (h, i) in (1..).zip(0..N) {
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(attrib(tag('D', i)))));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let ins = cadcraft_doc::Insert { block: "B".into(), attribs: (0..N).map(|i| attrib(tag('A', i))).collect(), ..Default::default() };
let h = d.add(&cadcraft_doc::Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let t = std::time::Instant::now();
assert_eq!(drawn(&d, h).len(), N);
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
}
File diff suppressed because it is too large Load Diff
+24 -15
View File
@@ -8,7 +8,9 @@ use cadcraft_geom::{Mat3, Vec2, Vec3};
use serde_json::{Value, json};
use super::super::curves::KW;
use super::super::file::{Version, lost_message, lost_writing, new_folder, own_version, report_lost, report_new_folder};
use super::super::file::{
Version, drops_unknown, dwg_notes, lost_message, lost_writing, new_folder, own_version, report_dwg_notes, report_lost, report_new_folder,
};
use super::super::machines::{SelOutcome, SelectPhase};
use super::super::modify::erase_kept;
use super::super::{CommandSpec, bad, point_param, str_param, targets};
@@ -46,7 +48,7 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string();
let base = point_param(p, "base");
let folder = new_folder(&path);
let (entities, bytes, lost, version) = match str_param(p, "name") {
let (entities, bytes, lost, version, notes) = match str_param(p, "name") {
Some("*") => write(s, "wblock", &path, Source::Whole)?,
Some(name) => write(s, "wblock", &path, Source::Block(name, base))?,
None => write(s, "wblock", &path, Source::Objects(&targets(s, p)?, base.unwrap_or(Vec2::ZERO)))?,
@@ -54,6 +56,7 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
report_new_folder(s, &mut r, folder);
report_lost(s, &mut r, &path, version, &lost);
report_dwg_notes(s, &mut r, notes);
Ok(r)
}
@@ -64,7 +67,7 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("-wblock", "`path` is required"))?.to_string();
let base = point_param(p, "base");
let folder = new_folder(&path);
let (entities, bytes, lost, version) = match str_param(p, "name") {
let (entities, bytes, lost, version, notes) = match str_param(p, "name") {
Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?,
None => {
let hs = targets(s, p)?;
@@ -80,16 +83,17 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
report_new_folder(s, &mut r, folder);
report_lost(s, &mut r, &path, version, &lost);
report_dwg_notes(s, &mut r, notes);
Ok(r)
}
/// Write `what` to `path` through the io hooks; the objects written, the file's size, what the
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams) and
/// the version it was written at, for the caller to report as a save does. The
/// written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its units
/// ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches and
/// scaled on insert, and its defaults (text size, current styles, annotation scales).
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version)> {
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams), the
/// version it was written at and what a DWG keeps only in part, for the caller to report as a
/// save does. The written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK
/// does: its units ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in
/// inches and scaled on insert, and its defaults (text size, current styles, annotation scales).
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version, Vec<String>)> {
let src = s.doc()?;
// The base point becomes the written drawing's origin: by default 0,0 for objects and the
// block's base point for a block.
@@ -115,14 +119,19 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi
// The written drawing's own version: the writer is given no other.
let version = own_version(&d, path);
let lost = lost_writing(&d, path, version);
Ok((d.model.len(), bytes.len(), lost, version))
let notes = if drops_unknown(path) { dwg_notes(&d) } else { Vec::new() };
Ok((d.model.len(), bytes.len(), lost, version, notes))
}
/// Say on the command line what the file written at `path` and `version` left out.
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>) {
/// Say on the command line what the file written at `path` and `version` left out, and what a
/// DWG keeps only in part (`notes`).
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>, notes: Vec<String>) {
if let Some(msg) = lost_message(path, version, lost) {
s.echo(msg);
}
for note in notes {
s.echo(note);
}
}
/// A new drawing of `ents`, with `src`'s settings and the layers, linetypes, styles and blocks
@@ -341,7 +350,7 @@ impl DashWblockM {
fn write(&self, s: &mut Session, what: Source) -> Result<Step> {
match write(s, "-wblock", &self.path, what) {
Ok((.., lost, version)) => echo_not_saved(s, &self.path, version, &lost),
Ok((.., lost, version, notes)) => echo_not_saved(s, &self.path, version, &lost, notes),
Err(e) => s.echo(e.to_string()),
}
Ok(Step::Done)
@@ -352,8 +361,8 @@ impl DashWblockM {
return Ok(Step::Done);
}
match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) {
Ok((.., lost, version)) => {
echo_not_saved(s, &self.path, version, &lost);
Ok((.., lost, version, notes)) => {
echo_not_saved(s, &self.path, version, &lost, notes);
erase(s, hs)?;
}
Err(e) => s.echo(e.to_string()),
+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"));
}
+18 -6
View File
@@ -79,17 +79,27 @@ pub(crate) fn paste(s: &mut Session, m: &Mat3) -> Result<Vec<Handle>> {
let defs = s.clipboard_source.as_ref().map(|c| c.defs.clone());
let space = s.space();
let d = s.doc_mut()?;
let renames = defs.map(|x| merge(d, &x)).unwrap_or_default();
let renames = defs.as_ref().map(|x| merge(d, x)).unwrap_or_default();
let mut out = Vec::new();
let mut copies = Vec::new();
for e in &ents {
let old_h = e.handle;
let mut e = adopt(d, e, &renames);
e.kind.transform(m);
d.ensure_layer(&e.common.layer);
out.push(e.handle);
copies.push((old_h, e.handle));
if let Some(st) = d.space_mut(&space) {
st.push(e);
}
}
if let Some(c) = &defs
&& !c.groups.is_empty()
{
super::groups::replicate_groups_from(d, &c.groups, &copies);
} else {
super::groups::replicate_groups_for_copies(d, &copies);
}
s.set_selection(out.clone());
Ok(out)
}
@@ -265,13 +275,15 @@ fn defs_for(src: &Drawing, ents: &[Entity]) -> Drawing {
}
let mut d = Drawing::new_imperial();
d.header = src.header.clone();
d.layers = pick(&src.layers, &used.layers, |l| &l.name);
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name);
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name);
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name);
d.layers = pick(&src.layers, &used.layers, |l| &l.name).into();
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name).into();
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name).into();
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name).into();
d.mleader_styles = pick(&src.mleader_styles, &used.mleader_styles, |t| &t.name);
d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name);
d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name).into();
d.blocks = src.blocks.iter().filter(|(k, _)| used.blocks.contains(&up(k))).map(|(k, b)| (k.clone(), b.clone())).collect();
let ent_handles: HashSet<Handle> = ents.iter().map(|e| e.handle).collect();
d.groups = src.groups.iter().filter(|g| !g.members.is_empty() && g.members.iter().all(|m| ent_handles.contains(m))).cloned().collect();
d.layouts.clear();
d
}
+1 -1
View File
@@ -129,7 +129,7 @@ fn save(s: &mut Session, name: &str, annotative: Option<bool>, replace: bool) ->
if let Some(a) = annotative {
st.annotative = a;
}
let name = match d.dim_styles.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
let name = match d.dim_styles.by_name_mut(&name) {
Some(existing) if replace => {
let kept = existing.name.clone();
*existing = DimStyle { name: kept.clone(), ..st };
+2 -2
View File
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("pline", "Polyline", run_pline)
.menu(&["Draw", "Polyline"])
.alias(&["pl"])
.params("{vertices: [[x,y] | {p:[x,y], bulge, startWidth, endWidth}], closed?, width?}")
.params("{vertices: [[x,y] | {p:[x,y], bulge, startWidth, endWidth}], closed?, width? (default PLINEWID unless vertices give widths)}")
.interactive(|_| Ok(Box::new(PlineM::default()))),
CommandSpec::new("circle", "Circle", run_circle)
.menu(&["Draw", "Circle", "Center, Radius"])
@@ -62,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("rectang", "Rectangle", super::draw2::run_rectang2)
.menu(&["Draw", "Rectangle"])
.alias(&["rec", "rectangle"])
.params("{p1, p2 | dimensions: [l, w] (p2 picks the quadrant) | area + length|breadth, rotation? (deg), fillet?, chamfer?: [d1, d2], width?, elevation?, thickness?, center?: bool (p1 is the centre, not a corner; the size spans it evenly)}")
.params("{p1, p2 | dimensions: [l, w] (p2 picks the quadrant) | area + length|breadth (the outline encloses it, cut corners included), rotation? (deg), fillet? (wins over a chamfer), chamfer?: [d1, d2], width?, elevation?, thickness?, center?: bool (p1 is the centre, not a corner; the size spans it evenly)}")
.interactive(|_| Ok(Box::new(super::draw2::RectM2::default()))),
CommandSpec::new("polygon", "Polygon", run_polygon)
.menu(&["Draw", "Polygon"])
+21 -3
View File
@@ -45,15 +45,21 @@ fn current_elevation(s: &Session) -> Result<f64> {
pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
let raw = p.get("vertices").or_else(|| p.get("points")).and_then(Value::as_array);
let mut vertex_widths = false;
for v in raw.into_iter().flatten() {
size_param("pline", v, "startWidth", true)?;
size_param("pline", v, "endWidth", true)?;
vertex_widths |= size_param("pline", v, "startWidth", true)?.is_some() | size_param("pline", v, "endWidth", true)?.is_some();
}
let vs: Vec<PolyVertex> = raw.map(|a| a.iter().filter_map(vertex_value).collect()).unwrap_or_default();
if vs.len() < 2 {
return Err(bad("pline", "`vertices` needs at least 2 points"));
}
let width = size_param("pline", p, "width", true)?.unwrap_or(0.0);
// Without a width, the polyline starts at PLINEWID as the command does (unless its vertices
// give their own widths).
let width = match size_param("pline", p, "width", true)? {
Some(w) => w,
None if vertex_widths => 0.0,
None => Some(s.doc()?.header.f64("PLINEWID", 0.0)).filter(|w| w.is_finite() && *w > 0.0).unwrap_or(0.0),
};
let mut k = lwpoly(vs, bool_or(p, "closed", false));
if let EntityKind::LwPolyline(pl) = &mut k {
pl.const_width = width;
@@ -266,8 +272,11 @@ impl Interactive for PlineM {
fn name(&self) -> &'static str {
"PLINE"
}
/// Segments start at PLINEWID, the width the last Width or Halfwidth answer left.
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.elevation = current_elevation(s)?;
let w = s.doc()?.header.f64("PLINEWID", 0.0);
(self.start_w, self.end_w) = if w.is_finite() && w > 0.0 { (w, w) } else { (0.0, 0.0) };
Ok(Step::Continue)
}
fn prompt(&self, s: &Session) -> Prompt {
@@ -316,6 +325,11 @@ impl Interactive for PlineM {
self.end_w = self.start_w;
}
self.asking_width = if self.asking_width == 1 { 2 } else { 0 };
if self.asking_width == 0 {
// The ending width becomes PLINEWID, the next polyline's width (AutoCAD:
// Halfwidth 0.5 0.5 leaves PLINEWID 1).
s.doc_mut()?.header.set_f64("PLINEWID", self.end_w);
}
return Ok(Step::Continue);
}
if let (Some(a), Some(st)) = (self.ask, self.verts.last().map(|v| v.p)) {
@@ -379,6 +393,10 @@ impl Interactive for PlineM {
l.bulge = 0.0;
(l.start_width, l.end_width) = (0.0, 0.0);
}
// Back to the mode of the segment now last (AutoCAD: `_A` point `_U` returns
// to "Specify next point", where `_L` is Length, not arc mode's Line).
let n = self.verts.len();
self.arc_mode = n >= 2 && self.verts.get(n - 2).is_some_and(|v| v.bulge != 0.0);
self.sync(s, false)?;
Ok(Step::Continue)
}
+7 -1
View File
@@ -125,7 +125,11 @@ impl Interactive for SplineM {
}
match i {
Input::Point(p) => {
self.pts.push(p);
// The same point again is not a further fit point (AutoCAD 2024 leaves it out),
// nor a kink.
if self.pts.last() != Some(&p) {
self.pts.push(p);
}
Ok(Step::Continue)
}
Input::Keyword(k) if k == "Undo" => {
@@ -175,6 +179,8 @@ impl Interactive for SplineM {
}
Some(crate::cmd::spline_opts::SplineAsk::EndTangent) => opts.end_tangent = self.pts.last().map(|l| c - *l).filter(|d| d.len() > 1e-12),
Some(_) => {}
// The cursor on the last point adds nothing, as a click there doesn't.
None if pts.last() == Some(&c) => {}
None => pts.push(c),
}
if pts.len() < 2 {
+1 -1
View File
@@ -7,7 +7,7 @@ use cadcraft_geom::{Arc, Circle, Ellipse, Line, PolyVertex, Polyline, Spline, TA
use serde_json::{Value, json};
use super::curves::{self, Chain, MAX_GEN, TanObj};
use super::helpers::{arc, circle, line, lwpoly, rect_vertices, rect_with_corners, v3};
use super::helpers::{arc, circle, line, lwpoly, rect_corners_fit, rect_vertices, rect_with_corners, v3};
use super::machines::number;
use super::{CommandSpec, bad, bool_or, f64_or, f64_req, point_param, point_req, point_value, points_param, size_param, str_param, targets};
+33 -14
View File
@@ -139,6 +139,15 @@ impl DivideM {
pub(super) fn new(measure: bool) -> Self {
DivideM { measure, obj: None, phase: DivPhase::Object, block: None, align: true }
}
/// The JSON form's parameters for the picked object, before the count or length.
fn params(&self, h: Handle, pick: Vec2) -> Value {
let mut params = json!({ "handle": h.hex(), "align": self.align, "from": [pick.x, pick.y] });
if let Some(b) = &self.block {
params["block"] = json!(b);
}
params
}
}
impl Interactive for DivideM {
@@ -187,27 +196,37 @@ impl Interactive for DivideM {
self.phase = DivPhase::Value;
Ok(Step::Continue)
}
(DivPhase::Value, inp @ (Input::Text(_) | Input::Point(_))) => {
(DivPhase::Value, inp @ (Input::Text(_) | Input::Point(_))) if self.measure => {
let Some((h, pick)) = self.obj else { return Ok(Step::Cancel) };
let v = match inp {
Input::Text(t) => number(&t).ok_or_else(|| other("Requires a number."))?,
Input::Point(q) => pick.dist(q),
_ => return Ok(Step::Continue),
};
let mut params = json!({ "handle": h.hex(), "align": self.align, "from": [pick.x, pick.y] });
if let Some(b) = &self.block {
params["block"] = json!(b);
}
if self.measure {
params["length"] = json!(v);
run_measure(s, &params)?;
} else {
if !(2.0..=32767.0).contains(&v) || v.fract() != 0.0 {
return Err(other("Requires an integer between 2 and 32767."));
}
params["segments"] = json!(v as u64);
run_divide(s, &params)?;
let mut params = self.params(h, pick);
params["length"] = json!(v);
run_measure(s, &params)?;
Ok(Step::Done)
}
(DivPhase::Value, inp) if !self.measure => {
// A whole number as typed: AutoCAD 2024 takes +5 and 05 here and refuses 5.0, 5.,
// 1e1, 4.5, 1, 32768, x, Enter and a point, naming the Block keyword while the
// prompt still offers it (measured).
let n = match inp {
Input::Text(t) => t.trim().parse::<u64>().ok().filter(|n| (2..=32767).contains(n)),
_ => None,
}
.ok_or_else(|| {
other(if self.block.is_some() {
"Requires an integer between 2 and 32767."
} else {
"Requires an integer between 2 and 32767, or option keyword."
})
})?;
let Some((h, pick)) = self.obj else { return Ok(Step::Cancel) };
let mut params = self.params(h, pick);
params["segments"] = json!(n);
run_divide(s, &params)?;
Ok(Step::Done)
}
(_, Input::Enter) => Ok(Step::Cancel),
+42 -16
View File
@@ -1,6 +1,6 @@
use super::{
Accept, EntityKind, Input, Interactive, PolyVertex, Prompt, Result, Session, Step, Value, Vec2, added, bad, bool_or, curves, f64_or, lwpoly,
number, other, point_param, point_req, rect_with_corners, size_param,
number, other, point_param, point_req, rect_corners_fit, rect_with_corners, size_param,
};
use crate::last_used::RectangModes;
@@ -19,9 +19,30 @@ fn rect_kind(first: Vec2, (w, h): (f64, f64), rot: f64, fillet: f64, chamfer: (f
k
}
/// The area a fillet's or chamfer's four corners take off the full rectangle (a fillet wins).
fn corner_area(fillet: f64, chamfer: (f64, f64)) -> f64 {
if fillet > 0.0 {
(4.0 - std::f64::consts::PI) * fillet * fillet
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 {
2.0 * chamfer.0 * chamfer.1
} else {
0.0
}
}
/// The sides of the rectangle of `area` with one side `side`, its length (or with `breadth`,
/// its width). AutoCAD sizes it so that the outline, corners cut, encloses the area: the corners'
/// area is added back. When the corners then don't fit they stay square, and the area is the full
/// rectangle's.
fn area_sides(area: f64, side: f64, breadth: bool, fillet: f64, chamfer: (f64, f64)) -> (f64, f64) {
let sides = |a: f64| if breadth { (a / side, side) } else { (side, a / side) };
let (w, h) = sides(area + corner_area(fillet, chamfer));
if rect_corners_fit(Vec2::new(w, h), fillet, chamfer) { (w, h) } else { sides(area) }
}
/// The width and height of a rectangle from its `dimensions`, its `p2` corner, its `area` with
/// `length` or `breadth`, or its second corner `p2`, rotated by `rot` about `a`.
fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool) -> Result<(f64, f64)> {
fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool, fillet: f64, chamfer: (f64, f64)) -> Result<(f64, f64)> {
Ok(if let Some(d) = p.get("dimensions").and_then(Value::as_array) {
let l = d.first().and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("rectang", "dimensions: [length, width]"))?;
let wd = d.get(1).and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("rectang", "dimensions: [length, width]"))?;
@@ -38,8 +59,8 @@ fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool) -> Result<(f64, f64)>
return Err(bad("rectang", "area must be positive"));
}
match (p.get("length").and_then(Value::as_f64), p.get("breadth").and_then(Value::as_f64)) {
(Some(l), _) if l.is_finite() && l > 0.0 => (l, area / l),
(_, Some(b)) if b.is_finite() && b > 0.0 => (area / b, b),
(Some(l), _) if l.is_finite() && l > 0.0 => area_sides(area, l, false, fillet, chamfer),
(_, Some(b)) if b.is_finite() && b > 0.0 => area_sides(area, b, true, fillet, chamfer),
_ => return Err(bad("rectang", "area needs `length` or `breadth`")),
}
} else {
@@ -68,7 +89,7 @@ pub(crate) fn run_rectang2(s: &mut Session, p: &Value) -> Result<Value> {
}
let fillet = size_param("rectang", p, "fillet", true)?.unwrap_or(0.0);
let width = size_param("rectang", p, "width", true)?.unwrap_or(0.0);
let (w, h) = rect_size(p, a, rot, centered)?;
let (w, h) = rect_size(p, a, rot, centered, fillet, ch)?;
if w.abs() < 1e-12 || h.abs() < 1e-12 || !w.is_finite() || !h.is_finite() {
return Err(bad("rectang", "rectangle has no area"));
}
@@ -116,10 +137,13 @@ pub(crate) struct RectM2 {
asking: Option<RAsk>,
}
/// A rectangle's rotation as AutoCAD 2024 shows it: degrees from 0 to 360, two decimals.
fn rotation_text(rotation: f64) -> String {
let t = format!("{:.2}", rotation.to_degrees().rem_euclid(360.0));
if t == "360.00" { "0.00".into() } else { t }
/// A rectangle's rotation (radians counterclockwise from +X) as AutoCAD 2024 shows it: from
/// ANGBASE in the ANGDIR sense, in the drawing's angle units, to two places. Rotation 30 typed
/// with ANGBASE 90 and ANGDIR 1 shows as "120.00", and 30.5 in degrees/minutes/seconds as
/// "30d30'".
fn rotation_text(s: &Session, rotation: f64) -> String {
let au = s.angle_settings();
crate::units::format_angle(au.shown(rotation), au.aunits, 2)
}
/// AutoCAD 2024's line listing the RECTANG modes that are set, `None` when none is ("Current
@@ -144,9 +168,10 @@ fn modes_line(s: &Session, m: &RectangModes) -> Option<String> {
if m.width > 0.0 {
parts.push(format!("Width={}", d(m.width)));
}
let rot = rotation_text(m.rotation);
if rot != "0.00" {
parts.push(format!("Rotation={rot}"));
// Listed when the rectangle is turned from +X at all, to two places, whatever ANGBASE says.
let turned = format!("{:.2}", m.rotation.to_degrees().rem_euclid(360.0));
if turned != "0.00" && turned != "360.00" {
parts.push(format!("Rotation={}", rotation_text(s, m.rotation)));
}
(!parts.is_empty()).then(|| format!("Current rectangle modes: {}", parts.join(" ")))
}
@@ -219,7 +244,7 @@ impl Interactive for RectM2 {
}
/// Asks for the pending option's value, or for the first and second points; in centre mode
/// the first prompt asks for the centre instead of a corner.
fn prompt(&self, _s: &Session) -> Prompt {
fn prompt(&self, s: &Session) -> Prompt {
let num = |m: &str, d: f64| Prompt::new(m, Accept::NUMBER).default(format!("{d:.4}"));
if let Some(a) = self.asking {
return match a {
@@ -237,7 +262,7 @@ impl Interactive for RectM2 {
RAsk::DimW => num("Specify width for rectangles", self.dims.map(|d| d.1).unwrap_or(10.0)),
RAsk::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER)
.kw(&["Pick points"])
.default(rotation_text(self.rotation))
.default(rotation_text(s, self.rotation))
.base_opt(self.first),
RAsk::RotPick1 => Prompt::new("Specify first point", Accept::POINT),
RAsk::RotPick2(b) => Prompt::new("Specify second point", Accept::POINT).base(b),
@@ -299,7 +324,7 @@ impl Interactive for RectM2 {
self.asking = Some(a);
return Err(other("Value must be positive."));
}
let (w, h) = if a == RAsk::AreaLength { (v, self.area / v) } else { (self.area / v, v) };
let (w, h) = area_sides(self.area, v, a == RAsk::AreaWidth, self.fillet, self.chamfer);
return self.make(s, w, h);
}
RAsk::DimL => {
@@ -314,7 +339,8 @@ impl Interactive for RectM2 {
RAsk::Rotation => match i {
Input::Keyword(_) => self.asking = Some(RAsk::RotPick1),
Input::Point(p) => self.rotation = self.first.map(|f| f.angle_to(p)).unwrap_or(0.0),
Input::Text(t) => self.rotation = s.angle_settings().direction(&t).ok_or_else(|| other("Requires a valid angle."))?,
// An amount turned in the ANGDIR sense from +X, ANGBASE aside, as AutoCAD takes it.
Input::Text(t) => self.rotation = s.angle_settings().rotation(&t).ok_or_else(|| other("Requires a valid angle."))?,
_ => {}
},
RAsk::RotPick1 => {
+5 -1
View File
@@ -26,6 +26,10 @@ fn default_max_arc_len(s: &Session, min: f64) -> f64 {
s.doc().ok().map_or(min, |d| d.header.f64("CADCRAFT_REVCLOUDMAXARCLEN", min)).max(min)
}
/// The bulge of every arc of a revision cloud (an arc of about 110°). Readers that check
/// `RevcloudProps` xdata and bulge accept a closed polyline whose bulges are within 0.02 of this.
const CLOUD_BULGE: f64 = 0.520567050552;
/// Bulged closed polyline vertices for a revision cloud around `boundary`.
pub(crate) fn cloud_vertices(boundary: &[Vec2], arc_len: f64, per_edge: bool, reverse: bool) -> Option<Vec<PolyVertex>> {
let mut pts: Vec<Vec2> = Vec::new();
@@ -69,7 +73,7 @@ pub(crate) fn cloud_vertices(boundary: &[Vec2], arc_len: f64, per_edge: bool, re
out.extend(chain.at_length_in(&ends, perim * j as f64 / k as f64).map(|x| x.0));
}
}
let b = if reverse { -0.5 } else { 0.5 };
let b = if reverse { -CLOUD_BULGE } else { CLOUD_BULGE };
Some(out.into_iter().map(|p| PolyVertex::with_bulge(p, b)).collect())
}
+251 -5
View File
@@ -729,6 +729,57 @@ fn divide_and_measure_command_line() {
s.cancel();
}
#[test]
fn divide_takes_a_whole_number_as_typed() {
// AutoCAD 2024 at "Enter the number of segments or [Block]:": +5, 05, the LISP real 5.0 and
// 32767 are taken; 5.0, 5., 1e1, 4.5, 1, 0, -3, 32768, x, Enter and a point from LISP are
// refused and asked again (measured).
let points = |s: &Session| kinds(s).iter().filter(|k| **k == "Point").count();
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
s.cmdline("divide 5,0").unwrap();
let asked = s.prompt_text();
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter the number of segments or [Block]:"));
for bad in ["5.0", "5.", "1e1", "4.5", "1", "0", "-3", "32768", "x", "", "(list 1 2)"] {
let logged = s.log.len();
s.cmdline(bad).unwrap();
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
assert_eq!(said, ["Requires an integer between 2 and 32767, or option keyword."], "{bad:?}");
assert_eq!(s.prompt_text(), asked, "{bad:?}");
}
assert_eq!(points(&s), 0);
s.cmdline("+5").unwrap();
assert!(s.running.is_none());
assert_eq!(points(&s), 4);
for (typed, n) in [("05", 4), ("(+ 2.5 2.5)", 4), ("2", 1), ("32767", 32766)] {
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
s.cmdline("divide 5,0").unwrap();
s.cmdline(typed).unwrap();
assert!(s.running.is_none(), "{typed}: {}", s.prompt_text());
assert_eq!(points(&s), n, "{typed}");
}
// MEASURE shares the prompt machine and is unchanged: Enter at its length still ends it.
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
s.cmdline("measure 5,0").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(points(&s), 0);
// After Block the prompt offers no keyword, and the message names none (AutoCAD 2024, measured).
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
let tick = s.execute("circle", &json!({"center": [50, 50], "radius": 0.1})).unwrap();
s.execute("block", &json!({"name": "DOT", "base": [50, 50], "handles": [h(&tick)], "keep": "delete"})).unwrap();
s.cmdline("divide 5,0 b DOT y").unwrap();
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter the number of segments:"));
s.cmdline("5.0").unwrap();
assert_eq!(s.log.last().map(String::as_str), Some("Requires an integer between 2 and 32767."));
s.cmdline("5").unwrap();
assert!(s.running.is_none());
assert_eq!(kinds(&s).iter().filter(|k| **k == "Block Reference").count(), 4);
}
// ---------------- REVCLOUD ----------------
#[test]
@@ -1101,6 +1152,198 @@ fn rectang_options_command_line() {
}
}
/// RECTANG against what AutoCAD 2024 stores for the same typed input (black-box: synthetic
/// input in accoreconsole, read back with `entget`): Area with the corners taken off, and
/// corners too large for the sides.
#[test]
fn rectang_area_and_oversized_corners_match_autocad() {
type Case = (&'static [&'static str], &'static [[f64; 3]], [f64; 3]);
// (typed input, vertices [x, y, bulge], [width, elevation, thickness])
let cases: [Case; 4] = [
// RECTANG-028: Area counts the chamfered corners off.
(
&["rectang _C 1.5 2.5 26.36462345136234,-19.7291241693893 _R 0 _A 1442.9297064464572 _W 35.53488991311575"],
&[
[26.36462345136234, -18.2291241693893, 0.0],
[28.86462345136234, -19.7291241693893, 0.0],
[65.68168268505678, -19.7291241693893, 0.0],
[67.18168268505678, -17.2291241693893, 0.0],
[67.18168268505678, 14.30576574372644, 0.0],
[64.68168268505678, 15.80576574372644, 0.0],
[27.86462345136234, 15.80576574372644, 0.0],
[26.36462345136234, 13.30576574372644, 0.0],
],
[0.0, 0.0, 0.0],
),
// RECTANG-035-VN: Area counts the fillets off, at survey coordinates.
(
&["rectang _F 2.0 612322.0691653182,2398792.948957577 _R 0 _A 592.8936847254046 _L 19.287858563349488"],
&[
[612322.0691653182, 2398794.948957577, 0.414213562373095],
[612324.0691653182, 2398792.948957577, 0.0],
[612339.3570238815, 2398792.948957577, 0.414213562373095],
[612341.3570238815, 2398794.948957577, 0.0],
[612341.3570238815, 2398821.866195597, 0.414213562373095],
[612339.3570238815, 2398823.866195598, 0.0],
[612324.0691653182, 2398823.866195598, 0.414213562373095],
[612322.0691653182, 2398821.866195597, 0.0],
],
[0.0, 0.0, 0.0],
),
// RECTANG-029: a fillet too large: each corner two coincident vertices.
(
&["rectang _F 11.37084114989061 -21.46774953784037,-0.023473793210982308 _R 0 -2.5163476213560187,49.88119923361903"],
&[
[-21.46774953784036, -0.0234737932109823, 0.0],
[-21.46774953784036, -0.0234737932109823, 0.0],
[-2.516347621356018, -0.0234737932109823, 0.0],
[-2.516347621356018, -0.0234737932109823, 0.0],
[-2.516347621356018, 49.88119923361903, 0.0],
[-2.516347621356018, 49.88119923361903, 0.0],
[-21.46774953784036, 49.88119923361903, 0.0],
[-21.46774953784036, 49.88119923361903, 0.0],
],
[0.0, 0.0, 0.0],
),
// RECTANG-039-VN: a chamfer too large, rotated, with Dimensions.
(
&[
"rectang _C 18.656567079201356 18.656567079201356 612317.9599920243,2398739.0200147885 _R 30 _D 26.652238684573366 32.64533161964191 612344.6122307089,2398771.6653464083",
],
&[
[612317.9599920243, 2398739.020014788, 0.0],
[612317.9599920243, 2398739.020014788, 0.0],
[612341.041507793, 2398752.34613413, 0.0],
[612341.041507793, 2398752.34613413, 0.0],
[612324.7188419831, 2398780.617820628, 0.0],
[612324.7188419831, 2398780.617820628, 0.0],
[612301.6373262145, 2398767.291701286, 0.0],
[612301.6373262145, 2398767.291701286, 0.0],
],
[0.0, 0.0, 0.0],
),
];
let same = |a: f64, b: f64| (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0);
for (input, want, [width, elevation, thickness]) in cases {
let mut s = Session::new();
for line in input {
s.cmdline(line).unwrap();
assert!(s.running.is_none(), "{line}: {}", s.prompt_text());
}
let e = s.doc().unwrap().model.last().unwrap().clone();
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{input:?}: {:?}", e.kind) };
let got: Vec<[f64; 3]> = p.vertices.iter().map(|v| [v.p.x, v.p.y, v.bulge]).collect();
let ok = got.len() == want.len() && got.iter().zip(want).all(|(g, w)| g.iter().zip(w).all(|(a, b)| same(*a, *b)));
assert!(
ok,
"{input:?}
got {got:?}
want {want:?}"
);
assert!(p.closed && same(p.const_width, width) && same(p.elevation, elevation) && same(e.common.thickness, thickness), "{input:?}");
}
// Rotation, elevation and thickness are remembered too: AutoCAD opens the next RECTANG with
// "Current rectangle modes: Elevation=7.5000 Thickness=2.2500 Rotation=30.96".
let mut s = Session::new();
s.cmdline("rectang _E 7.5 _T 2.25 0,0 _R _P 0,0 10,6 10,20").unwrap();
s.cmdline("rectang 100,100 110,105").unwrap();
let e = s.doc().unwrap().model.last().unwrap().clone();
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{:?}", e.kind) };
let edge = p.vertices[1].p - p.vertices[0].p;
assert!(p.vertices[0].p == Vec2::new(100.0, 100.0) && same(edge.angle(), 6f64.atan2(10.0)), "{p:?}");
assert!(p.elevation == 7.5 && e.common.thickness == 2.25);
}
/// RECTANG's Rotation follows the drawing's angle settings as AutoCAD 2024's does.
#[test]
fn rectang_rotation_follows_the_angle_settings() {
let modes = |s: &Session| s.log.iter().filter(|l| l.starts_with("Current rectangle modes:")).cloned().collect::<Vec<_>>();
// With ANGBASE 90 and ANGDIR 1, AutoCAD 2024 turns a rectangle given Rotation 30 clockwise
// by 30° from +X (ANGBASE aside), and shows that rotation from ANGBASE: "Rotation=120.00",
// and <120.00> as the next rotation default.
let mut s = Session::new();
s.cmdline("setvar angbase 90").unwrap();
s.cmdline("setvar angdir 1").unwrap();
s.cmdline("rectang 50,0 _R 30 60,5").unwrap();
let e = s.doc().unwrap().model.last().unwrap().clone();
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{:?}", e.kind) };
let edge = p.vertices[1].p - p.vertices[0].p;
assert!((edge.y.atan2(edge.x) + 30f64.to_radians()).abs() < 1e-9, "{p:?}");
s.start("rectang").unwrap();
assert_eq!(modes(&s), ["Current rectangle modes: Rotation=120.00"]);
s.cmdline("50,0").unwrap();
s.cmdline("_R").unwrap();
assert!(s.prompt_text().contains("<120.00>"), "{}", s.prompt_text());
s.cancel();
// In degrees/minutes/seconds: "Rotation=30d30'".
let mut s = Session::new();
s.cmdline("setvar aunits 1").unwrap();
s.cmdline("rectang 50,0 _R 30.5 60,5").unwrap();
s.start("rectang").unwrap();
assert_eq!(modes(&s), ["Current rectangle modes: Rotation=30d30'"]);
s.cancel();
}
/// Area allows for cut corners only while they fit: a fillet too large for the resulting sides
/// leaves square corners, so the rectangle is the full area asked for (4 × 1, not 4 × 1.858).
/// Corners exactly as long as the shorter side allows still fit; a hair longer and the corners
/// stay square, each still written twice (AutoCAD 2024, `entget` of a 4 x 2 rectangle).
#[test]
fn rectang_corners_at_the_limit_fit_and_just_over_stay_square() {
let b = (std::f64::consts::PI / 8.0).tan();
let fit: [(&str, &[(f64, f64, f64)]); 4] = [
(
"_F 0.9999",
&[
(0.0, 0.9999, b),
(0.9999, 0.0, 0.0),
(3.0001, 0.0, b),
(4.0, 0.9999, 0.0),
(4.0, 1.0001, b),
(3.0001, 2.0, 0.0),
(0.9999, 2.0, b),
(0.0, 1.0001, 0.0),
],
),
("_F 1", &[(0.0, 1.0, b), (1.0, 0.0, 0.0), (3.0, 0.0, b), (4.0, 1.0, 0.0), (4.0, 1.0, b), (3.0, 2.0, 0.0), (1.0, 2.0, b), (0.0, 1.0, 0.0)]),
(
"_C 1 1",
&[(0.0, 1.0, 0.0), (1.0, 0.0, 0.0), (3.0, 0.0, 0.0), (4.0, 1.0, 0.0), (4.0, 1.0, 0.0), (3.0, 2.0, 0.0), (1.0, 2.0, 0.0), (0.0, 1.0, 0.0)],
),
(
"_C 1.2 0.8",
&[(0.0, 1.2, 0.0), (0.8, 0.0, 0.0), (2.8, 0.0, 0.0), (4.0, 0.8, 0.0), (4.0, 0.8, 0.0), (3.2, 2.0, 0.0), (1.2, 2.0, 0.0), (0.0, 1.2, 0.0)],
),
];
let square =
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 2.0, 0.0), (4.0, 2.0, 0.0), (0.0, 2.0, 0.0), (0.0, 2.0, 0.0)];
let over: [(&str, &[(f64, f64, f64)]); 2] = [("_F 1.0001", &square), ("_C 1.2 0.81", &square)];
for (corners, want) in fit.into_iter().chain(over) {
let mut s = Session::new();
s.cmdline(&format!("rectang {corners} 0,0 4,2")).unwrap();
let EntityKind::LwPolyline(p) = last(&s) else { panic!("no polyline") };
let got: Vec<(f64, f64, f64)> = p.vertices.iter().map(|v| (v.p.x, v.p.y, v.bulge)).collect();
let ok = got.len() == want.len()
&& got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-9 && (g.1 - w.1).abs() < 1e-9 && (g.2 - w.2).abs() < 1e-6);
assert!(ok, "{corners}: {got:?}");
}
}
#[test]
fn rectang_area_with_corners_too_large_stays_exact() {
let check = |s: &Session| {
let pts = rect_pts(s);
let b = cadcraft_geom::Bounds2::from_points(pts.clone());
assert!(near(b.min, 0.0, 0.0) && near(b.max, 4.0, 1.0), "{pts:?}");
assert!(pts.len() == 8 && pts.chunks(2).all(|c| c[0] == c[1]), "{pts:?}");
};
let mut s = Session::new();
s.cmdline("rectang _F 2 0,0 _A 4 _L 4").unwrap();
check(&s);
s.execute("rectang", &json!({"p1": [0, 0], "area": 4, "length": 4, "fillet": 2})).unwrap();
check(&s);
}
/// Guards the JSON `center: true` form for every sizing route: a picked corner mirrored about
/// the centre, full-size `dimensions`, full `area`, rotation about the centre, that the default
/// corner mode is untouched, and that centre mode without a size is rejected.
@@ -1136,7 +1379,7 @@ fn rectang_center_mode_json() {
}
/// Guards that fillet, chamfer, width and thickness still apply in centre mode, and that an
/// oversized fillet falls back to sharp corners without moving the rectangle off centre.
/// oversized fillet leaves sharp corners without moving the rectangle off centre.
#[test]
fn rectang_center_mode_honours_options() {
let mut s = Session::new();
@@ -1153,9 +1396,11 @@ fn rectang_center_mode_honours_options() {
assert_eq!(rect_pts(&s).len(), 8);
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
// A fillet too large for the rectangle falls back to sharp corners, still centred.
// A fillet too large for the rectangle leaves sharp corners, each one two coincident vertices
// as in AutoCAD, still centred.
s.execute("rectang", &json!({"center": true, "p1": [10, 10], "p2": [14, 16], "fillet": 5})).unwrap();
assert_eq!(rect_pts(&s).len(), 4);
let pts = rect_pts(&s);
assert!(pts.len() == 8 && pts.chunks(2).all(|c| c[0] == c[1]), "{pts:?}");
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
}
@@ -1183,8 +1428,9 @@ fn rectang_center_mode_command_line() {
assert!(s.running.is_none(), "{}", s.prompt_text());
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
// Area too: the rectangle of that area is centred on the first point.
s.cmdline("rectang ce 10,10 a 96 l 8").unwrap();
// Area too: the rectangle of that area is centred on the first point (without the fillet
// remembered from above, which would take its corners off the area).
s.cmdline("rectang f 0 ce 10,10 a 96 l 8").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
+39 -17
View File
@@ -63,19 +63,11 @@ enum Order {
Under,
}
/// Move `hs` in the current space's draw order, keeping their order among themselves. Above and
/// Under place them right over the topmost reference object or right under the lowest one.
/// Returns how many objects moved.
fn reorder(s: &mut Session, hs: &[Handle], order: Order, refs: &[Handle]) -> Result<usize> {
let space = s.space();
let d = s.doc_mut()?;
let Some(st) = d.space_mut(&space) else { return Ok(0) };
fn reorder_store(st: &mut cadcraft_doc::EntityStore, hs: &[Handle], order: Order) -> usize {
let index: HashMap<Handle, usize> = st.handles().into_iter().enumerate().map(|(i, h)| (h, i)).collect();
let mut moving: Vec<(usize, Handle)> = hs.iter().filter_map(|h| index.get(h).map(|i| (*i, *h))).collect();
moving.sort_unstable();
moving.dedup();
let set: HashSet<Handle> = moving.iter().map(|m| m.1).collect();
let refs: Vec<(usize, Handle)> = refs.iter().filter(|h| !set.contains(h)).filter_map(|h| index.get(h).map(|i| (*i, *h))).collect();
match order {
Order::Front => {
for (_, h) in &moving {
@@ -87,6 +79,29 @@ fn reorder(s: &mut Session, hs: &[Handle], order: Order, refs: &[Handle]) -> Res
st.send_to_back(*h);
}
}
Order::Above | Order::Under => {}
}
moving.len()
}
/// Move `hs` in the current space's draw order, keeping their order among themselves. Above and
/// Under place them right over the topmost reference object or right under the lowest one.
/// Returns how many objects moved.
fn reorder(s: &mut Session, hs: &[Handle], order: Order, refs: &[Handle]) -> Result<usize> {
let space = s.space();
let d = s.doc_mut()?;
let Some(st) = d.space_mut(&space) else { return Ok(0) };
if matches!(order, Order::Front | Order::Back) {
return Ok(reorder_store(st, hs, order));
}
let index: HashMap<Handle, usize> = st.handles().into_iter().enumerate().map(|(i, h)| (h, i)).collect();
let mut moving: Vec<(usize, Handle)> = hs.iter().filter_map(|h| index.get(h).map(|i| (*i, *h))).collect();
moving.sort_unstable();
moving.dedup();
let set: HashSet<Handle> = moving.iter().map(|m| m.1).collect();
let refs: Vec<(usize, Handle)> = refs.iter().filter(|h| !set.contains(h)).filter_map(|h| index.get(h).map(|i| (*i, *h))).collect();
match order {
Order::Front | Order::Back => {}
Order::Above => {
let Some(&(_, mut cur)) = refs.iter().max() else { return Err(EngineError::Other("no reference objects".into())) };
for (_, h) in &moving {
@@ -181,15 +196,23 @@ impl Annot {
}
}
/// Every object of the current space that `keep` accepts, in draw order.
fn of_kind(s: &Session, keep: impl Fn(&EntityKind) -> bool) -> Result<Vec<Handle>> {
let d = s.doc()?;
Ok(d.space(&s.space()).map(|st| st.iter().filter(|e| keep(&e.kind)).map(|e| e.handle).collect()).unwrap_or_default())
/// Reorder objects across all spaces (model space and all paper space layouts).
fn reorder_all_spaces(s: &mut Session, order: Order, keep: impl Fn(&EntityKind) -> bool) -> Result<usize> {
let d = s.doc_mut()?;
let mut total = 0;
// Model space
let hs: Vec<Handle> = d.model.iter().filter(|e| keep(&e.kind)).map(|e| e.handle).collect();
total += reorder_store(&mut d.model, &hs, order);
// All paper space layouts
for layout in &mut d.layouts {
let hs: Vec<Handle> = layout.entities.iter().filter(|e| keep(&e.kind)).map(|e| e.handle).collect();
total += reorder_store(&mut layout.entities, &hs, order);
}
Ok(total)
}
fn annotations_to_front(s: &mut Session, which: Annot) -> Result<Value> {
let hs = of_kind(s, |k| which.matches(k))?;
let n = reorder(s, &hs, Order::Front, &[])?;
let n = reorder_all_spaces(s, Order::Front, |k| which.matches(k))?;
Ok(json!({ "moved": n, "message": format!("{n} object(s) brought to front.") }))
}
@@ -208,8 +231,7 @@ fn run_texttofront(s: &mut Session, p: &Value) -> Result<Value> {
}
fn run_hatchtoback(s: &mut Session, _p: &Value) -> Result<Value> {
let hs = of_kind(s, |k| matches!(k, EntityKind::Hatch(_)))?;
let n = reorder(s, &hs, Order::Back, &[])?;
let n = reorder_all_spaces(s, Order::Back, |k| matches!(k, EntityKind::Hatch(_)))?;
Ok(json!({ "moved": n, "message": format!("{n} hatch object(s) sent to back.") }))
}
+17 -4
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}")
.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}")
.noundo(),
CommandSpec::new("preview", "Plot Preview", run_preview)
.menu(&["File", "Plot Preview"])
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("pdfbook", "Sheet Books to PDF...", run_pdfbook)
.menu(&["File", "Sheet Books to PDF..."])
.alias(&["printpdf", "pdfb"])
.params("{path?: \"DIR/NAME^NAME2.pdf\" (default: the drawing's file; a `^` splits the name into one book name per row of frames; else returns base64 `data` per book), names?: [book names], frameHeight?: mm (default 297), unit?: mm per drawing unit (default 1)} → {books: [{name, pages, bytes, path? | data}], skipped}: closed polylines of the frame height in model space are sheet frames; each row (same lower edge, bottom to top) is one PDF, its frames left to right one page each on the paper (ISO A-series, either orientation) they match")
.params("{path?: \"DIR/NAME^NAME2.pdf\" (default: the drawing's file; a `^` splits the name into one book name per row of frames; else returns base64 `data` per book), names?: [book names], frameHeight?: mm (default 297), unit?: mm per drawing unit (default 1)} → {books: [{name, pages, bytes, path? | data}], skipped}: closed polylines of the frame height in model space are sheet frames; each row (same lower edge, bottom to top) is one PDF, its frames left to right one page each on the paper (any standard size — ISO, JIS, ANSI — either orientation) they match")
.noundo(),
CommandSpec::new("attach", "Attach", |s, p| match str_param(p, "path").map(extension) {
Some(e) if super::image::is_image_ext(&e) => super::image::run_imageattach(s, p),
@@ -123,7 +123,7 @@ 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 = (hooks.write)(s.doc()?, &file).map_err(|e| bad("export", e))?;
let (bytes, notes) = 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) => {
@@ -134,6 +134,7 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
};
super::file::report_new_folder(s, &mut r, folder);
super::file::report_loss(s, &mut r, &file);
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
@@ -572,7 +573,8 @@ struct Frame {
landscape: bool,
}
/// The ISO/ANSI paper a frame of `w` x `h` mm fits (either orientation), and whether it is landscape.
/// The standard paper (ISO, JIS or ANSI) a frame of `w` x `h` mm fits (either orientation), and whether
/// it is landscape.
fn paper_for(w: f64, h: f64) -> Option<(&'static str, bool)> {
cadcraft_render::PAPER_SIZES.iter().find_map(|p| {
let (pw, ph) = (p.width_mm, p.height_mm);
@@ -877,6 +879,17 @@ mod tests {
let r = s.execute("preview", &json!({ "layout": "layout1", "paper": "A4", "landscape": true, "width": 600 })).unwrap();
assert_eq!((r["layout"].as_str(), r["width"].as_u64(), r["height"].as_u64()), (Some("Layout1"), Some(600), Some(424)));
assert_eq!(r["paper"], "ISO A4 (210.00 x 297.00 MM)");
// The bare B5 is the ISO size it always was; the JIS sheet needs its explicit name, and the
// Japanese postcards resolve by their names and their Japanese spelling.
let r = s.execute("preview", &json!({ "layout": "layout1", "paper": "B5", "landscape": false, "width": 400 })).unwrap();
assert_eq!(r["paper"], "ISO B5 (176.00 x 250.00 MM)");
assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(400), Some(568)));
let r = s.execute("preview", &json!({ "layout": "layout1", "paper": "B5 (JIS)", "landscape": false, "width": 400 })).unwrap();
assert_eq!(r["paper"], "JIS B5 (182.00 x 257.00 MM)");
assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(400), Some(565)));
let r = s.execute("preview", &json!({ "layout": "layout1", "paper": "はがき", "landscape": false, "width": 200 })).unwrap();
assert_eq!(r["paper"], "Japanese Postcard (100.00 x 148.00 MM)");
assert_eq!(r["height"], 296);
assert!(s.execute("preview", &json!({ "layout": "Nope" })).is_err());
assert!(s.execute("preview", &json!({ "paper": "Nope" })).is_err());
for p in [json!({ "scale": -1, "fit": false }), json!({ "scale": 1e-300, "fit": false }), json!({ "width": -5 }), json!({ "width": 1e30 })] {
+167 -21
View File
@@ -49,6 +49,47 @@ pub fn io() -> Option<&'static IoHooks> {
IO.get()
}
/// [`IoHooks::write`] and [`IoHooks::plot`] that also return what an image (PNG, SVG, PDF) draws
/// short of the drawing because of a render limit, one note each, such as dashed lines drawn
/// continuous past the dash limit (installed by the app with the image writers, a lower layer;
/// see `cadcraft_io::write_framed_noted` and `cadcraft_io::plotter::plot_noted`). EXPORT, QSAVE
/// and SAVEAS to an image, `document.bytes` and PLOT (so PUBLISH and PDFBOOK, sheet by sheet)
/// report them; without the hooks they write through [`IoHooks`] with no such notes. The app
/// installs the same writers as its [`IoHooks`].
pub struct NotedIo {
pub write: fn(&Drawing, &str) -> std::result::Result<(Vec<u8>, Vec<String>), String>,
pub plot: fn(&Drawing, &cadcraft_doc::Space, &Value) -> std::result::Result<(Vec<u8>, Vec<String>), String>,
}
static NOTED_IO: OnceLock<NotedIo> = OnceLock::new();
pub fn set_noted_io(h: NotedIo) {
let _ = NOTED_IO.set(h);
}
/// `d` written as `name` with the image's notes ([`NotedIo::write`]), or through `hooks.write`
/// with none when the app installed no [`NotedIo`].
pub(crate) fn write_noted(hooks: &IoHooks, d: &Drawing, name: &str) -> std::result::Result<(Vec<u8>, Vec<String>), String> {
match NOTED_IO.get() {
Some(n) => (n.write)(d, name),
None => (hooks.write)(d, name).map(|bytes| (bytes, Vec::new())),
}
}
/// `d` plotted with the plot's notes ([`NotedIo::plot`]), or through `hook` with none when the
/// app installed no [`NotedIo`].
pub(crate) fn plot_noted(
hook: PlotHook,
d: &Drawing,
space: &cadcraft_doc::Space,
opts: &Value,
) -> std::result::Result<(Vec<u8>, Vec<String>), String> {
match NOTED_IO.get() {
Some(n) => (n.plot)(d, space, opts),
None => hook(d, space, opts).map(|bytes| (bytes, Vec::new())),
}
}
/// An entity as DXF groups and back, for AutoLISP's `entget`, `entmake` and `entmod`
/// (installed by the app with the DXF reader and writer, a lower layer).
pub struct EntityCodec {
@@ -104,6 +145,46 @@ pub fn set_dwg_compat_lost(f: DwgCompatLost) {
let _ = DWG_COMPAT_LOST.set(f);
}
/// Notes on what a DWG keeps of a drawing only in part, such as a linetype with more dash
/// elements than a DWG can count (installed by the app with the DWG writer, a lower layer; see
/// `cadcraft_io::dwg_notes`).
pub type DwgNotes = fn(&Drawing) -> Vec<String>;
static DWG_NOTES: OnceLock<DwgNotes> = OnceLock::new();
pub fn set_dwg_notes(f: DwgNotes) {
let _ = DWG_NOTES.set(f);
}
/// The [`DwgNotes`] of `d`, the drawing a DWG save writes: none without the hook.
pub fn dwg_notes(d: &Drawing) -> Vec<String> {
DWG_NOTES.get().map(|f| f(d)).unwrap_or_default()
}
/// Say on the command line what the DWG just written keeps only in part (`notes`, from
/// [`dwg_notes`]), and list it in the result's `warnings`.
pub(crate) fn report_dwg_notes(s: &mut Session, r: &mut Value, notes: Vec<String>) {
report_notes(s, r, notes);
}
/// Say each of `notes` on the command line and add them to the result's `warnings`.
pub(crate) fn report_notes(s: &mut Session, r: &mut Value, notes: Vec<String>) {
if notes.is_empty() {
return;
}
for note in &notes {
s.echo(note.clone());
}
if let Some(o) = r.as_object_mut() {
match o.get_mut("warnings").and_then(Value::as_array_mut) {
Some(list) => list.extend(notes.into_iter().map(Value::String)),
None => {
o.insert("warnings".into(), json!(notes));
}
}
}
}
/// What a DXF of `version` leaves out of `d` for its proxies' string streams (#3229): empty from
/// 2007 on. `d` is written as committed (a reference edit's working copies are not in the file).
fn proxies_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
@@ -208,9 +289,10 @@ fn is_dxf(path: &str) -> bool {
Format::from_path(path) == Some(Format::Dxf)
}
/// The drawing written to `path` with `opts`: through [`IoHooks::write`] when no option is set,
/// else through the [`write_as`] hook.
fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<Vec<u8>> {
/// The drawing written to `path` with `opts`: an image, or a drawing file with no option set,
/// through [`IoHooks::write`] (with an image's notes, [`write_noted`]); a drawing file at a
/// chosen version or as binary DXF through the [`write_as`] hook.
fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(Vec<u8>, Vec<String>)> {
let hooks = io().ok_or_else(|| bad(cmd, "file formats are not available in this build"))?;
if opts.binary && !is_dxf(path) {
return Err(bad(cmd, "binary applies to DXF files only"));
@@ -219,11 +301,12 @@ fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<Vec<
let d: &cadcraft_doc::Drawing = if is_drawing_file(path) { s.state()?.drawing() } else { s.doc()? };
let copy = (opts.portable_fonts && is_drawing_file(path)).then(|| Drawing { portable_fonts: true, ..d.clone() });
let d = copy.as_ref().unwrap_or(d);
let r = if opts.version.is_none() && !opts.binary {
(hooks.write)(d, path)
// An image has no version: `write_as` would write the same bytes without the notes.
let r = if !is_drawing_file(path) || (opts.version.is_none() && !opts.binary) {
write_noted(hooks, d, path)
} else {
let w = write_as().ok_or_else(|| bad(cmd, "saving at a chosen version or as binary DXF is not available in this build"))?;
w(d, path, opts)
w(d, path, opts).map(|bytes| (bytes, Vec::new()))
};
r.map_err(|e| bad(cmd, e))
}
@@ -243,6 +326,10 @@ pub fn specs() -> Vec<CommandSpec> {
.params("{path} | {data: base64, name} → {index, entities?, warnings: what reading left out}")
.enabled(always)
.noundo(),
CommandSpec::new("whohas", "Who Has", run_whohas)
.params("{path?: a drawing file (default: the current drawing's)} → {path, holder: {user, host, instance, opened} | null}")
.enabled(always)
.noundo(),
CommandSpec::new("close", "Close", run_close).menu(&["File", "Close"]).key("Cmd+W").params("{index?}").noundo(),
CommandSpec::new("closeall", "Close All", run_closeall).menu(&["File", "Close All"]).enabled(always).noundo(),
CommandSpec::new("qsave", "Save", run_qsave_reporting).menu(&["File", "Save"]).key("Cmd+S").alias(&["save"]).params("{path?}").noundo(),
@@ -255,7 +342,7 @@ pub fn specs() -> Vec<CommandSpec> {
.noundo(),
CommandSpec::new("document.switch", "Switch Drawing", run_switch).params("{index}").enabled(always).noundo(),
CommandSpec::new("document.bytes", "Drawing as bytes", run_bytes)
.params("{format?: dxf, version?: 2000…2018, binary?: bool, portableFonts?: bool} → {data: base64}")
.params("{format?: dxf, version?: 2000…2018, binary?: bool, portableFonts?: bool} → {data: base64, warnings?: what an image draws short of the drawing}")
.noundo(),
CommandSpec::new("script", "Run Script...", run_script)
.menu(&["Tools", "Run Script..."])
@@ -469,6 +556,36 @@ fn run_open(s: &mut Session, p: &Value) -> Result<Value> {
Ok(opened(s, i, false))
}
/// WHOHAS: who has a drawing open, from its lock file ([`crate::drawlock`]): the current
/// drawing's, or the file `path`.
fn run_whohas(s: &mut Session, p: &Value) -> Result<Value> {
// Left out (or null): the current drawing's file; anything but text is an error, not the
// current drawing asked about by mistake.
let path = match p.get("path") {
None | Some(Value::Null) => s.state()?.path.clone().ok_or_else(|| bad("whohas", "the drawing has no file yet; pass `path`"))?,
Some(Value::String(path)) => path.clone(),
Some(_) => return Err(bad("whohas", "`path` must be a file path")),
};
// The web has no lock files to look at: an error, not "nobody has it open".
#[cfg(target_arch = "wasm32")]
{
let _ = path;
Err(bad("whohas", "drawing locks are not available on the web"))
}
#[cfg(not(target_arch = "wasm32"))]
{
// Under the automation roots, the lock beside a file outside them is not looked at.
crate::file_access::check_read(&path).map_err(|e| bad("whohas", e))?;
let holder = crate::drawlock::holder(std::path::Path::new(&path));
let msg = match &holder {
Some(h) => format!("{} is open by {}.", file_name(&path), h.describe()),
None => format!("Nobody has {} open (no current lock).", file_name(&path)),
};
s.echo(msg);
Ok(json!({ "path": path, "holder": holder }))
}
}
/// `close [index]`: cancel the running command, remove the drawing (default: active), keep the active index valid, and bump the document epoch; an unknown index is an error.
fn run_close(s: &mut Session, p: &Value) -> Result<Value> {
let i = p.get("index").and_then(Value::as_u64).map(|i| i as usize).unwrap_or(s.active);
@@ -499,18 +616,19 @@ fn run_closeall(s: &mut Session, _p: &Value) -> Result<Value> {
ok()
}
pub(crate) fn save_to(s: &mut Session, path: &str) -> Result<usize> {
pub(crate) fn save_to(s: &mut Session, path: &str) -> Result<(usize, Vec<String>)> {
let opts = SaveAs { binary: s.state()?.binary_dxf && is_dxf(path), ..SaveAs::default() };
save_as(s, "save", path, &opts)
}
/// Save to `path` with `opts`. A drawing file then keeps the version and binary choice: the
/// version goes into the drawing's `$ACADVER`, so later saves (QSAVE) write it again.
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<usize> {
/// version goes into the drawing's `$ACADVER`, so later saves (QSAVE) write it again. Also an
/// image's notes ([`write_noted`]).
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(usize, Vec<String>)> {
if s.doc()?.refedit.is_some() {
return Err(bad(cmd, "A block reference is being edited in place: finish with REFCLOSE (Save or Discard) before saving."));
}
let bytes = write_bytes(s, cmd, path, opts)?;
let (bytes, notes) = write_bytes(s, cmd, path, opts)?;
let n = commit_save(s, path, &bytes, store)?;
if is_drawing_file(path) {
let st = s.state_mut()?;
@@ -522,7 +640,7 @@ fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<usiz
st.saved = st.drawing().clone();
}
}
Ok(n)
Ok((n, notes))
}
/// Put saved bytes where the user gets them: natively the file at `path`; on the web, which has
@@ -735,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)?;
@@ -749,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
@@ -775,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
@@ -812,15 +932,18 @@ fn run_save(s: &mut Session, p: &Value) -> Result<Value> {
Some(p) => p.to_string(),
None => s.state()?.path.clone().ok_or_else(|| bad("qsave", "drawing has no file name yet; use saveas {path}"))?,
};
let n = save_to(s, &path)?;
Ok(saved(&path, n))
let (n, notes) = save_to(s, &path)?;
let mut r = saved(&path, n);
report_notes(s, &mut r, notes);
Ok(r)
}
fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("saveas", "`path` is required"))?.to_string();
let opts = save_options("saveas", p)?;
let n = save_as(s, "saveas", &path, &opts)?;
let (n, notes) = save_as(s, "saveas", &path, &opts)?;
let mut r = saved(&path, n);
report_notes(s, &mut r, notes);
if is_drawing_file(&path) {
r["version"] = json!(opts.version.unwrap_or_else(|| drawing_version(s, &path)).year());
r["binary"] = json!(opts.binary);
@@ -869,10 +992,13 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
let opts = save_options("document.bytes", p)?;
let version = opts.version.unwrap_or_else(|| drawing_version(s, &format!("drawing.{fmt}")));
let lost = not_saved_as(s.doc()?, version);
let bytes = write_bytes(s, "document.bytes", &format!("drawing.{fmt}"), &opts)?;
let (bytes, notes) = write_bytes(s, "document.bytes", &format!("drawing.{fmt}"), &opts)?;
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len() });
report_notes(s, &mut r, notes);
if drops_unknown(format!("drawing.{fmt}")) {
report_not_saved(s, &mut r, &lost);
let notes = s.state().map(|st| dwg_notes(st.drawing())).unwrap_or_default();
report_dwg_notes(s, &mut r, notes);
} else if is_dxf_file(format!("drawing.{fmt}")) {
let lost = host_dxf_lost(s, version);
report_lost(s, &mut r, "drawing.dxf", version, &lost);
@@ -1005,7 +1131,9 @@ pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
let Ok(d) = s.doc() else { return };
let version = own_version(d, path);
let lost = lost_writing(d, path, version);
let notes = if drops_unknown(path) { dwg_notes(d) } else { Vec::new() };
report_lost(s, r, path, version, &lost);
report_dwg_notes(s, r, notes);
}
/// Say on the command line what the file `path`, written at `version`, couldn't keep (`lost`),
@@ -1112,6 +1240,8 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R
report_new_folder(s, &mut r, folder);
if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) {
report_not_saved(s, &mut r, &lost);
let notes = s.state().map(|st| dwg_notes(st.drawing())).unwrap_or_default();
report_dwg_notes(s, &mut r, notes);
} else if r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) {
let lost = host_dxf_lost(s, version);
report_lost(s, &mut r, "drawing.dxf", version, &lost);
@@ -1179,6 +1309,22 @@ mod tests {
use crate::Session;
use crate::temp_dir::TempDir;
/// Notes join the warnings a result already has instead of replacing them, and are said on
/// the command line.
#[test]
fn notes_are_added_to_the_warnings_a_result_has() {
let mut s = Session::new();
let mut r = json!({ "warnings": ["kept"] });
super::report_notes(&mut s, &mut r, vec!["added".into()]);
assert_eq!(r["warnings"], json!(["kept", "added"]));
let mut r = json!({});
super::report_notes(&mut s, &mut r, Vec::new());
assert!(r.get("warnings").is_none());
super::report_notes(&mut s, &mut r, vec!["first".into()]);
assert_eq!(r["warnings"], json!(["first"]));
assert!(s.log.ends_with(&["added".to_string(), "first".to_string()]), "{:?}", s.log);
}
/// Whether the `.bak` name is taken is asked without following a link there: a dangling link
/// counts as taken, so a file that doesn't look like a drawing leaves it alone.
#[cfg(unix)]
+2 -8
View File
@@ -455,15 +455,9 @@ fn tinted_dim_style(d: &mut Drawing, name: &str, color: Color, tinted: &mut Tint
if let Some(n) = tinted.names.get(&key) {
return Some(n.clone());
}
let st = d.dim_styles.iter().find(|s| s.name.eq_ignore_ascii_case(name))?.clone();
let st = d.dim_style(name)?.clone();
let base = format!("COMPARE_{}_{}", tag(color), st.name);
let new = tinted.next.find(
"dimension style",
&base,
d.dim_styles.len(),
|i| suffixed(&base, i),
|n| d.dim_styles.iter().any(|s| s.name.eq_ignore_ascii_case(n)),
);
let new = tinted.next.find("dimension style", &base, d.dim_styles.len(), |i| suffixed(&base, i), |n| d.dim_style(n).is_some());
d.dim_styles.push(DimStyle {
name: new.clone(),
dim_line_color: Color::ByBlock,
+94 -6
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,15 +337,18 @@ 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)?;
let m = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) {
Some(f) if f > 0.0 => Mat3::scale_about(base, f),
// 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 => {
mode_matrix(GripMode::Scale, base, point_req("grip.scale", p, "to")?).ok_or_else(|| bad("grip.scale", "scale factor would be zero"))?
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")) }
}
};
apply(s, &hs, &m, 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<_>>() }))
}
fn run_grip_mirror(s: &mut Session, p: &Value) -> Result<Value> {
+54 -23
View File
@@ -9,12 +9,12 @@
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;
use super::machines::number;
use super::modify::transform_entities;
use super::modify::{at_elevation, scale_entities, transform_entities};
use crate::grips::{GripAction, GripMode, grip_action, grip_actions, mode_matrix};
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Running, Session, Step};
@@ -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) {
@@ -220,14 +223,7 @@ impl GripEdit {
}
}
/// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes).
fn edit(&mut self, s: &mut Session, to: Vec2, m: Option<Mat3>) -> Result<Step> {
let before = s.state()?.doc.clone();
let changed = match (self.mode, m) {
(GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(),
(_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(),
(_, None) => return Err(other("Invalid point.")),
};
fn finish_edit(&mut self, before: Arc<Drawing>, changed: bool) -> Result<Step> {
if !changed {
return Err(other("The objects can't be edited that way (locked, or the result would be degenerate)."));
}
@@ -240,6 +236,33 @@ impl GripEdit {
}
}
/// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes).
fn edit(&mut self, s: &mut Session, to: Vec2, m: Option<Mat3>) -> Result<Step> {
let before = s.state()?.doc.clone();
let changed = match (self.mode, m) {
(GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(),
(_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(),
(_, None) => return Err(other("Invalid point.")),
};
self.finish_edit(before, changed)
}
/// Scale `targets` uniformly about `base` in 3D, scaling text heights, elevations and thickness.
fn edit_scale(&mut self, s: &mut Session, f: f64) -> Result<Step> {
if !f.is_finite() || f <= 1e-12 {
return Err(other("Invalid point."));
}
let before = s.state()?.doc.clone();
// 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)
}
fn mode_input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Keyword(k) => match k.as_str() {
@@ -285,13 +308,13 @@ impl GripEdit {
s.echo(self.label());
Ok(Step::Continue)
}
Input::Point(p) => {
let m = self.matrix(p);
self.edit(s, p, m)
}
Input::Deferred(d) => {
let m = self.matrix(d.at);
self.edit(s, d.at, m)
Input::Point(p) | Input::Deferred(crate::snap::Deferred { at: p, .. }) => {
if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(p))
} else {
let m = self.matrix(p);
self.edit(s, p, m)
}
}
Input::Text(t) => match self.mode {
GripMode::Rotate => {
@@ -300,7 +323,7 @@ impl GripEdit {
}
GripMode::Scale => {
let f = positive(number(&t))?;
self.edit(s, self.base, Some(Mat3::scale_about(self.base, f)))
self.edit_scale(s, f)
}
_ => Err(other("Requires a point or an option keyword.")),
},
@@ -327,14 +350,21 @@ impl GripEdit {
(Ask::RefFirst, Input::Text(t)) => self.ask = Ask::RefNew(value(&t)?),
(Ask::RefFirst, Input::Enter) => self.ask = Ask::RefNew(if rotate { 0.0 } else { 1.0 }),
(Ask::RefSecond(a), Input::Point(p)) => self.ask = Ask::RefNew(between(a, p)?),
(Ask::RefNew(_), Input::Point(p)) => {
let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?;
return self.edit(s, p, Some(m));
(Ask::RefNew(r), Input::Point(p)) => {
if rotate {
let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?;
return self.edit(s, p, Some(m));
}
let f = positive(Some(self.base.dist(p) / r))?;
return self.edit_scale(s, f);
}
(Ask::RefNew(r), Input::Text(t)) => {
let v = value(&t)?;
let m = if rotate { Mat3::rotate_about(self.base, v - r) } else { Mat3::scale_about(self.base, positive(Some(v / r))?) };
return self.edit(s, self.base, Some(m));
if rotate {
return self.edit(s, self.base, Some(Mat3::rotate_about(self.base, v - r)));
}
let f = positive(Some(v / r))?;
return self.edit_scale(s, f);
}
(_, Input::Enter) => self.ask = Ask::Mode,
_ => {}
@@ -429,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)
}
+29
View File
@@ -71,6 +71,35 @@ fn next_unnamed(d: &Drawing) -> String {
(1..=d.groups.len() + 1).map(|n| format!("*A{n}")).find(|n| !used.contains(n)).unwrap_or_else(|| format!("*A{}", d.groups.len() + 1))
}
/// When entities are copied, replicate any whole groups whose members were all copied.
pub(crate) fn replicate_groups_from(d: &mut Drawing, src_groups: &[Group], copies: &[(Handle, Handle)]) {
if copies.is_empty() || src_groups.is_empty() {
return;
}
let map: std::collections::HashMap<Handle, Handle> = copies.iter().copied().collect();
let mut new_groups = Vec::new();
for g in src_groups {
let active_members: Vec<Handle> = g.members.iter().copied().filter(|h| d.entity(*h).is_some()).collect();
if !active_members.is_empty() && active_members.iter().all(|h| map.contains_key(h)) {
let new_members: Vec<Handle> = active_members.iter().filter_map(|h| map.get(h).copied()).collect();
new_groups.push((g.description.clone(), g.selectable, new_members));
}
}
for (desc, selectable, members) in new_groups {
if d.groups.len() >= MAX_GROUPS {
break;
}
let name = next_unnamed(d);
d.groups.push(Group { name, description: desc, selectable, members });
}
}
/// When entities in the drawing `d` are copied, replicate any whole groups among them.
pub(crate) fn replicate_groups_for_copies(d: &mut Drawing, copies: &[(Handle, Handle)]) {
let groups = d.groups.clone();
replicate_groups_from(d, &groups, copies);
}
/// `hs` without repeats and without handles of objects that don't exist.
fn existing(d: &Drawing, hs: &[Handle]) -> Vec<Handle> {
let mut seen = std::collections::HashSet::new();
+450 -32
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};
@@ -17,6 +18,7 @@ use super::{CommandSpec, bad, bool_or, f64_or, point_param, points_param, size_p
use crate::{Accept, EngineError, Input, Interactive, Picker, Prompt, Result, Session, Step};
mod arcs;
mod assoc;
pub(crate) use assoc::detach;
mod edit;
@@ -25,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"])
@@ -54,13 +70,15 @@ pub(super) fn outline_tol(ext: Bounds2) -> f64 {
}
/// Tessellated outlines of every visible curve in the space (hatch boundary candidates), each
/// with the handle of the object it came from.
fn outlines(d: &Drawing, space: &Space, near: Option<Bounds2>) -> (Vec<Vec<Vec2>>, Vec<Handle>) {
let Some(store) = d.space(space) else { return (Vec::new(), Vec::new()) };
/// with the handle of the object it came from and its exact piece ([`arcs::pieces_of`]), and
/// the flattening tolerance.
fn outlines(d: &Drawing, space: &Space, near: Option<Bounds2>) -> (Vec<Vec<Vec2>>, Vec<Handle>, Vec<Option<arcs::Piece>>, f64) {
let ext = d.extents(space);
let tol = outline_tol(ext);
let Some(store) = d.space(space) else { return (Vec::new(), Vec::new(), Vec::new(), tol) };
let mut out = Vec::new();
let mut owners = Vec::new();
let mut pieces = Vec::new();
for e in store.iter() {
if !d.is_visible(e) || matches!(e.kind, EntityKind::Hatch(_) | EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_)) {
continue;
@@ -73,9 +91,10 @@ fn outlines(d: &Drawing, space: &Space, near: Option<Bounds2>) -> (Vec<Vec<Vec2>
}
let polys = object_polys(d, e, tol, ext);
owners.extend(std::iter::repeat_n(e.handle, polys.len()));
pieces.extend(arcs::pieces_of(e, polys.len()));
out.extend(polys);
}
(out, owners)
(out, owners, pieces, tol)
}
/// An object's outline as polylines (tolerance `tol`), infinite lines clipped to a generous
@@ -193,7 +212,7 @@ impl OriginMode {
}
/// The origin for loops: `current` when the mode keeps it.
pub(crate) fn origin(self, loops: &[HatchLoop], current: Vec2) -> Vec2 {
let b = Bounds2::from_points(loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p)).filter(|p| p.is_finite()));
let b = loops_bounds(loops);
if b.is_empty() {
return current;
}
@@ -208,6 +227,25 @@ impl OriginMode {
}
}
/// The extents of hatch loops with their arcs: a bulged edge reaches past its vertices (a circle
/// kept as two half-circle vertices spans its whole height).
fn loops_bounds(loops: &[HatchLoop]) -> Bounds2 {
let mut b = Bounds2::from_points(loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p)).filter(|p| p.is_finite()));
for l in loops {
let vs = &l.vertices;
for (i, v) in vs.iter().enumerate() {
let Some(next) = vs.get((i + 1) % vs.len()) else { continue };
if let Some((arc, _)) = cadcraft_geom::bulge_to_arc(v.p, next.p, v.bulge) {
let ab = arc.bounds();
if ab.min.is_finite() && ab.max.is_finite() {
b = b.union(&ab);
}
}
}
}
b
}
/// Island detection style by name (HPISLANDDETECTION 0 normal, 1 outer, 2 ignore).
pub(crate) fn island_style(t: &str) -> Option<u8> {
match t.trim().to_ascii_lowercase().as_str() {
@@ -224,15 +262,17 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
let space = s.space();
let ext = d.extents(&space);
let tol = ((ext.width() + ext.height()) * 1e-9).max(1e-9);
let (polys, owners) = outlines(d, &space, None);
let (polys, owners, pieces, ftol) = outlines(d, &space, None);
// A line that ends on a flattened curve (an ellipse) can stop short of its chords.
let polys = cadcraft_geom::region::snap_ends(&polys, outline_tol(ext), tol);
let polys = cadcraft_geom::region::snap_ends(&polys, ftol, tol);
let found = cadcraft_geom::region::boundary_at_gap(&polys, p, tol, gap_tolerance(d))
.ok_or_else(|| EngineError::Other("Valid hatch boundary not found.".into()))?;
let outer = found.outer;
let ob = Bounds2::from_points(outer.iter().copied());
let sources = handles_of(&owners, &found.outer_sources);
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, boundary_flags: None, sources }];
// The traced outline is flattened: circular runs become arcs again (#1167).
let mut loops =
vec![HatchLoop { vertices: arcs::with_arcs(&outer, &found.outer_edges, &pieces, ftol), outer: true, boundary_flags: None, sources }];
// Islands: closed objects entirely inside the outer loop that don't contain the pick point.
if let Some(store) = d.space(&space) {
for e in store.iter() {
@@ -261,7 +301,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
if open_curves {
let sources = handles_of(&owners, &island.sources);
loops.push(HatchLoop {
vertices: island.outline.into_iter().map(PolyVertex::new).collect(),
vertices: arcs::with_arcs(&island.outline, &island.edges, &pieces, ftol),
outer: false,
boundary_flags: None,
sources,
@@ -274,7 +314,9 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
pub(crate) fn loops_from_handles(s: &Session, hs: &[Handle]) -> Result<Vec<HatchLoop>> {
let d = s.doc()?;
let mut loops = Vec::new();
for h in hs {
let mut seen = std::collections::HashSet::new();
// An object selected twice is one boundary.
for h in hs.iter().filter(|h| seen.insert(**h)) {
if let Some(vs) = d.entity(*h).and_then(|e| closed_loop(d, e)) {
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), boundary_flags: None, sources: vec![*h] });
}
@@ -300,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.
@@ -325,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)),
@@ -352,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) },
})
}
}
@@ -429,17 +482,18 @@ fn same_loop(a: &HatchLoop, b: &HatchLoop) -> bool {
})
}
/// Deduplicate boundary loops that describe the same boundary.
/// Deduplicate boundary loops that describe the same boundary in the same role. A loop that is
/// one pick's outer loop and another's island (a pick inside a circle and one around it) stays
/// twice: merged, the island would be gone and the even-odd fill would leave the circle empty.
fn dedup_loops(loops: &mut Vec<HatchLoop>) {
let mut unique: Vec<HatchLoop> = Vec::with_capacity(loops.len());
for l in loops.drain(..) {
if let Some(existing) = unique.iter_mut().find(|u| same_loop(u, &l)) {
if let Some(existing) = unique.iter_mut().find(|u| u.outer == l.outer && same_loop(u, &l)) {
for s in l.sources {
if !existing.sources.contains(&s) {
existing.sources.push(s);
}
}
existing.outer = existing.outer || l.outer;
} else {
unique.push(l);
}
@@ -554,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> {
@@ -571,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>>,
@@ -588,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,
@@ -620,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(", ")));
@@ -635,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,
@@ -660,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,
@@ -687,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 {
@@ -696,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 => {}
@@ -786,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" => {
@@ -854,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();
@@ -963,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();
+147
View File
@@ -0,0 +1,147 @@
//! Exact arcs in traced hatch boundaries (#1167).
//!
//! The boundary search works on flattened curves, so a loop traced around an internal point
//! comes out as chords: a hatch in a circle had 158 straight edges and the wrong area. Each
//! traced edge knows the input polyline it lies on, and each input polyline is one piece of one
//! object (a line, a circle, an arc or one segment of a polyline), so nothing is guessed from
//! nearby geometry: a run of edges on the same circular piece becomes one bulged vertex again,
//! and the corners move onto the exact curves (where a line or another circle crosses).
use cadcraft_doc::{Entity, EntityKind, Prim};
use cadcraft_geom::{Circle, Line, PolyVertex, Segment, Vec2, arc_to_bulge, circle_circle, line_circle, shoelace};
/// The exact curve behind one input polyline.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Piece {
Line(Line),
Circle(Circle),
}
/// The exact piece behind each of `e`'s `n` outline polylines (one per primitive, in order, as
/// `select::hit_polylines` makes them), or `None` for each when `e` isn't made of lines and
/// circular arcs or the count doesn't match.
pub(crate) fn pieces_of(e: &Entity, n: usize) -> Vec<Option<Piece>> {
if !matches!(e.kind, EntityKind::Line(_) | EntityKind::Arc(_) | EntityKind::Circle(_) | EntityKind::LwPolyline(_)) {
return vec![None; n];
}
let prims = e.kind.prims();
if prims.len() != n {
return vec![None; n];
}
prims
.iter()
.map(|p| match p {
Prim::Seg(Segment::Line(l)) => Some(Piece::Line(*l)),
Prim::Seg(Segment::Arc { arc, .. }) => Some(Piece::Circle(Circle::new(arc.center, arc.radius))),
Prim::Circle(c) => Some(Piece::Circle(*c)),
_ => None,
})
.collect()
}
fn same_circle(a: &Circle, b: &Circle) -> bool {
a.center == b.center && a.radius == b.radius
}
/// The loop `pts` (edge `i` from `pts[i]` to the next vertex, closed) with its circular runs
/// as bulged vertices. `edges` names each edge's input polyline, `pieces` each polyline's exact
/// curve; `tol` is the flattening tolerance the polylines were made with. Anything that doesn't
/// check out stays as traced.
pub(crate) fn with_arcs(pts: &[Vec2], edges: &[Option<usize>], pieces: &[Option<Piece>], tol: f64) -> Vec<PolyVertex> {
let n = pts.len();
let plain = || pts.iter().map(|p| PolyVertex::new(*p)).collect::<Vec<_>>();
if n < 3 || edges.len() != n || !(tol.is_finite() && tol > 0.0) || pts.iter().any(|p| !p.is_finite()) {
return plain();
}
let at = |i: usize| pts.get(i % n).copied().unwrap_or_default();
let piece = |i: usize| edges.get(i % n).copied().flatten().and_then(|k| pieces.get(k).copied().flatten());
// A chord of a curve flattened to `tol` stays within `tol` of it; corners split where two
// chords cross may be a little further.
let slack = tol * 4.0;
let near_circle = |c: &Circle, q: Vec2| (c.center.dist(q) - c.radius).abs() <= slack;
// The circle each edge lies on: its piece is a circle and both ends and the middle are on
// it (the middle, so a long chord across the circle doesn't pass for an arc).
let circ: Vec<Option<(usize, Circle)>> = (0..n)
.map(|i| {
let k = edges.get(i).copied().flatten()?;
let Some(Piece::Circle(c)) = piece(i) else { return None };
let (a, b) = (at(i), at(i + 1));
(c.radius.is_finite() && c.radius > slack && near_circle(&c, a) && near_circle(&c, b) && near_circle(&c, a.mid(b))).then_some((k, c))
})
.collect();
let key = |i: usize| circ.get(i % n).copied().flatten().map(|(k, _)| k);
if circ.iter().all(Option::is_none) {
return plain();
}
let ccw = shoelace(pts) > 0.0;
// One whole circle: two half circles, as a hatch made by selecting the circle has.
if let Some(Some((k0, c))) = circ.first().copied()
&& (0..n).all(|i| key(i) == Some(k0))
{
let b = if ccw { 1.0 } else { -1.0 };
return vec![PolyVertex::with_bulge(c.center - Vec2::X * c.radius, b), PolyVertex::with_bulge(c.center + Vec2::X * c.radius, b)];
}
let line_of = |i: usize| match piece(i) {
Some(Piece::Line(l)) if l.a != l.b && [at(i), at(i + 1)].iter().all(|q| ((*q - l.a).cross(l.b - l.a) / l.a.dist(l.b)).abs() <= slack) => {
Some(l)
}
_ => None,
};
let onto = |c: &Circle, q: Vec2| {
let d = q - c.center;
if d.len() > 0.0 { c.center + d.normalized() * c.radius } else { q }
};
// Vertex `i` (between edges `i - 1` and `i`) on the exact curves: where the two pieces
// cross, nearest the traced corner, or else moved onto the circle it is on.
let corner = |i: usize| -> Vec2 {
let p = at(i);
let (prev, next) = (circ.get((i + n - 1) % n).copied().flatten(), circ.get(i % n).copied().flatten());
let crossings: Vec<Vec2> = match (prev, next) {
(Some((_, a)), Some((_, b))) if same_circle(&a, &b) => return onto(&a, p),
(Some((_, a)), Some((_, b))) => circle_circle(&a, &b),
(Some((_, c)), None) => line_of(i).map(|l| line_circle(&l, &c).into_iter().map(|x| x.0).collect()).unwrap_or_default(),
(None, Some((_, c))) => line_of(i + n - 1).map(|l| line_circle(&l, &c).into_iter().map(|x| x.0).collect()).unwrap_or_default(),
(None, None) => return p,
};
// Where two curves cross at a shallow angle, a corner off them by the flattening
// tolerance can be off along them by up to about √(2·r·tolerance): the crossing nearest
// the traced corner is taken within that reach, when no other crossing is as near.
let r = prev.or(next).map_or(0.0, |(_, c)| c.radius);
let reach = slack * 2.0 + (2.0 * r * slack).sqrt();
let mut xs: Vec<(f64, Vec2)> = crossings.into_iter().filter(|x| x.is_finite()).map(|x| (x.dist(p), x)).collect();
xs.sort_by(|a, b| a.0.total_cmp(&b.0));
match (xs.first(), xs.get(1)) {
(Some(&(d, x)), second) if d <= reach && second.is_none_or(|&(d2, _)| d2 > 2.0 * d + slack) => x,
_ => prev.or(next).map_or(p, |(_, c)| onto(&c, p)),
}
};
// Start where a run begins, so no run wraps past the end.
let Some(s) = (0..n).find(|&i| key(i) != key(i + n - 1)) else { return plain() };
let mut out = Vec::with_capacity(n);
let mut i = 0;
while i < n {
let e = (s + i) % n;
let p = corner(e);
let Some((k, c)) = circ.get(e).copied().flatten() else {
out.push(PolyVertex::new(p));
i += 1;
continue;
};
// The angle the run turns through about the centre, edge by edge.
let mut sweep = 0.0;
let mut a = p;
let mut j = i;
while j < n && key(s + j) == Some(k) {
let last = j + 1 >= n || key(s + j + 1) != Some(k);
let b = if last { corner(s + j + 1) } else { at(s + j + 1) };
let (u, v) = (a - c.center, b - c.center);
sweep += u.cross(v).atan2(u.dot(v));
a = b;
j += 1;
}
let bulge = arc_to_bulge(sweep);
out.push(PolyVertex::with_bulge(p, if bulge.is_finite() { bulge } else { 0.0 }));
i = j;
}
if out.len() < 2 { plain() } else { out }
}
+12 -5
View File
@@ -87,8 +87,14 @@ fn refill(before: &Drawing, after: &Drawing, l: &HatchLoop) -> Refill {
return Refill::Open;
}
let tol = super::outline_tol(nb);
let mut polys: Vec<Vec<Vec2>> = Vec::new();
let mut pieces = Vec::new();
for e in live.iter().filter_map(|h| after.entity(*h)) {
let ps = object_polys(after, e, tol, nb);
pieces.extend(super::arcs::pieces_of(e, ps.len()));
polys.extend(ps);
}
let snap = ((nb.width() + nb.height()) * 1e-9).max(1e-9);
let polys: Vec<Vec<Vec2>> = live.iter().filter_map(|h| after.entity(*h)).flat_map(|e| object_polys(after, e, tol, nb)).collect();
let polys = region::snap_ends(&polys, tol, snap);
let gap = gap_tolerance(after);
let found = if l.outer {
@@ -97,13 +103,14 @@ fn refill(before: &Drawing, after: &Drawing, l: &HatchLoop) -> Refill {
let ob = if ob.is_empty() { nb } else { ob };
let old = outline_of(&l.vertices, (ob.width() + ob.height()).max(1e-9) / 20000.0);
region::interior_point(&old)
.and_then(|q| region::enclosing_loop_gap(&polys, map_point(q, &ob, &nb), snap, gap))
.or_else(|| region::outline(&polys, snap, gap))
.and_then(|q| region::enclosing_loop_edges_gap(&polys, map_point(q, &ob, &nb), snap, gap))
.or_else(|| region::outline_edges(&polys, snap, gap))
} else {
region::outline(&polys, snap, gap)
region::outline_edges(&polys, snap, gap)
};
match found {
Some(pts) => Refill::Loop(pts.into_iter().map(PolyVertex::new).collect()),
// Traced again from flattened curves: circular runs become arcs again (#1167).
Some((pts, edges)) => Refill::Loop(super::arcs::with_arcs(&pts, &edges, &pieces, tol)),
None => Refill::Open,
}
}
+16 -2
View File
@@ -8,7 +8,7 @@ use cadcraft_geom::{Bounds2, Polyline, Vec2, point_in_polygon};
use serde_json::{Value, json};
use super::assoc::{detach, same_shape};
use super::{GRADIENT_NAMES, ORIGIN_KW, OriginMode, closed_loop, dedup_loops, gradient_name, island_style, loops_at, loops_from_handles};
use super::{GRADIENT_NAMES, ORIGIN_KW, OriginMode, closed_loop, dedup_loops, gradient_name, island_style, loops_at, loops_from_handles, same_loop};
use crate::cmd::helpers::lwpoly;
use crate::cmd::{bad, bool_or, point_param, points_param, size_param, str_param, targets};
use crate::{Accept, Input, Interactive, Picker, Prompt, Result, Session, Step};
@@ -420,7 +420,21 @@ fn edit_loops(h: &mut Hatch, added: &[HatchLoop], removed: &[usize]) -> Result<(
return Ok(());
}
h.loops = h.loops.drain(..).enumerate().filter_map(|(i, l)| (!removed.contains(&i)).then_some(l)).collect();
h.loops.extend_from_slice(added);
// A boundary the hatch already has is not added again (whatever role it has here): a second
// copy would cancel it under the odd-parity fill. Its objects join the loop there, so picking
// it links an unlinked loop to them.
for a in added {
match h.loops.iter_mut().find(|l| same_loop(l, a)) {
Some(l) => {
for s in &a.sources {
if !l.sources.contains(s) {
l.sources.push(*s);
}
}
}
None => h.loops.push(a.clone()),
}
}
dedup_loops(&mut h.loops);
if h.loops.is_empty() {
return Err(bad("hatchedit", "a hatch needs at least one boundary loop"));
+33 -14
View File
@@ -68,29 +68,48 @@ pub fn polygon_from_edge(p1: Vec2, p2: Vec2, sides: usize) -> Vec<PolyVertex> {
/// chamfer distances at every corner, in AutoCAD 2024's order: from `a` along X to `b`'s X, then
/// `b`, then back along Y. A chamfer cuts the edge into each corner by its first distance and the
/// edge out of it by its second; each fillet arc starts on the edge into its corner. A fillet or
/// chamfer that doesn't fit leaves the corners square.
/// chamfer too large for the shorter side leaves the corners square, each as two coincident
/// vertices, as AutoCAD stores them.
pub fn rect_with_corners(a: Vec2, b: Vec2, fillet: f64, chamfer: (f64, f64)) -> Vec<PolyVertex> {
let corners = [a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y)];
let short = (b.x - a.x).abs().min((b.y - a.y).abs());
let (d_in, d_out, bulge) = if fillet > 0.0 && fillet * 2.0 <= short + 1e-12 {
// Counter-clockwise round the corners (a positive bulge) when `b` is up and right of `a`, or
// down and left.
let sign = if (b.x - a.x) * (b.y - a.y) >= 0.0 { 1.0 } else { -1.0 };
(fillet, fillet, sign * cadcraft_geom::arc_to_bulge(std::f64::consts::FRAC_PI_2))
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 && chamfer.0 + chamfer.1 <= short + 1e-12 {
(chamfer.0, chamfer.1, 0.0)
} else {
return corners.into_iter().map(PolyVertex::new).collect();
};
let Some((d_in, d_out)) = rect_corner_cuts(fillet, chamfer) else { return corners.into_iter().map(PolyVertex::new).collect() };
let fits = rect_corners_fit(b - a, fillet, chamfer);
// Counter-clockwise round the corners (a positive bulge) when `b` is up and right of `a`, or
// down and left.
let sign = if (b.x - a.x) * (b.y - a.y) >= 0.0 { 1.0 } else { -1.0 };
let bulge = if fillet > 0.0 { sign * cadcraft_geom::arc_to_bulge(std::f64::consts::FRAC_PI_2) } else { 0.0 };
let mut out = Vec::with_capacity(8);
for (i, cur) in corners.iter().enumerate() {
let (Some(prev), Some(next)) = (corners.get((i + 3) % 4), corners.get((i + 1) % 4)) else { continue };
out.push(PolyVertex::with_bulge(*cur + (*prev - *cur).normalized() * d_in, bulge));
out.push(PolyVertex::new(*cur + (*next - *cur).normalized() * d_out));
if fits {
out.push(PolyVertex::with_bulge(*cur + (*prev - *cur).normalized() * d_in, bulge));
out.push(PolyVertex::new(*cur + (*next - *cur).normalized() * d_out));
} else {
out.extend([PolyVertex::new(*cur), PolyVertex::new(*cur)]);
}
}
out
}
/// How far a rectangle's fillet or chamfer cuts into the edges into and out of each corner, if
/// one is set: the fillet radius on both, or the two chamfer distances. A fillet wins over a
/// chamfer.
fn rect_corner_cuts(fillet: f64, chamfer: (f64, f64)) -> Option<(f64, f64)> {
if fillet > 0.0 {
Some((fillet, fillet))
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 {
Some(chamfer)
} else {
None
}
}
/// Whether a fillet or chamfer fits a rectangle of `size` (signed sides): its two cuts together
/// no longer than the shorter side. True when neither is set.
pub fn rect_corners_fit(size: Vec2, fillet: f64, chamfer: (f64, f64)) -> bool {
rect_corner_cuts(fillet, chamfer).is_none_or(|(d_in, d_out)| d_in + d_out <= size.x.abs().min(size.y.abs()) + 1e-12)
}
// ---------- the user's support files ----------
/// Largest support file (linetype, hatch pattern or alias file) read.
+9 -4
View File
@@ -532,12 +532,17 @@ pub(super) fn object_area(s: &Session, h: Handle) -> Result<(f64, f64)> {
(cadcraft_geom::PI * a * b, arc.arc_length_from(0.0, cadcraft_geom::TAU))
}
EntityKind::Hatch(hh) => {
// Odd parity, as drawn: a loop nested inside an odd number of other loops is an unfilled island.
let geoms: Vec<Polyline> = hh.loops.iter().map(|l| Polyline { vertices: l.vertices.clone(), closed: true }).collect();
let polys: Vec<Vec<Vec2>> = geoms.iter().map(|g| g.tessellate(1e-3)).collect();
// Odd parity, as drawn: a loop nested inside an odd number of other loops is an unfilled
// island. The loops the fill keeps (a repeated loop once; an outer loop and an island
// that are the same boundary cancel), each measured exactly with its arcs.
let kept = cadcraft_render::hatch_fill_loop_indices(hh, 1e-3);
let geoms: Vec<Polyline> =
kept.iter().filter_map(|(i, _)| hh.loops.get(*i)).map(|l| Polyline { vertices: l.vertices.clone(), closed: true }).collect();
let polys: Vec<Vec<Vec2>> = kept.into_iter().map(|(_, p)| p).collect();
let mut total = (0.0, 0.0);
for (i, g) in geoms.iter().enumerate() {
let probe = polys.get(i).and_then(|p| p.first().copied());
// As the fill tests nesting: an edge's middle (a vertex may touch the loop around).
let probe = polys.get(i).and_then(|p| cadcraft_render::hatch_loop_probe(p));
let depth = probe.map_or(0, |pt| polys.iter().enumerate().filter(|(j, q)| *j != i && cadcraft_geom::point_in_polygon(q, pt)).count());
total.0 += if depth % 2 == 0 { g.area().abs() } else { -g.area().abs() };
total.1 += g.len();
+1 -2
View File
@@ -62,8 +62,7 @@ impl Scope {
Some(_) => {
let name = given.unwrap_or_default();
let d = s.doc()?;
let l =
d.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(&name)).ok_or_else(|| bad(cmd, format!("no layout named \"{name}\"")))?;
let l = d.layout(&name).ok_or_else(|| bad(cmd, format!("no layout named \"{name}\"")))?;
Ok(Scope::Space(Space::Paper(l.name.clone())))
}
}
+3 -2
View File
@@ -251,6 +251,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
*l = updated;
if let Some(nn) = new_name {
l.name = nn.clone();
cadcraft_doc::foreign::Foreign::rename_shared(&mut d.foreign, &["LAYER"], &old, &nn);
// Re-point entities in model space, every layout and every block definition.
repoint(&mut d.model, &old, &nn);
for layout in &mut d.layouts {
@@ -297,7 +298,7 @@ fn run_layerp(s: &mut Session, _p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
let snap = d.header.str("CADCRAFT_LAYERP", "");
let layers: Vec<Layer> = serde_json::from_str(&snap).map_err(|_| bad("layerp", "No previous layer state."))?;
d.layers = layers;
d.layers = layers.into();
Ok(json!({"message": "Restored previous layer states."}))
}
@@ -375,7 +376,7 @@ fn run_layuniso(s: &mut Session, _p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
let snap = d.header.str("CADCRAFT_LAYISO", "");
let layers: Vec<Layer> = serde_json::from_str(&snap).map_err(|_| bad("layuniso", "No isolated layers."))?;
d.layers = layers;
d.layers = layers.into();
ok()
}
+176 -10
View File
@@ -26,14 +26,18 @@ pub fn specs() -> Vec<CommandSpec> {
.interactive(|_| Ok(Box::new(prompts::LayoutM::default()))),
CommandSpec::new("layout.new", "New Layout", run_new)
.menu(&["Insert", "Layout", "New Layout"])
.params("{name?, viewport?: bool (default true)} → {name, viewport}")
.params("{name?, viewport?: bool (default true), window?: [[x1,y1],[x2,y2]] (the model area the viewport shows; default the model extents)} → {name, viewport} (typed: asks the name only; LAYOUT.NEWAREA also asks the area)")
.interactive(|_| Ok(Box::new(NewLayoutM))),
CommandSpec::new("layout.newarea", "New Layout from Area...", run_new)
.menu(&["Insert", "Layout", "New Layout from Area..."])
.params("{name?, viewport?: bool (default true), window?: [[x1,y1],[x2,y2]] (the model area the viewport shows; default the model extents)} → {name, viewport} (typed: asks the name, then the area)")
.interactive(|_| Ok(Box::new(NewLayoutAreaM::default()))),
CommandSpec::new("layout.delete", "Delete Layout", run_delete).params("{name}"),
CommandSpec::new("layout.rename", "Rename Layout", run_rename).params("{from?: current layout, to}"),
CommandSpec::new("layout.copy", "Copy Layout", run_copy).params("{from, to?}"),
CommandSpec::new("layout.list", "List Layouts", run_list).params("→ [{name, tabOrder, page, viewports}]").noundo(),
CommandSpec::new("layout.saveas", "Save Layout as Template", saveas::run_saveas)
.params("{name?: layout (default: the current layout, else the first tab), path: .dwt (or .dwg, .dxf; no extension adds .dwt)} → {name, path, bytes, notSaved?}")
.params("{name?: layout (default: the current layout, else the first tab), path: .dwt (or .dwg, .dxf; no extension adds .dwt)} → {name, path, bytes, notSaved?, warnings?}")
.noundo(),
CommandSpec::new("mview", "Viewports", run_mview)
.alias(&["mv"])
@@ -78,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("pagesetup", "Page Setup Manager...", run_pagesetup)
.menu(&["File", "Page Setup Manager..."])
.params(
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|\"B4 (JIS)\"|\"Japanese Postcard\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
),
CommandSpec::new("plot", "Print...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "plot")?, "plot"))
.menu(&["File", "Print..."])
@@ -225,7 +229,133 @@ impl Interactive for NewLayoutM {
}
}
/// LAYOUT.NEWAREA from the menu or command line: asks for the name (Enter takes the next free one),
/// then for the part of the model the new layout shows. The Model tab is shown for that, so it
/// can be zoomed and panned first; two corners pick the area (Enter takes the whole drawing). The
/// new layout is then shown, zoomed to that area.
#[derive(Default)]
struct NewLayoutAreaM {
/// The checked name, once it has been asked.
name: Option<String>,
/// The first corner of the model area.
first: Option<Vec2>,
/// The tab the command started in, put back when it is cancelled.
from: Option<Space>,
}
impl NewLayoutAreaM {
/// Show tab `space` (`layout.set`).
fn show(s: &mut Session, space: &Space) -> Result<()> {
let set = find_command("layout.set").ok_or_else(|| crate::EngineError::UnknownCommand("layout.set".into()))?;
(set.run)(s, &json!({ "name": space.tab_name() }))?;
Ok(())
}
}
impl Interactive for NewLayoutAreaM {
fn name(&self) -> &'static str {
"LAYOUT"
}
fn prompt(&self, s: &Session) -> Prompt {
match (&self.name, self.first) {
(None, _) => {
let next = s.doc().map(next_layout_name).unwrap_or_else(|_| "Layout1".into());
Prompt::new("Enter name of new layout", Accept::TEXT).default(next)
}
(Some(_), None) => {
Prompt::new("Specify first corner of the model area to show in the layout, or press ENTER for the whole drawing", Accept::POINT)
}
// A window's first corner: with ortho on, the opposite corner is not bent onto it.
(Some(_), Some(a)) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let Some(name) = self.name.clone() else {
let name = match i {
Input::Text(t) if !t.trim().is_empty() => t.trim().to_string(),
Input::Text(_) | Input::Enter => next_layout_name(s.doc()?),
_ => return Ok(Step::Continue),
};
// A taken or invalid name is an error: the session reports it and asks again.
let name = check_name("layout.newarea", s.doc()?, &name, None)?;
// The area is picked in the Model tab, where the drawing can be zoomed and panned.
self.from = Some(s.layout_space());
Self::show(s, &Space::Model)?;
self.name = Some(name);
return Ok(Step::Continue);
};
// The corners are model points. If another tab was shown meanwhile (a tab click, `layout.set`),
// a point would be read in that space, so the command ends and leaves that choice alone.
if s.layout_space() != Space::Model {
self.from = None;
return Ok(Step::Cancel);
}
let window = match (i, self.first) {
(Input::Point(p), None) => {
self.first = Some(p);
return Ok(Step::Continue);
}
(Input::Point(p), Some(a)) => Some([a, p]),
(Input::Enter, None) => None,
_ => return Ok(Step::Continue),
};
let mut p = json!({ "name": name });
if let (Some([a, b]), Some(o)) = (window, p.as_object_mut()) {
o.insert("window".into(), json!([[a.x, a.y], [b.x, b.y]]));
}
// A window without width or height is an error, reported before any layout is added:
// the session asks for the first corner again.
self.first = None;
run_new(s, &p)?;
Self::show(s, &Space::Paper(name))?;
Ok(Step::Done)
}
/// Puts back the tab the command started in.
fn cancelled(&mut self, s: &mut Session) {
// Only if the Model tab is still shown: a tab the user chose since is left alone.
if let Some(from) = self.from.take()
&& s.layout_space() == Space::Model
&& let Err(e) = Self::show(s, &from)
{
s.echo(e.to_string());
}
}
/// The rectangle following the cursor while the second corner is picked.
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
let Some(a) = self.first else { return Vec::new() };
let corners = [a, Vec2::new(c.x, a.y), c, Vec2::new(a.x, c.y), a];
corners
.windows(2)
.filter_map(|w| match w {
[p, q] => Some(super::helpers::line(*p, *q)),
_ => None,
})
.collect()
}
}
/// The model-space window of a `layout.new`, when it has one: `window: [[x1, y1], [x2, y2]]`.
fn window_param(p: &Value) -> Result<Option<Bounds2>> {
let Some(raw) = p.get("window").filter(|w| !w.is_null()) else { return Ok(None) };
let corners = raw.as_array();
let a = corners.and_then(|c| c.first()).and_then(point_value);
let b = corners.and_then(|c| c.get(1)).and_then(point_value);
let (Some(a), Some(b)) = (a, b) else {
return Err(bad("layout.new", "`window` needs two corners: [[x1, y1], [x2, y2]]"));
};
let w = Bounds2::new(a, b);
if w.min.is_finite() && w.max.is_finite() && w.width() > 1e-9 && w.height() > 1e-9 && w.width() < 1e12 && w.height() < 1e12 {
Ok(Some(w))
} else {
Err(bad("layout.new", "the window needs a width and a height"))
}
}
/// LAYOUT.NEW from JSON: add a layout (with a viewport unless `viewport` is false), zoomed to
/// `window` when it has one and to the model extents otherwise.
fn run_new(s: &mut Session, p: &Value) -> Result<Value> {
// Checked before anything is added, so a bad window leaves no layout behind.
let window = window_param(p)?;
let d = s.doc()?;
let name = match str_param(p, "name") {
Some(n) => check_name("layout.new", d, n, None)?,
@@ -236,16 +366,30 @@ fn run_new(s: &mut Session, p: &Value) -> Result<Value> {
s.doc_mut()?.layouts.push(Layout { page, ..Layout::new(&name, order) });
let mut vp = Value::Null;
if bool_or(p, "viewport", true) {
// AutoCAD behaviour: one viewport over the printable area, zoomed to the model extents.
// AutoCAD behaviour: one viewport over the printable area, zoomed to the model extents,
// or to the `window` when it has one.
let space = Space::Paper(name.clone());
let rect = printable(s, &name)?;
if let Some(h) = add_viewports(s, &space, rect, 1, "")?.first() {
if let Some(w) = window {
show_window(s, *h, w)?;
}
vp = json!(h.hex());
}
}
Ok(json!({ "name": name, "viewport": vp }))
}
/// Zoom viewport `h` to the model area `w`.
fn show_window(s: &mut Session, h: Handle, w: Bounds2) -> Result<()> {
s.doc_mut()?.modify_entity(h, |e| {
if let EntityKind::Viewport(v) = &mut e.kind {
(v.view_center, v.view_height) = fit_bounds(w, v.width, v.height);
}
})?;
Ok(())
}
fn run_delete(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("layout.delete", "`name` is required"))?;
let name = layout_name("layout.delete", s.doc()?, name)?;
@@ -437,6 +581,11 @@ fn fit_view(d: &Drawing, w: f64, h: f64) -> (Vec2, f64) {
let hi = d.header.point("LIMMAX").map(|p| p.xy()).unwrap_or(Vec2::new(12.0, 9.0));
ext = Bounds2::new(lo, hi);
}
fit_bounds(ext, w, h)
}
/// The view centre and height that show the model area `ext` in a viewport of size `w` × `h`.
fn fit_bounds(ext: Bounds2, w: f64, h: f64) -> (Vec2, f64) {
let aspect = (w / h.max(1e-12)).max(1e-12);
let vh = (ext.height().max(ext.width() / aspect) * 1.02).max(1e-9);
let c = ext.center();
@@ -683,8 +832,21 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
// The standard size the layout had before this call, so that resubmitting it (the Plot
// dialog's Apply to Layout always sends `paper`) keeps the layout's paper units.
let old_paper = cadcraft_render::paper_size(&page.paper).map(|ps| ps.name);
let turned = p.get("landscape").and_then(Value::as_bool).filter(|l| *l != page.landscape);
// The orientation first: a paper taken from a device turns its margins to the sheet the page
// names when `page_device` copies them.
if let Some(l) = turned {
page.landscape = l;
}
// A plotter's own papers (with their printable areas) come first.
let device_paper = super::plotters::page_device(cmd, p, &mut page)?;
// A page that keeps its paper keeps its margins, and the margins are measured against the
// sheet's axes: turning the orientation turns them too (#1266). Explicit margins are already
// on the new sheet's axes.
if turned.is_some() && !device_paper && p.get("margins").is_none() {
page.margins_mm =
if page.landscape { super::plotters::landscape_margins(page.margins_mm) } else { super::plotters::portrait_margins(page.margins_mm) };
}
if let Some(paper) = p.get("paper").filter(|_| !device_paper) {
let n = paper.as_str().ok_or_else(|| bad(cmd, "`paper` must be a paper name"))?;
let ps = cadcraft_render::paper_size(n).ok_or_else(|| {
@@ -723,9 +885,6 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
(None, None) if p.get("width").is_none() && p.get("height").is_none() => {}
_ => return Err(bad(cmd, "`width` and `height` (mm, 0-5080) are both required for a custom size")),
}
if let Some(l) = p.get("landscape").and_then(Value::as_bool) {
page.landscape = l;
}
// Paper units: what one paper-space unit is on this layout, whatever the paper's own family
// (an ARCH D sheet can be drawn in millimetres, #3249).
if let Some(v) = p.get("paperUnits") {
@@ -890,7 +1049,7 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
if is_image && sheets.as_ref().is_some_and(|names| names.len() > 1) {
return Err(bad(cmd, "`layouts` with several sheets needs PDF output; PNG and SVG hold one sheet, so plot each layout separately"));
}
let bytes = hook(s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?;
let (bytes, notes) = super::file::plot_noted(hook, s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?;
let layout = match &sheets {
Some(names) => names.first().cloned().unwrap_or_default(),
None => space.tab_name().to_string(),
@@ -909,15 +1068,22 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
let mut r = json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_new_folder(s, &mut r, folder);
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
#[cfg(target_arch = "wasm32")]
{
super::exchange::deliver_file(cmd, _path, &bytes, super::file::deliver())?;
Ok(json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format }))
let mut r = json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
}
None => Ok(json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format })),
None => {
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
}
}
+4 -1
View File
@@ -12,7 +12,7 @@ use cadcraft_doc::{Common, Drawing, Entity, EntityKind, EntityStore, Point};
use cadcraft_geom::Vec3;
use serde_json::{Value, json};
use super::super::file::{drops_unknown, io, not_saved, not_saved_message};
use super::super::file::{drops_unknown, dwg_notes, io, not_saved, not_saved_message, report_dwg_notes};
use super::super::{bad, str_param};
use super::layout_name;
use super::prompts::current_layout;
@@ -136,6 +136,9 @@ pub(super) fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
o.insert("notSaved".into(), json!(lost));
}
}
if drops_unknown(&path) {
report_dwg_notes(s, &mut r, dwg_notes(&t));
}
Ok(r)
}
+136
View File
@@ -88,6 +88,7 @@ fn new_layout_from_the_menu_asks_for_a_name() {
s.cmdline("Layout1").unwrap();
assert!(s.running.is_some(), "a taken name asks again");
s.cmdline("Sheet A").unwrap();
// The name is all it asks: no model area, no tab change.
assert!(s.running.is_none());
s.start("layout.new").unwrap();
s.cmdline("").unwrap();
@@ -95,6 +96,141 @@ fn new_layout_from_the_menu_asks_for_a_name() {
assert!(d.layout("Sheet A").is_some() && d.layout("Layout3").is_some(), "Enter takes the default name");
}
/// LAYOUT.NEWAREA asks the name, then the area; Enter takes the whole drawing.
#[test]
fn new_layout_from_area_asks_a_name_then_the_area() {
let mut s = session_with_model();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet A").unwrap();
assert!(s.running.is_some() && s.current_prompt().is_some_and(|p| p.message.contains("first corner of the model area")));
s.cmdline("").unwrap();
assert!(s.running.is_none());
assert!(s.doc().unwrap().layout("Sheet A").is_some());
}
/// The viewport of layout `name`.
fn only_viewport(s: &Session, name: &str) -> Viewport {
let v = viewports(s, name);
assert_eq!(v.len(), 1, "one viewport");
v.into_iter().next().map(|(_, v)| v).unwrap()
}
/// A `window` zooms the new layout's viewport to that part of the model.
#[test]
fn a_new_layout_can_show_a_window_of_the_model() {
let mut s = session_with_model();
s.execute("layout.new", &json!({"name": "Sheet W", "window": [[10, 10], [30, 20]]})).unwrap();
let v = only_viewport(&s, "Sheet W");
assert!(v.view_center.dist(Vec2::new(20.0, 15.0)) < 1e-9, "centred on the window: {:?}", v.view_center);
let aspect = v.width / v.height;
assert!(v.view_height >= 10.0 && v.view_height * aspect >= 20.0, "the whole window is in view");
assert!(v.view_height <= (10.0_f64).max(20.0 / aspect) * 1.02 + 1e-9, "and not much more: {}", v.view_height);
// Without a window the viewport shows the model extents, as before.
s.execute("layout.new", &json!({"name": "Sheet E"})).unwrap();
let e = only_viewport(&s, "Sheet E");
assert!(e.view_height > v.view_height * 2.0, "extents are larger than the window");
}
/// A window without area, or not two corners, is an error that leaves no layout behind.
#[test]
fn a_bad_layout_window_adds_no_layout() {
let mut s = session_with_model();
let before = s.doc().unwrap().layouts.len();
for w in [
json!([[1, 1], [1, 9]]),
json!([[1, 1], [9, 1]]),
json!([[1, 1]]),
json!("all"),
json!([[1, 1], ["a", 2]]),
json!([[f64::MAX, 0], [-f64::MAX, 1]]),
] {
assert!(s.execute("layout.new", &json!({"name": "Bad", "window": w})).is_err(), "{w}");
}
assert_eq!(s.doc().unwrap().layouts.len(), before, "no layout is left behind");
}
/// The interactive command shows the Model tab, takes two corners and shows the new layout.
#[test]
fn new_layout_picks_the_model_area_in_the_model_tab() {
let mut s = session_with_model();
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet P").unwrap();
assert_eq!(s.space(), Space::Model, "the Model tab is shown to pick the area");
s.cmdline("10,10").unwrap();
assert!(s.current_prompt().is_some_and(|p| p.message == "Specify opposite corner"));
// A window without width re-asks for the first corner and adds nothing.
s.cmdline("10,30").unwrap();
assert!(s.current_prompt().is_some_and(|p| p.message.contains("first corner")), "{:?}", s.current_prompt().map(|p| p.message));
assert!(s.doc().unwrap().layout("Sheet P").is_none());
s.cmdline("10,10").unwrap();
s.cmdline("30,20").unwrap();
assert!(s.running.is_none());
assert_eq!(s.space(), Space::Paper("Sheet P".into()), "the new layout is shown");
let v = only_viewport(&s, "Sheet P");
assert!(v.view_center.dist(Vec2::new(20.0, 15.0)) < 1e-9, "{:?}", v.view_center);
s.undo().unwrap();
assert!(s.doc().unwrap().layout("Sheet P").is_none(), "one undo step");
}
/// A tab shown while the corners are picked ends the command instead of reading points in that space.
#[test]
fn new_layout_ends_if_another_tab_is_shown_while_picking() {
let mut s = session_with_model();
let before = s.doc().unwrap().layouts.len();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet T").unwrap();
assert_eq!(s.space(), Space::Model);
// A tab shown meanwhile: the next point must not be taken for a model corner.
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.cmdline("10,10").unwrap();
assert!(s.running.is_none(), "the command ended");
assert_eq!(s.layout_space(), Space::Paper("Layout1".into()), "the tab that was shown stays");
assert_eq!(s.doc().unwrap().layouts.len(), before, "no layout was added");
}
/// The opposite-corner prompt is a window corner, so ortho does not bend it.
#[test]
fn the_opposite_corner_is_not_bent_by_ortho() {
let mut s = session_with_model();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet O").unwrap();
s.cmdline("10,10").unwrap();
let p = s.current_prompt().unwrap();
assert!(p.corner && p.base == Some(Vec2::new(10.0, 10.0)), "a window's opposite corner prompt");
}
/// Esc puts back the tab the command started in and adds no layout.
#[test]
fn cancelling_new_layout_puts_the_tab_back() {
let mut s = session_with_model();
s.execute("layout.set", &json!({"name": "Layout2"})).unwrap();
let before = s.doc().unwrap().layouts.len();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet C").unwrap();
assert_eq!(s.space(), Space::Model);
s.cancel();
assert!(s.running.is_none());
assert_eq!(s.space(), Space::Paper("Layout2".into()), "back in the tab it started in: {:?}", s.log);
assert_eq!(s.doc().unwrap().layouts.len(), before);
// Esc at the name prompt changes nothing either.
s.start("layout.newarea").unwrap();
s.cancel();
assert_eq!(s.space(), Space::Paper("Layout2".into()));
}
/// Esc after the user chose another tab leaves that tab shown, not the one the command started in.
#[test]
fn cancelling_new_layout_keeps_a_tab_chosen_meanwhile() {
let mut s = session_with_model();
s.execute("layout.set", &json!({"name": "Layout2"})).unwrap();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet K").unwrap();
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.cancel();
assert!(s.running.is_none());
assert_eq!(s.space(), Space::Paper("Layout1".into()), "the tab chosen meanwhile stays: {:?}", s.log);
}
#[test]
fn mview_arrangements_and_interactive() {
let mut s = session_with_model();
+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,
+1 -1
View File
@@ -36,7 +36,7 @@ use oops::run_oops;
pub(crate) use oops::{Erased, erase_kept};
use select_then::{DisplaceM, Op, SelectThen};
use stretch::{StretchM, run_stretch};
pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities};
pub(crate) use transform::{at_elevation, holds_ole_frame, ole_refusal, refuse_ole_frames, scale_entities, transform_entities};
use transform::{mirror_entities, mirror_kind, run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
pub(crate) use trim::{
CUT_ONCE, Edges, Overlay, edge_segments, edge_segments_over, extend, extend_kind, extended, json_pick_error, trim, trim_kind, trimmed,
+376 -50
View File
@@ -129,80 +129,406 @@ pub(crate) fn join(s: &mut Session, hs: &[Handle]) -> Result<Option<Handle>> {
if hs.iter().any(|h| crate::cmd::curves::is_locked(s, *h)) {
return Err(EngineError::Other("An object is on a locked layer.".into()));
}
let hs = joinable_picks(s.doc()?, hs);
let hs = &hs[..];
if let Some(h) = join_on_source(s, hs)? {
return Ok(Some(h));
}
let d = s.doc()?;
let mut segs: Vec<Segment> = Vec::new();
// Source entity of each segment in `segs`, so only entities that end up in the chain are removed.
let mut owners: Vec<Handle> = Vec::new();
let mut common = None;
// Each object JOIN can take, as the pieces it is made of: a line or an arc is one piece, an
// open polyline its segments in order, each keeping its vertices, bulge and widths exactly.
// Each also with whether it faces down: an arc or a polyline whose normal points down Z
// (measured with 0,0,-1; a tilted one is taken the same way). A line faces up whatever its
// normal (AutoCAD 2024 joins one with normal 0,0,-1 to a polyline facing up, and no line to a
// polyline facing down; measured).
let mut units: Vec<(bool, Vec<Piece>)> = Vec::new();
let down = |e: &Entity| !matches!(e.kind, EntityKind::Line(_)) && e.common.extrusion.z < 0.0;
for h in hs {
let Some(e) = d.entity(*h) else { continue };
common.get_or_insert_with(|| e.common.clone());
match &e.kind {
EntityKind::Line(l) => segs.push(Segment::Line(Line::new(l.a.xy(), l.b.xy()))),
EntityKind::Arc(a) => segs.push(Segment::Arc { arc: Arc::new(a.center.xy(), a.radius, a.start, a.end), ccw: true }),
EntityKind::LwPolyline(p) if !p.closed => segs.extend(Polyline { vertices: p.vertices.clone(), closed: false }.segments()),
_ => {}
let piece =
|ends: (Vec2, Vec2), heights: (f64, f64), bulge: f64, widths: Option<(f64, f64)>| Piece { owner: *h, ends, heights, bulge, widths };
let unit: Vec<Piece> = match &e.kind {
// A line of no length joins as AutoCAD 2024 joins it, a repeated vertex.
EntityKind::Line(l) => vec![piece((l.a.xy(), l.b.xy()), (l.a.z, l.b.z), 0.0, None)],
EntityKind::Arc(a) => {
let arc = Arc::new(a.center.xy(), a.radius, a.start, a.end);
vec![piece((arc.start_point(), arc.end_point()), (a.center.z, a.center.z), cadcraft_geom::arc_to_bulge(arc.sweep()), None)]
}
// Repeated vertices included: AutoCAD 2024 keeps them.
EntityKind::LwPolyline(p) if !p.closed => {
// The elevation is along the polyline's normal: down Z for a mirrored one.
let z = if down(e) { -p.elevation } else { p.elevation };
p.vertices
.windows(2)
.map(|w| {
let widths = if p.const_width > 0.0 { (p.const_width, p.const_width) } else { (w[0].start_width, w[0].end_width) };
piece((w[0].p, w[1].p), (z, z), w[0].bulge, Some(widths))
})
.collect()
}
_ => Vec::new(),
};
if !unit.is_empty() {
units.push((down(e), unit));
}
owners.resize(segs.len(), *h);
}
if segs.len() < 2 {
if units.iter().map(|u| u.1.len()).sum::<usize>() < 2 {
return Err(EngineError::Other("Select at least two objects to join.".into()));
}
// Chain greedily from the first segment.
let mut chain = vec![segs.remove(0)];
let mut used = vec![owners.remove(0)];
// An object facing the other way from a polyline source stays out (AutoCAD 2024, measured: one
// facing up takes no arc facing down, and one facing down no arc or polyline facing up). Onto a
// line or an arc it wasn't measured (the core console's JOIN takes only collinear lines or arcs
// on one circle onto those), so objects facing either way still join there.
let polyline_source = units.first().filter(|u| u.1.first().is_some_and(|p| p.widths.is_some())).map(|u| u.0);
let units: Vec<Vec<Piece>> = units.into_iter().filter(|u| polyline_source.is_none_or(|down| u.0 == down)).map(|u| u.1).collect();
// A new polyline takes the source's properties.
let first = units.first().and_then(|u| u.first()).map(|p| p.owner);
let common = first.and_then(|h| d.entity(h)).map(|e| e.common.clone());
let tol = 1e-6;
loop {
let start = chain.first().map(Segment::start).unwrap_or_default();
let end = chain.last().map(Segment::end).unwrap_or_default();
let Some(i) =
segs.iter().position(|s| s.start().near(end, tol) || s.end().near(end, tol) || s.start().near(start, tol) || s.end().near(start, tol))
else {
break;
};
let s0 = segs.remove(i);
used.push(owners.remove(i));
if s0.start().near(end, tol) {
chain.push(s0);
} else if s0.end().near(end, tol) {
chain.push(s0.reversed());
} else if s0.end().near(start, tol) {
chain.insert(0, s0);
} else {
chain.insert(0, s0.reversed());
}
}
if chain.len() < 2 {
let links = chain_units(units, tol);
// One object alone joins nothing, even a polyline whose ends meet: AutoCAD 2024 leaves it open
// ("0 segments added to polyline").
let closed = links.first().zip(links.last()).is_some_and(|(a, b)| meet(a.start(), b.end(), tol));
let one_object = links.first().is_some_and(|f| links.iter().all(|l| l.owner == f.owner));
if links.len() < 2 || one_object {
return Err(EngineError::Other("Objects are not connected.".into()));
}
let closed = chain.first().zip(chain.last()).is_some_and(|(a, b)| a.start().near(b.end(), tol));
let mut vs: Vec<PolyVertex> = chain
let used = |h: &Handle| links.iter().any(|l| l.owner == *h);
// A polyline's own segments keep their widths.
let mut vs: Vec<PolyVertex> = links
.iter()
.map(|s| PolyVertex {
p: s.start(),
bulge: match s {
Segment::Line(_) => 0.0,
Segment::Arc { arc, ccw } => cadcraft_geom::arc_to_bulge(if *ccw { arc.sweep() } else { -arc.sweep() }),
},
..Default::default()
.map(|l| {
let (start_width, end_width) = l.widths.unwrap_or_default();
PolyVertex { p: l.ends.0, bulge: l.bulge, start_width, end_width }
})
.collect();
if !closed && let Some(l) = chain.last() {
vs.push(PolyVertex::new(l.end()));
if !closed && let Some(l) = links.last() {
vs.push(PolyVertex::new(l.ends.1));
}
let space = s.space();
// A new polyline goes in the source's space, whichever space is current.
let space = first.and_then(|h| d.space_of(h)).unwrap_or_else(|| s.space());
let doc = s.doc_mut()?;
for h in hs.iter().filter(|h| used.contains(*h)) {
// A polyline source takes the other pieces and keeps its handle (AutoCAD 2024: "1 segments
// added to polyline").
if let Some(src) = first
&& let Some(EntityKind::LwPolyline(sp)) = doc.entity(src).map(|e| &e.kind)
&& let Some(onto) = onto_polyline(sp, src, &links, closed)
{
for h in hs.iter().filter(|h| **h != src && used(h)) {
doc.remove_entity(*h);
}
doc.modify_entity(src, |e| e.kind = EntityKind::LwPolyline(onto))?;
s.set_selection(Vec::new());
return Ok(Some(src));
}
for h in hs.iter().filter(|h| used(h)) {
doc.remove_entity(*h);
}
// A new polyline stays at the source's height, as a polyline source keeps its elevation. The
// elevation runs along its normal: negated for one facing down. Not measured: the core
// console's JOIN makes no new polyline.
let height = links.iter().find(|l| Some(l.owner) == first).map_or(0.0, |l| l.heights.0);
let common = common.unwrap_or_default();
let elevation = if common.extrusion.z < 0.0 { -height } else { height };
let mut kind = lwpoly(vs, closed);
if let EntityKind::LwPolyline(p) = &mut kind {
p.elevation = elevation;
}
let nh = doc.new_handle();
if let Some(st) = doc.space_mut(&space) {
st.push(Entity { handle: nh, common: common.unwrap_or_default(), kind: lwpoly(vs, closed) });
st.push(Entity { handle: nh, common, kind });
}
s.set_selection(Vec::new());
Ok(Some(nh))
}
/// The picks JOIN can take, each once, in the order picked: lines, arcs and open polylines. The
/// first of them is the source (AutoCAD 2024 passes over a circle picked first and leaves it).
fn joinable_picks(d: &cadcraft_doc::Drawing, hs: &[Handle]) -> Vec<Handle> {
let mut seen = std::collections::HashSet::new();
let joinable = |h: &Handle| {
d.entity(*h).is_some_and(|e| match &e.kind {
EntityKind::Line(_) => true,
EntityKind::Arc(a) => a.radius > cadcraft_geom::EPS,
EntityKind::LwPolyline(p) => !p.closed,
_ => false,
})
};
hs.iter().copied().filter(|h| joinable(h) && seen.insert(*h)).collect()
}
/// Whether JOIN would make the picked arcs a circle. AutoCAD 2024 asks first ("Combined arc
/// segments form a circle. Convert to circle? [Yes/No] <Yes>:"), and No leaves every arc as it
/// is (measured).
pub(crate) fn join_makes_circle(s: &Session, hs: &[Handle]) -> bool {
let Ok(d) = s.doc() else { return false };
// Elliptical arcs and splines join another way, and a locked object stops the join.
let other_way = |h: &Handle| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Ellipse(_) | EntityKind::Spline(_)));
if hs.iter().any(|h| other_way(h) || crate::cmd::curves::is_locked(s, *h)) {
return false;
}
let picks = joinable_picks(d, hs);
let arcs: Vec<&cadcraft_doc::Arc> = picks
.iter()
.filter_map(|h| match d.entity(*h).map(|e| &e.kind) {
Some(EntityKind::Arc(a)) => Some(a),
_ => None,
})
.collect();
let tol = 1e-6;
match &arcs[..] {
[g, rest @ ..] if !rest.is_empty() && arcs.len() == picks.len() => arc_reach(g, rest, tol).is_some_and(|far| far > cadcraft_geom::TAU - tol),
_ => false,
}
}
/// How far round the source arc `g`'s circle, counterclockwise from its start, it and the
/// `others` reach; `None` when one of them isn't on that circle (less than `tol` off its centre
/// and radius). An arc that starts even a hair before the source's start reaches on round past
/// it: AutoCAD 2024 makes a circle of 7°-100° and an arc stored from 7° less 5e-16 rad, and
/// leaves 7°-100° with one from exactly 7° or 5e-7 rad after it.
fn arc_reach(g: &cadcraft_doc::Arc, others: &[&cadcraft_doc::Arc], tol: f64) -> Option<f64> {
let same_circle =
|o: &cadcraft_doc::Arc| o.center.xy().dist(g.center.xy()) < tol && (o.radius - g.radius).abs() < tol && (o.center.z - g.center.z).abs() < tol;
let reach = |o: &cadcraft_doc::Arc| norm_angle(o.start - g.start) + cadcraft_geom::ccw_sweep(o.start, o.end);
others.iter().all(|o| same_circle(o)).then(|| others.iter().map(|o| reach(o)).fold(reach(g), f64::max))
}
/// The chain JOIN builds from the first object: each next object with an end on one of the
/// chain's ends joins whole, turned round where needed, as AutoCAD 2024 joins them, until a join
/// closes the chain; one that the chain meets only at an inner vertex of a polyline stays out.
/// Ends are compared at the objects' own end points, not ones worked out again from arcs, and at
/// their heights.
fn chain_units(mut units: Vec<Vec<Piece>>, tol: f64) -> Vec<Piece> {
let ends = |u: &[Piece]| u.first().zip(u.last()).map(|(a, b)| (a.start(), b.end()));
let near = |p, q| meet(p, q, tol);
if units.is_empty() {
return Vec::new();
}
// A source that already ends where it starts still takes more, unless it has no length at all
// (AutoCAD 2024, measured with a polyline that ends where it starts and with a line of no
// length).
let mut chain: std::collections::VecDeque<Piece> = units.remove(0).into();
if chain.iter().all(|p| p.ends.0.near(p.ends.1, tol)) {
return chain.into();
}
while let (Some(start), Some(end)) = (chain.front().map(Piece::start), chain.back().map(Piece::end)) {
let meets = |u: &Vec<Piece>| ends(u).is_some_and(|(a, b)| near(a, end) || near(b, end) || near(a, start) || near(b, start));
let Some(i) = units.iter().position(meets) else { break };
let unit = units.remove(i);
let Some((a, b)) = ends(&unit) else { break };
// Where an object that meets the chain at more than one place goes, as AutoCAD 2024 puts
// it (measured): a polyline by its first vertex if it can, and before the chain rather
// than after it; a line or an arc turned round if it can, its end on the chain's end
// before its start on the chain's start.
let polyline = unit.first().is_some_and(|p| p.widths.is_some());
let (before, turned) = if polyline {
if near(a, start) {
(true, true)
} else if near(a, end) {
(false, false)
} else {
(near(b, start), !near(b, start))
}
} else if near(b, end) {
(false, true)
} else if near(a, start) {
(true, true)
} else {
(!near(a, end), false)
};
match (before, turned) {
(false, false) => chain.extend(unit),
(false, true) => chain.extend(unit.into_iter().rev().map(Piece::flipped)),
(true, false) => unit.into_iter().rev().for_each(|p| chain.push_front(p)),
(true, true) => unit.into_iter().for_each(|p| chain.push_front(p.flipped())),
}
// A chain that a join closes takes nothing more.
if chain.front().zip(chain.back()).is_some_and(|(f, l)| near(f.start(), l.end())) {
break;
}
}
chain.into()
}
/// A segment in the chain JOIN builds: the object it came from, its end points as the object has
/// them (turned round when it runs backwards in the chain) and their world heights (a line's own
/// Z, an arc's centre Z, a polyline's elevation, negated for one facing down), its bulge and, for a
/// polyline's own segment, its widths.
#[derive(Clone, Copy)]
struct Piece {
owner: Handle,
ends: (Vec2, Vec2),
heights: (f64, f64),
bulge: f64,
widths: Option<(f64, f64)>,
}
impl Piece {
fn flipped(self) -> Self {
Piece {
ends: (self.ends.1, self.ends.0),
heights: (self.heights.1, self.heights.0),
bulge: -self.bulge,
widths: self.widths.map(|(a, b)| (b, a)),
..self
}
}
fn start(&self) -> (Vec2, f64) {
(self.ends.0, self.heights.0)
}
fn end(&self) -> (Vec2, f64) {
(self.ends.1, self.heights.1)
}
}
/// Whether two ends meet: in plan and at the same height. AutoCAD 2024 leaves an end that meets
/// another only in plan apart (measured: a line or a polyline at 0 and a line at 5, or a polyline
/// at 5 and a line at 0, end to end in plan, stay as they are).
fn meet(p: (Vec2, f64), q: (Vec2, f64), tol: f64) -> bool {
p.0.near(q.0, tol) && (p.1 - q.1).abs() < tol
}
/// The open polyline `sp` (handle `src`) with the chain's other pieces added before and after
/// it, as AutoCAD 2024 JOIN makes it (measured with `entget`): its own vertices stay exactly as
/// they are, and so do its elevation, linetype generation and, when only lines and arcs join,
/// its constant width; another polyline's segments keep their bulges and widths; a line or arc
/// takes the widths of the source's vertex at the end it joins (first or last); and when another
/// polyline joins, the end vertex's widths are cleared.
///
/// `None` when the source's segments aren't one run of the chain (they always are: the chain
/// starts from the source and takes its segments in order).
fn onto_polyline(sp: &cadcraft_doc::LwPolyline, src: Handle, links: &[Piece], closed: bool) -> Option<cadcraft_doc::LwPolyline> {
let run: Vec<usize> = (0..links.len()).filter(|i| links[*i].owner == src).collect();
let (&first, &last) = (run.first()?, run.last()?);
if sp.closed || run.len() != last - first + 1 {
return None;
}
let other_polyline = links.iter().any(|l| l.owner != src && l.widths.is_some());
let mut own = sp.vertices.clone();
if other_polyline && sp.const_width > 0.0 {
// The constant width goes, so spell it out on the source's own segments.
for v in &mut own {
(v.start_width, v.end_width) = (sp.const_width, sp.const_width);
}
}
let widths = |v: &PolyVertex| (v.start_width, v.end_width);
let (head, tail) = (widths(own.first()?), widths(own.last()?));
let vertex = |i: usize, fill: (f64, f64)| {
let (start_width, end_width) = links[i].widths.unwrap_or(fill);
PolyVertex { p: links[i].ends.0, bulge: links[i].bulge, start_width, end_width }
};
let mut vs: Vec<PolyVertex> = (0..first).map(|i| vertex(i, head)).collect();
vs.extend(own);
if last + 1 < links.len() {
// The source's end vertex starts the first piece after it.
let v = vertex(last + 1, tail);
if let Some(end) = vs.last_mut() {
(end.bulge, end.start_width, end.end_width) = (v.bulge, v.start_width, v.end_width);
}
vs.extend((last + 2..links.len()).map(|i| vertex(i, tail)));
vs.push(PolyVertex { p: links.last()?.ends.1, start_width: tail.0, end_width: tail.1, ..Default::default() });
}
if other_polyline && let Some(end) = vs.last_mut() {
(end.start_width, end.end_width) = (0.0, 0.0);
}
if closed {
// The last vertex is the first one again.
vs.pop();
}
Some(cadcraft_doc::LwPolyline { vertices: vs, closed, const_width: if other_polyline { 0.0 } else { sp.const_width }, ..sp.clone() })
}
/// JOIN onto the first object (the source) as AutoCAD 2024 does when the others all lie on its
/// line or its circle: gaps and overlaps are bridged and the source keeps its handle.
///
/// - Lines on the source's line make one line, from the source's start end to the farthest
/// point the way it runs (and back past its start if one reaches behind it).
/// - Arcs on the source's circle join counterclockwise from the source's start to the farthest
/// end; arcs that reach all the way round make a circle, a new object in their place.
///
/// `None` when the objects aren't all of one of those kinds.
fn join_on_source(s: &mut Session, hs: &[Handle]) -> Result<Option<Handle>> {
let d = s.doc()?;
let ents: Vec<std::sync::Arc<Entity>> = hs.iter().filter_map(|h| d.entity(*h).cloned()).collect();
let [src, rest @ ..] = &ents[..] else { return Ok(None) };
if rest.is_empty() || ents.len() != hs.len() {
return Ok(None);
}
// AutoCAD 2024 takes lines less than 1e-6 off the source's line, and arcs less than 1e-6
// off its centre and radius, at any size of coordinates (measured at 0, 1000 and 2.4e6), and
// makes a circle of arcs that come round to less than 1e-6 radians from the source's start.
let tol = 1e-6;
let kind = match &src.kind {
EntityKind::Line(l) => {
let (a, b) = (l.a.xy(), l.b.xy());
let len = a.dist(b);
let lines: Vec<&cadcraft_doc::Line> = rest
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(o) => Some(o),
_ => None,
})
.collect();
let level = |z: f64| (z - l.a.z).abs() < tol;
if lines.len() != rest.len() || len <= 0.0 || !level(l.b.z) || !lines.iter().all(|o| level(o.a.z) && level(o.b.z)) {
return Ok(None);
}
let u = (b - a) * (1.0 / len);
let on_line = |p: Vec2| (p - a).cross(u).abs() < tol;
if !lines.iter().all(|o| on_line(o.a.xy()) && on_line(o.b.xy())) {
return Ok(None);
}
let ts = lines.iter().flat_map(|o| [o.a.xy(), o.b.xy()]).map(|p| (p - a).dot(u)).chain([0.0, len]);
let (t0, t1) = ts.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), t| (lo.min(t), hi.max(t)));
let at = |t: f64| (a + u * t).to3(l.a.z);
EntityKind::Line(cadcraft_doc::Line { a: at(t0), b: if t1 == len { l.b } else { at(t1) } })
}
EntityKind::Arc(g) => {
let arcs: Vec<&cadcraft_doc::Arc> = rest
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Arc(o) => Some(o),
_ => None,
})
.collect();
let Some(far) = arc_reach(g, &arcs, tol).filter(|_| arcs.len() == rest.len()) else { return Ok(None) };
if far > cadcraft_geom::TAU - tol {
let circle = Entity {
handle: Handle(0),
common: src.common.clone(),
kind: EntityKind::Circle(cadcraft_doc::Circle { center: g.center, radius: g.radius }),
};
// In the source's space, whichever space is current.
let space = d.space_of(src.handle).unwrap_or_else(|| s.space());
let doc = s.doc_mut()?;
for h in hs {
doc.remove_entity(*h);
}
let nh = doc.new_handle();
if let Some(st) = doc.space_mut(&space) {
st.push(Entity { handle: nh, ..circle });
}
s.set_selection(Vec::new());
return Ok(Some(nh));
}
let end = if far > cadcraft_geom::ccw_sweep(g.start, g.end) { norm_angle(g.start + far) } else { g.end };
EntityKind::Arc(cadcraft_doc::Arc { end, ..g.clone() })
}
_ => return Ok(None),
};
let src_h = src.handle;
let doc = s.doc_mut()?;
for h in hs.iter().filter(|h| **h != src_h) {
doc.remove_entity(*h);
}
doc.modify_entity(src_h, |e| e.kind = kind)?;
s.set_selection(Vec::new());
Ok(Some(src_h))
}
pub(super) fn run_join(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
if p.get("close").and_then(Value::as_bool) == Some(true) {
+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
}
+76 -21
View File
@@ -19,7 +19,8 @@ fn offsettable(k: &EntityKind) -> bool {
}
/// Offset an entity by `dist` towards `side`. Returns the new geometry.
pub(crate) fn offset_kind(k: &EntityKind, dist: f64, side: Vec2) -> Option<EntityKind> {
/// `gap` is OFFSETGAPTYPE, used by polylines only.
pub(crate) fn offset_kind(k: &EntityKind, dist: f64, side: Vec2, gap: i64) -> Option<EntityKind> {
match k {
EntityKind::Line(l) => {
let ln = Line::new(l.a.xy(), l.b.xy());
@@ -64,7 +65,7 @@ pub(crate) fn offset_kind(k: &EntityKind, dist: f64, side: Vec2) -> Option<Entit
let t = nearest.tangent(0.5);
let left = t.cross(side - c) > 0.0;
let d = if left { dist } else { -dist };
offset_polyline(&pl, d).map(|vs| {
offset_polyline(&pl, d, gap).map(|vs| {
let mut k = lwpoly(vs, p.closed);
if let EntityKind::LwPolyline(n) = &mut k {
n.const_width = p.const_width;
@@ -135,35 +136,50 @@ pub(super) fn offset_points(pts: &[Vec2], d: f64, closed: bool) -> Vec<Vec2> {
out
}
/// Offset a polyline: offset each segment, then join neighbours at their intersections.
pub(crate) fn offset_polyline(pl: &Polyline, d: f64) -> Option<Vec<PolyVertex>> {
let segs: Vec<Segment> = pl.segments().iter().filter_map(|s| s.offset(d)).collect();
if segs.is_empty() {
/// Offset a polyline: offset each segment, then join neighbours at their intersections. `gap`
/// (OFFSETGAPTYPE) fills the gap at the outside of a corner between two lines: 0 extends both
/// copies to meet, 1 inserts an arc of radius `d` centred on the corner, 2 inserts a chamfer line.
pub(crate) fn offset_polyline(pl: &Polyline, d: f64, gap: i64) -> Option<Vec<PolyVertex>> {
let pairs: Vec<(Segment, Segment)> = pl.segments().iter().filter_map(|s| s.offset(d).map(|o| (*s, o))).collect();
if pairs.is_empty() {
return None;
}
let segs: Vec<Segment> = pairs.iter().map(|(_, o)| *o).collect();
let n = segs.len();
// Where each offset segment starts after joining it to the previous one.
let mut starts: Vec<Vec2> = Vec::with_capacity(n);
// At each joint: where the previous copy ends, an optional fill vertex (its start and bulge),
// and where this copy starts.
let mut joints: Vec<(Vec2, Option<PolyVertex>, Vec2)> = Vec::with_capacity(n);
for i in 0..n {
let s = segs.get(i)?;
starts.push(if i == 0 && !pl.closed {
s.start()
joints.push(if i == 0 && !pl.closed {
(s.start(), None, s.start())
} else {
let prev = segs.get((i + n - 1) % n)?;
join_point(prev, s).unwrap_or(s.start())
let corner = pairs.get(i)?.0.start();
// Only two segments that meet in the source have a corner to fill (a collapsed arc
// between them leaves none).
let adjacent = pairs.get((i + n - 1) % n)?.0.end().near(corner, 1e-9);
match gap_fill(prev, s, corner, d.abs(), if adjacent { gap } else { 0 }) {
Some((a, fill, b)) => (a, Some(fill), b),
None => {
let j = join_point(prev, s).unwrap_or(s.start());
(j, None, j)
}
}
});
}
let mut verts: Vec<PolyVertex> = Vec::new();
for i in 0..n {
let s = segs.get(i)?;
let start = *starts.get(i)?;
let end = if i + 1 < n {
*starts.get(i + 1)?
let start = joints.get(i)?.2;
let next = if i + 1 < n {
joints.get(i + 1)
} else if pl.closed {
*starts.first()?
joints.first()
} else {
s.end()
None
};
let end = next.map_or(s.end(), |j| j.0);
let bulge = match s {
Segment::Line(_) => 0.0,
Segment::Arc { arc, ccw } => {
@@ -179,6 +195,9 @@ pub(crate) fn offset_polyline(pl: &Polyline, d: f64) -> Option<Vec<PolyVertex>>
}
};
verts.push(PolyVertex { p: start, bulge, start_width: 0.0, end_width: 0.0 });
if let Some(fill) = next.and_then(|j| j.1) {
verts.push(fill);
}
}
if !pl.closed {
verts.push(PolyVertex::new(segs.last()?.end()));
@@ -186,6 +205,40 @@ pub(crate) fn offset_polyline(pl: &Polyline, d: f64) -> Option<Vec<PolyVertex>>
Some(verts)
}
/// The OFFSETGAPTYPE fill between the offset copies `a` and `b` of two lines meeting at `corner`,
/// when the copies leave a gap (the outside of the turn): where `a` ends, the fill vertex, and
/// where `b` starts. `None` keeps the extended join.
fn gap_fill(a: &Segment, b: &Segment, corner: Vec2, d: f64, gap: i64) -> Option<(Vec2, PolyVertex, Vec2)> {
let (Segment::Line(la), Segment::Line(lb)) = (a, b) else { return None };
if gap == 0 || la.a.near(la.b, 1e-12) || lb.a.near(lb.b, 1e-12) || a.end().near(b.start(), 1e-9) {
return None;
}
let (ta, tb) = (la.dir(), lb.dir());
let j = join_point(a, b)?;
if (j - la.b).dot(ta) <= 1e-9 {
return None;
}
let (ra, rb) = (la.b - corner, lb.a - corner);
match gap {
1 => {
let sweep = ra.cross(rb).atan2(ra.dot(rb));
Some((la.b, PolyVertex::with_bulge(la.b, cadcraft_geom::arc_to_bulge(sweep)), lb.a))
}
2 => {
// The chamfer is the line at distance `d` from the corner, square to the bisector.
let m = (ra + rb).normalized();
let (ka, kb) = (ta.dot(m), tb.dot(m));
if ka.abs() < 1e-9 || kb.abs() < 1e-9 {
return None;
}
let pa = la.b + ta * ((d - ra.dot(m)) / ka);
let pb = lb.a + tb * ((d - rb.dot(m)) / kb);
Some((pa, PolyVertex::new(pa), pb))
}
_ => None,
}
}
fn join_point(a: &Segment, b: &Segment) -> Option<Vec2> {
if a.end().near(b.start(), 1e-9) {
return Some(b.start());
@@ -202,7 +255,8 @@ pub(super) fn run_offset(s: &mut Session, p: &Value) -> Result<Value> {
}
let side = point_req("offset", p, "side")?;
let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| bad("offset", "no such object"))?;
let k = offset_kind(&e.kind, dist.abs(), side).ok_or_else(|| bad("offset", "cannot offset that object"))?;
let gap = s.doc()?.header.i64("OFFSETGAPTYPE", 0);
let k = offset_kind(&e.kind, dist.abs(), side, gap).ok_or_else(|| bad("offset", "cannot offset that object"))?;
let current_layer = match str_param(p, "layer").map(str::to_ascii_lowercase).as_deref() {
None | Some("source") => false,
Some("current") => true,
@@ -321,9 +375,10 @@ impl Interactive for OffsetM {
}
let (erase, current) = offset_options(s);
s.echo(format!(
"Current settings: Erase source={} Layer={} OFFSETGAPTYPE=0",
"Current settings: Erase source={} Layer={} OFFSETGAPTYPE={}",
if erase { "Yes" } else { "No" },
if current { "Current" } else { "Source" }
if current { "Current" } else { "Source" },
s.doc().map(|d| d.header.i64("OFFSETGAPTYPE", 0)).unwrap_or(0)
));
Ok(Step::Continue)
}
@@ -491,7 +546,7 @@ impl Interactive for OffsetM {
.fold(f64::INFINITY, f64::min)
}
};
match offset_kind(&e.kind, dist, p) {
match offset_kind(&e.kind, dist, p, s.doc()?.header.i64("OFFSETGAPTYPE", 0)) {
Some(k) => {
let before = s.state()?.doc.clone();
let (erase, current) = offset_options(s);
@@ -521,6 +576,6 @@ impl Interactive for OffsetM {
Some(x) => x,
None => crate::select::entity_distance(d, e, c, 1e-3),
};
offset_kind(&e.kind, dist, c).into_iter().collect()
offset_kind(&e.kind, dist, c, d.header.i64("OFFSETGAPTYPE", 0)).into_iter().collect()
}
}
+271 -62
View File
@@ -1,4 +1,4 @@
use super::break_join::join;
use super::break_join::{join, join_makes_circle};
use super::explode::explode;
use super::transform::{at_elevation, erase, scale_entities, transform_entities};
use super::{
@@ -20,6 +20,18 @@ pub(super) enum Op {
Join,
}
/// COPY's Array option: asking how many items, then where the second one goes (or, with Fit, the
/// last one).
#[derive(Clone, Copy, PartialEq)]
enum CopyArray {
Off,
Count,
Items { n: u16, fit: bool },
}
/// The most items COPY's Array option makes, the original included, as in AutoCAD.
const MAX_COPY_ITEMS: u16 = 32767;
/// Select objects, then collect the points/values the operation needs.
pub(super) struct SelectThen {
op: Op,
@@ -27,19 +39,25 @@ pub(super) struct SelectThen {
objs: Vec<Handle>,
pts: Vec<Vec2>,
reference: bool,
/// ROTATE Reference: the reference angle (radians), once known. Its first point, and the
/// first of the two new-angle points, are kept in `ref_from`.
/// ROTATE Reference: the reference angle (radians), once known.
ref_angle: Option<f64>,
/// ROTATE Reference: the new angle is given by two points (the `Points` option).
/// ROTATE/SCALE Reference: the new angle/length is given by two points (the `Points` option).
ref_points: bool,
/// SCALE Reference: first point of a reference length given by two points.
/// ROTATE/SCALE Reference: first point of a reference or `Points` pair given by two points.
ref_from: Option<Vec2>,
/// SCALE Reference: the reference length, once known.
ref_len: Option<f64>,
copy_mode: bool,
/// COPY: one copy and done (COPYMODE 1, until the Multiple option), else copies until Exit.
copy_single: bool,
/// COPY: the objects each placement made, so Undo takes back the last one.
copies: Vec<Vec<Handle>>,
copy_array: CopyArray,
ask_erase: bool,
/// JOIN of a single arc or elliptical arc: the prompt asks for arcs to join to it, or cLose.
join_source: Option<Handle>,
/// JOIN of arcs that make a circle: asking whether to.
ask_circle: bool,
}
impl SelectThen {
@@ -55,8 +73,12 @@ impl SelectThen {
ref_from: None,
ref_len: None,
copy_mode: false,
copy_single: false,
copies: Vec::new(),
copy_array: CopyArray::Off,
ask_erase: false,
join_source: None,
ask_circle: false,
}
}
fn apply(&mut self, s: &mut Session) -> Result<Step> {
@@ -84,8 +106,120 @@ impl SelectThen {
}
}
/// JOIN the selected objects and report what they became.
/// 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 {
CopyArray::Count => Prompt::new("Enter number of items to array", Accept::NUMBER),
CopyArray::Items { fit: false, .. } => Prompt::new("Specify second point", Accept::POINT).kw(&["Fit"]).base_opt(base),
CopyArray::Items { fit: true, .. } => Prompt::new("Specify second point", Accept::POINT).kw(&["Array"]).base_opt(base),
CopyArray::Off if self.copies.is_empty() => {
Prompt::new("Specify second point", Accept::POINT).kw(&["Array"]).default("use first point as displacement").base_opt(base)
}
CopyArray::Off => Prompt::new("Specify second point", Accept::POINT).kw(&["Array", "Exit", "Undo"]).default("Exit").base_opt(base),
}
}
/// COPY once the base point is known (AutoCAD 2024, measured): a point places a copy; Enter
/// at the first prompt copies by the base point taken as a displacement, and after a copy
/// ends the command; Array asks for a number of items, the original included, then puts
/// them a second point apart (or, with Fit, spread up to it, Enter keeping them at the
/// base); Undo takes back the last placement. One placement ends a single-copy COPY.
fn copy_input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let Some(base) = self.pts.first().copied() else { return Ok(Step::Continue) };
let placed = match (self.copy_array, i) {
(CopyArray::Count, Input::Enter) => return self.copy_done(s),
(CopyArray::Count, i) => {
// A whole number as typed, from 2 to 32767 whatever the selection: AutoCAD 2024 takes
// +3 and 03 here, refuses 4.0, 1e1, 8/2, 1', 3", 50002 and a point, and doesn't
// apply MAXARRAY (with MAXARRAY 100000, four lines and 26000 items made 104000
// lines; measured).
let n = match i {
Input::Text(t) => t.trim().parse::<u16>().ok().filter(|v| (2..=MAX_COPY_ITEMS).contains(v)),
_ => None,
}
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 2 and {MAX_COPY_ITEMS}.")))?;
// Not AutoCAD's: the copies (items after the first, times the objects) stay within
// ARRAY's own limit, whatever MAXARRAY says, so a large selection can't run out of
// memory.
let copies = u64::from(n - 1).saturating_mul(u64::try_from(self.objs.len()).unwrap_or(u64::MAX));
if copies > cadcraft_doc::MAX_ARRAY_ITEMS {
return Err(EngineError::Other(format!(
"The array would create {copies} objects; the limit is {}. Use fewer items or select fewer objects.",
cadcraft_doc::MAX_ARRAY_ITEMS
)));
}
self.copy_array = CopyArray::Items { n, fit: false };
return Ok(Step::Continue);
}
(CopyArray::Items { n, fit }, Input::Keyword(kw)) if kw == if fit { "Array" } else { "Fit" } => {
self.copy_array = CopyArray::Items { n, fit: !fit };
return Ok(Step::Continue);
}
(CopyArray::Items { n, fit }, i @ (Input::Point(_) | Input::Enter)) => {
let p = if let Input::Point(p) = i { p } else { base };
let step = if fit { (p - base) * (1.0 / f64::from(n - 1)) } else { p - base };
self.copy_array = CopyArray::Off;
let mut made = Vec::new();
for k in 1..n {
match transform_entities(s, &self.objs, &Mat3::translate(step * f64::from(k)), true) {
Ok(hs) => made.extend(hs),
Err(e) => {
// The items made so far are a placement Undo takes back.
self.copies.push(made);
return Err(e);
}
}
}
made
}
(CopyArray::Off, Input::Keyword(kw)) if kw == "Array" => {
self.copy_array = CopyArray::Count;
return Ok(Step::Continue);
}
(CopyArray::Off, Input::Keyword(kw)) if kw == "Undo" => {
if let Some(last) = self.copies.pop() {
let d = s.doc_mut()?;
for h in last {
d.remove_entity(h);
}
if self.copies.is_empty() {
s.echo("Command has been completely undone.");
}
}
return Ok(Step::Continue);
}
(CopyArray::Off, Input::Keyword(kw)) if kw == "Exit" => return self.copy_done(s),
(CopyArray::Off, Input::Enter) if !self.copies.is_empty() => return self.copy_done(s),
(CopyArray::Off, Input::Enter) => {
transform_entities(s, &self.objs, &Mat3::translate(base), true)?;
return self.copy_done(s);
}
(CopyArray::Off, Input::Point(p)) => transform_entities(s, &self.objs, &Mat3::translate(p - base), true)?,
_ => return Ok(Step::Continue),
};
self.copies.push(placed);
if self.copy_single {
return self.copy_done(s);
}
Ok(Step::Continue)
}
fn copy_done(&mut self, s: &mut Session) -> Result<Step> {
s.set_selection(Vec::new());
Ok(Step::Done)
}
/// JOIN the selected objects and report what they became. Arcs that make a circle ask first,
/// as AutoCAD 2024 does.
fn join_now(&mut self, s: &mut Session) -> Result<Step> {
if join_makes_circle(s, &self.objs) {
self.ask_circle = true;
return Ok(Step::Continue);
}
self.join_apply(s)
}
fn join_apply(&mut self, s: &mut Session) -> Result<Step> {
match join(s, &self.objs) {
Ok(h) => {
// Objects outside the joined chain are kept, so count only the ones JOIN consumed
@@ -95,6 +229,9 @@ impl SelectThen {
let what = match h.and_then(|h| d.entity(h)).map(|e| &e.kind) {
Some(EntityKind::Spline(_)) => "spline",
Some(EntityKind::Ellipse(_)) => "ellipse",
Some(EntityKind::Line(_)) => "line",
Some(EntityKind::Arc(_)) => "arc",
Some(EntityKind::Circle(_)) => "circle",
_ => "polyline",
};
s.echo(format!("{n} objects joined into 1 {what}"))
@@ -127,30 +264,47 @@ impl SelectThen {
}
}
/// SCALE Reference: reference length (typed, or two points), then new length (typed, or a
/// point measured from the base point). The scale factor is new length / reference length.
/// SCALE Reference: reference length (typed, or two points), then new length (typed, a point
/// measured from the base point, or two points after `Points`). The scale factor is new length /
/// reference length.
fn scale_reference(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let Some(base) = self.pts.first().copied() else { return Ok(Step::Done) };
match (self.ref_len, self.ref_from, i) {
(None, None, Input::Point(p)) => {
if matches!(&i, Input::Keyword(k) if k == "Copy") {
self.copy_mode = true;
s.echo("Scaling a copy of the selected objects.");
return Ok(Step::Continue);
}
let Some(r) = self.ref_len else {
match (self.ref_from, i) {
(None, Input::Point(p)) => self.ref_from = Some(p),
(None, Input::Text(t)) => self.ref_len = Some(require_length(number(&t))?),
(None, Input::Enter) => self.ref_len = Some(1.0),
(Some(a), Input::Point(p)) => {
self.ref_len = Some(require_length(Some(a.dist(p)))?);
self.ref_from = None;
}
(_, Input::Enter) => return Ok(Step::Done),
_ => {}
}
return Ok(Step::Continue);
};
match (self.ref_points, self.ref_from, i) {
(false, _, Input::Keyword(k)) if k == "Points" => {
self.ref_points = true;
self.ref_from = None;
Ok(Step::Continue)
}
(false, _, Input::Point(p)) => self.scale_by(s, base, base.dist(p) / r),
(false, _, Input::Text(t)) => {
let n = require_length(number(&t))?;
self.scale_by(s, base, n / r)
}
(true, None, Input::Point(p)) => {
self.ref_from = Some(p);
Ok(Step::Continue)
}
(None, None, Input::Text(t)) => {
self.ref_len = Some(require_length(number(&t))?);
Ok(Step::Continue)
}
(None, None, Input::Enter) => {
self.ref_len = Some(1.0);
Ok(Step::Continue)
}
(None, Some(a), Input::Point(p)) => {
self.ref_len = Some(require_length(Some(a.dist(p)))?);
Ok(Step::Continue)
}
(Some(r), _, Input::Point(p)) => self.scale_by(s, base, base.dist(p) / r),
(Some(r), _, Input::Text(t)) => {
let n = require_length(number(&t))?;
(true, Some(a), Input::Point(p)) => {
let n = require_length(Some(a.dist(p)))?;
self.scale_by(s, base, n / r)
}
(_, _, Input::Enter) => Ok(Step::Done),
@@ -158,6 +312,26 @@ impl SelectThen {
}
}
/// The prompt while SCALE Reference collects its lengths.
fn scale_reference_prompt(&self) -> Prompt {
let base = self.pts.first().copied();
match (self.ref_len, self.ref_points, self.ref_from) {
(None, _, None) => Prompt::new("Specify reference length", Accept::POINT_OR_NUMBER).kw(&["Copy"]).default("1"),
(None, _, Some(p)) | (Some(_), true, Some(p)) => Prompt::new("Specify second point", Accept::POINT).base(p),
(Some(_), false, _) => Prompt::new("Specify new length", Accept::POINT_OR_NUMBER).kw(&["Points", "Copy"]).base_opt(base).distance(),
(Some(_), true, None) => Prompt::new("Specify first point", Accept::POINT),
}
}
/// Live factor and rubber-band anchor while SCALE Reference previews with the cursor at `c`.
fn scale_reference_factor(&self, base: Vec2, c: Vec2) -> Option<(f64, Vec2)> {
match (self.ref_len, self.ref_points, self.ref_from) {
(Some(r), false, _) => positive_length(Some(base.dist(c) / r)).map(|f| (f, base)),
(Some(r), true, Some(a)) => positive_length(Some(a.dist(c) / r)).map(|f| (f, a)),
_ => None,
}
}
/// ROTATE Reference: reference angle (typed, or two points), then the new angle (typed, a
/// point measured from the base point, or two points after `Points`). The objects turn by the
/// new angle minus the reference angle.
@@ -308,6 +482,9 @@ impl Interactive for SelectThen {
if self.ask_erase {
return Prompt::new("Erase source objects?", Accept::TEXT).kw(&["Yes", "No"]).default("No");
}
if self.ask_circle {
return Prompt::new("Combined arc segments form a circle. Convert to circle?", crate::cmd::curves::KW).kw(&["Yes", "No"]).default("Yes");
}
if let Some(src) = self.join_source {
let ellipse = s.doc().is_ok_and(|d| matches!(d.entity(src).map(|e| &e.kind), Some(EntityKind::Ellipse(_))));
let msg = if ellipse { "Select elliptical arcs to join to source" } else { "Select arcs to join to source" };
@@ -316,11 +493,7 @@ impl Interactive for SelectThen {
let k = self.pts.len();
let base = self.pts.first().copied();
if self.op == Op::Scale && self.reference {
return match (self.ref_len, self.ref_from) {
(Some(_), _) => Prompt::new("Specify new length", Accept::POINT_OR_NUMBER).base_opt(base),
(None, Some(p)) => Prompt::new("Specify second point", Accept::POINT).base(p),
(None, None) => Prompt::new("Specify reference length", Accept::POINT_OR_NUMBER).default("1"),
};
return self.scale_reference_prompt();
}
if self.op == Op::Rotate && self.reference {
return self.rotate_reference_prompt();
@@ -328,7 +501,7 @@ impl Interactive for SelectThen {
match (self.op, k) {
(Op::Move | Op::Copy, 0) => Prompt::new("Specify base point", Accept::POINT).kw(&["Displacement"]),
(Op::Move, _) => Prompt::new("Specify second point or <use first point as displacement>", Accept::POINT).base_opt(base),
(Op::Copy, _) => Prompt::new("Specify second point", Accept::POINT).kw(&["Array", "Exit", "Undo"]).base_opt(base),
(Op::Copy, _) => self.copy_prompt(base),
(Op::Rotate | Op::Scale, 0) => Prompt::new("Specify base point", Accept::POINT),
// ROTATE and SCALE offer the angle/factor used last time.
(Op::Rotate, _) => {
@@ -361,6 +534,14 @@ impl Interactive for SelectThen {
}
}
}
// No leaves every arc as it is (AutoCAD 2024, measured).
if self.ask_circle {
return match &i {
Input::Keyword(k) if k == "No" => Ok(Step::Done),
Input::Keyword(_) | Input::Enter => self.join_apply(s),
_ => Err(EngineError::Other("Invalid option keyword.".into())),
};
}
if let Some(src) = self.join_source {
return self.join_source_input(s, src, i);
}
@@ -388,10 +569,6 @@ impl Interactive for SelectThen {
self.reference = true;
Ok(Step::Continue)
}
(Op::Copy, _, Input::Keyword(kw)) if kw == "Exit" => {
s.set_selection(Vec::new());
Ok(Step::Done)
}
(_, 0, Input::Point(p)) => {
self.pts.push(p);
Ok(Step::Continue)
@@ -408,15 +585,7 @@ impl Interactive for SelectThen {
s.set_selection(Vec::new());
Ok(Step::Done)
}
(Op::Copy, _, Input::Point(p)) => {
let d = p - self.pts[0];
transform_entities(s, &self.objs, &Mat3::translate(d), true)?;
Ok(Step::Continue)
}
(Op::Copy, _, Input::Enter) => {
s.set_selection(Vec::new());
Ok(Step::Done)
}
(Op::Copy, _, i) => self.copy_input(s, i),
(Op::Rotate, 1, inp @ (Input::Point(_) | Input::Text(_) | Input::Enter)) => {
let a = match inp {
Input::Point(p) => self.pts[0].angle_to(p),
@@ -468,16 +637,15 @@ impl Interactive for SelectThen {
return Vec::new();
}
let Some(base) = self.pts.first().copied() else { return Vec::new() };
let m = match self.op {
Op::Move | Op::Copy => Mat3::translate(c - base),
Op::Rotate => Mat3::rotate_about(base, base.angle_to(c)),
Op::Scale if !self.reference => Mat3::scale_about(base, base.dist(c).max(1e-9)),
Op::Scale => match self.ref_len.and_then(|r| positive_length(Some(base.dist(c) / r))) {
Some(f) => Mat3::scale_about(base, f),
None if self.ref_len.is_some() => 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),
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
_ => return Vec::new(),
};
let Ok(d) = s.doc() else { return Vec::new() };
@@ -496,7 +664,7 @@ impl Interactive for SelectThen {
k
})
.collect();
out.push(line(base, c));
out.push(line(rubber_from, c));
out
}
/// Separate shared GPU transforms from objects that need an individual MIRROR preview.
@@ -505,15 +673,18 @@ impl Interactive for SelectThen {
return None;
}
let base = self.pts.first().copied()?;
let matrix = match self.op {
Op::Move | Op::Copy => Mat3::translate(c - base),
Op::Rotate => Mat3::rotate_about(base, base.angle_to(c)),
Op::Scale if !self.reference => Mat3::scale_about(base, base.dist(c).max(1e-9)),
Op::Scale => Mat3::scale_about(base, self.ref_len.and_then(|r| positive_length(Some(base.dist(c) / r)))?),
Op::Mirror if !self.ask_erase => Mat3::mirror(base, c),
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(base, c)];
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 });
}
@@ -542,11 +713,13 @@ impl Interactive for SelectThen {
pub(super) struct DisplaceM {
inner: SelectThen,
displacement: bool,
/// COPY's mOde option: asking Single or Multiple.
ask_mode: bool,
}
impl DisplaceM {
pub(super) fn new(op: Op) -> Self {
DisplaceM { inner: SelectThen::new(op), displacement: false }
DisplaceM { inner: SelectThen::new(op), displacement: false, ask_mode: false }
}
/// At "Specify base point": objects selected, no point yet.
fn at_base(&self) -> bool {
@@ -559,14 +732,26 @@ impl Interactive for DisplaceM {
self.inner.name()
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.inner.copy_single = self.inner.op == Op::Copy && s.settings.copymode;
self.inner.begin(s)
}
fn prompt(&self, s: &Session) -> Prompt {
if self.displacement {
return Prompt::new("Specify displacement", Accept::POINT).default("0,0");
}
if self.ask_mode {
let current = if s.settings.copymode { "Single" } else { "Multiple" };
return Prompt::new("Enter a copy mode option", crate::cmd::curves::KW).kw(&["Single", "Multiple"]).default(current);
}
if self.at_base() {
return Prompt::new("Specify base point", Accept::POINT).kw(&["Displacement"]).default("Displacement");
// COPY: mOde sets COPYMODE; Multiple, offered while it is single, copies until Exit
// this once.
let kw: &[&str] = match self.inner.op {
Op::Copy if self.inner.copy_single => &["Displacement", "mOde", "Multiple"],
Op::Copy => &["Displacement", "mOde"],
_ => &["Displacement"],
};
return Prompt::new("Specify base point", Accept::POINT).kw(kw).default("Displacement");
}
self.inner.prompt(s)
}
@@ -583,10 +768,34 @@ impl Interactive for DisplaceM {
s.set_selection(Vec::new());
return Ok(Step::Done);
}
if self.ask_mode {
match &i {
Input::Keyword(k) if k == "Single" || k == "Multiple" => s.settings.copymode = k == "Single",
Input::Enter => {}
_ => return Ok(Step::Continue),
}
// The mode shown is the mode this COPY runs in, Enter keeping it.
self.inner.copy_single = s.settings.copymode;
self.ask_mode = false;
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);
}
if self.at_base() && self.inner.op == Op::Copy {
match &i {
Input::Keyword(k) if k == "mOde" => {
self.ask_mode = true;
return Ok(Step::Continue);
}
Input::Keyword(k) if k == "Multiple" => {
self.inner.copy_single = false;
return Ok(Step::Continue);
}
_ => {}
}
}
self.inner.input(s, i)
}
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
+55 -4
View File
@@ -3,6 +3,7 @@ use super::{
Accept, Entity, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelectKind, SelectMode, Session, Step, Value, Vec2, bad, json,
line, points_param,
};
use cadcraft_geom::Arc;
/// An area whose vertices STRETCH moves: a window's box, or a polygon closed back to its first
/// point.
@@ -40,6 +41,18 @@ fn add_mline_vertex_hits(s: &Session, area: &StretchArea, hs: &mut Vec<Handle>)
}
}
/// The bulge that keeps an arc's height (bulge × chord / 2) when its chord changes length; none
/// once the chord collapses to a point, which has no arc left to keep.
fn keep_height(bulge: f64, old_chord: f64, new_chord: f64) -> f64 {
if new_chord.is_nan() || new_chord <= 1e-12 {
0.0
} else if old_chord.is_finite() {
bulge * old_chord / new_chord
} else {
bulge
}
}
/// Move the vertices of `e` that lie inside any of the areas `wins` by `d` (STRETCH).
fn stretch_entity(e: &mut Entity, wins: &[StretchArea], d: Vec2) {
let inside = |p: Vec2| wins.iter().any(|a| a.contains(p));
@@ -55,18 +68,56 @@ fn stretch_entity(e: &mut Entity, wins: &[StretchArea], d: Vec2) {
mv(&mut l.b);
}
EntityKind::LwPolyline(pl) => {
let old: Vec<Vec2> = pl.vertices.iter().map(|v| v.p).collect();
for v in &mut pl.vertices {
if inside(v.p) {
v.p += d;
}
}
// An arc segment keeps its height (bulge × chord / 2) as its ends move, as in AutoCAD.
let n = pl.vertices.len();
let segs = if pl.closed { n } else { n.saturating_sub(1) };
for i in 0..segs {
let j = (i + 1) % n;
let (Some(a0), Some(b0), Some(b1)) = (old.get(i), old.get(j), pl.vertices.get(j).map(|v| v.p)) else { continue };
if let Some(v) = pl.vertices.get_mut(i)
&& v.bulge != 0.0
{
v.bulge = keep_height(v.bulge, a0.dist(*b0), v.p.dist(b1));
}
}
}
EntityKind::MLine(m) => m.vertices.iter_mut().for_each(|v| mv(&mut v.p)),
EntityKind::Arc(a) => {
// Arcs keep their shape: move when the centre is inside.
if inside(a.center.xy()) {
a.center.x += d.x;
a.center.y += d.y;
// AutoCAD moves the ends inside the area and keeps the arc's height (bulge × chord / 2);
// the centre alone moves nothing. An end stretched onto the other leaves the arc as it
// was: AutoCAD collapses it into a zero-radius arc at that point (radius 6e-16, start
// 180°, end 0°), an object nothing can draw or pick, which CADCraft does not make.
let g = Arc::new(a.center.xy(), a.radius, a.start, a.end);
let (s0, e0) = (g.start_point(), g.end_point());
let (s_in, e_in) = (inside(s0), inside(e0));
let (s1, e1) = (if s_in { s0 + d } else { s0 }, if e_in { e0 + d } else { e0 });
if s_in && e_in {
// Both ends move: the arc moves whole (a full sweep has no chord to rebuild from).
(a.center.x, a.center.y) = (a.center.x + d.x, a.center.y + d.y);
} else if (s_in || e_in)
&& let Some((r, _)) =
cadcraft_geom::bulge_to_arc(s1, e1, keep_height(cadcraft_geom::arc_to_bulge(g.sweep()), s0.dist(e0), s1.dist(e1)))
{
(a.center.x, a.center.y) = (r.center.x, r.center.y);
(a.radius, a.start, a.end) = (r.radius, r.start, r.end);
}
}
// Control points inside the area move (AutoCAD).
EntityKind::Spline(sp) if sp.fit.is_empty() => sp.control.iter_mut().filter(|p| inside(**p)).for_each(|p| *p += d),
// A spline built from fit points: the fit points inside the area move and it is fitted
// through them again, its fit data kept (AutoCAD 2024). All of them inside, it moves.
EntityKind::Spline(sp) => {
if sp.fit.iter().all(|p| inside(*p)) {
sp.transform(&Mat3::translate(d));
} else if sp.fit.iter().any(|p| inside(*p)) {
let fit: Vec<Vec2> = sp.fit.iter().map(|p| if inside(*p) { *p + d } else { *p }).collect();
*sp = sp.refit(&fit, sp.closed);
}
}
EntityKind::Solid(so) | EntityKind::Trace(so) => so.corners.iter_mut().for_each(mv),
@@ -84,6 +84,7 @@ pub(crate) fn at_elevation(s: &Session, p: Vec2) -> Vec3 {
fn edit_entities(s: &mut Session, hs: &[Handle], copy: bool, edit: impl Fn(&mut Entity)) -> Result<Vec<Handle>> {
let d = s.doc_mut()?;
let mut out = Vec::new();
let mut copies = Vec::new();
for h in hs {
let Some(sp) = d.space_of(*h) else { continue };
if copy {
@@ -94,6 +95,7 @@ fn edit_entities(s: &mut Session, hs: &[Handle], copy: bool, edit: impl Fn(&mut
if let Some(st) = d.space_mut(&sp) {
st.push(ne);
out.push(nh);
copies.push((*h, nh));
}
} else {
let locked = d.entity(*h).and_then(|e| d.layer(&e.common.layer)).is_some_and(|l| l.locked);
@@ -104,6 +106,9 @@ fn edit_entities(s: &mut Session, hs: &[Handle], copy: bool, edit: impl Fn(&mut
out.push(*h);
}
}
if copy && !copies.is_empty() {
crate::cmd::groups::replicate_groups_for_copies(d, &copies);
}
Ok(out)
}
+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.

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