Compare commits

...
Author SHA1 Message Date
FredApps 8698649da1 Merge main into stack/e6
Conflict: crates/engine/tests/it/main.rs (both new test modules kept: legacy_sysvars and lisp_answer_by_frames).
2026-12-03 06:25:12 +01:00
FredApps a6add77c5a Drop #3580 from this landing
Reverts the Merge #3580 commit (0d70d25f, first parent) and the landing fix that moved its
tests into tests/it (4ecd4aed). #3580 is not ready (changes still requested on 9bbe7b69) and lands
on its own. #3601, #3497 and #3503 stay.
2026-12-03 05:45:02 +01:00
Tanish Manku 4ecd4aed42 Landing fix: #3580's tests join each crate's tests/it binary (rule 30) 2026-12-02 14:19:42 -07:00
Tanish Manku 636dd26f07 Merge #3503 2026-12-02 14:19:34 -07:00
Tanish Manku 0d70d25f07 Merge #3580 2026-12-02 14:19:23 -07:00
Tanish Manku 15c8926c97 Merge #3497 2026-12-02 14:19:16 -07:00
Tanish Manku 300a64f711 Merge #3601 2026-12-02 14:19:13 -07:00
Magzhan ZhakudaandClaude Opus 5.5 27a9b91f3c Vertex identifier tests: move into the io harness (tests/it)
AGENTS.md rule 30: one integration test binary per crate. The five cases
move unchanged into crates/io/tests/it/lwpolyline_vertex_ids.rs, registered
in main.rs under the same target guard the separate binary had.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 15:50:44 +05:00
Magzhan Zhakuda e48f8805a5 Merge remote-tracking branch 'origin/main' into fix/lwpolyline-vertex-ids
# Conflicts:
#	crates/doc/src/foreign.rs
2026-12-02 15:44:22 +05:00
FredApps 9bbe7b69a3 Merge remote-tracking branch 'origin/main' into yan-3580 2026-12-02 08:59:06 +01:00
FredApps 8cde239e64 Text Style: Apply writes only the fields the dialog changed; a refused number says why
Apply and the unsaved-changes Yes sent the whole staged style, so a change made to another
field of the style by another route since the edit began was written back over. They now send
only the fields that differ from the style as the first edit found it.

A refused height, width factor or oblique angle went back to its value without a word. The
dialog now says what the field accepts, in a live region, until an entry is accepted. The shared
expr_field is unchanged.
2026-12-02 08:58:58 +01:00
code-compliant 15c3c9564a Answer two review findings: continue text with a usable height, name annotative rows
Enter at TEXT's start point does not continue with a height that neither the last text nor TEXTSIZE can give. An annotative style's row says so in its accessible name, which starts with the visible style name. The Escape test for another window now fails if any control of the dialog takes the focus.
2026-12-02 10:37:25 +08:00
FredApps f288082ff3 Merge main into ACADVER fix, keeping shared test registration 2026-12-02 02:35:24 +01:00
code-compliant 0fd046c4c1 Keep a click on an editor over the drawing from leaving the keys with the dialog
The grace for a closed list's last focused item now applies only to a list that a key closed. A list that a click closed gives the focus to what was clicked, so a click on an editor over the drawing while a list was open takes the keys from the dialog at once.
2026-12-02 07:20:37 +08:00
code-compliant 7bd33b7ff1 Give a closed list's focus back only to a control that is still there and enabled
The focus owed to the control that opened a list or menu is given two passes after the list closed, once what the choice did has been drawn: to the control if it is still there and enabled, else to the chosen style. A button the choice turned off, a row it hid and a style it deleted no longer take the focus back. The dialog keeps the keys through the passes in which the closed list's last item still looks focused.
2026-12-02 07:05:34 +08:00
code-compliant 9ce7cde286 Put the focus on the chosen style after Delete from the style list's menu
The menu's Delete removes the row that held the focus, as the Delete button does, so the focus goes to the chosen style here too.
2026-12-02 06:39:51 +08:00
code-compliant 0cf540495f Put the focus on the chosen style when Apply, Set Current or Delete turns itself off
Each of the three buttons disables itself after it works, and egui drops the focus of a control that turns off, so a person using the keyboard was left with no focused control. The focus now goes to the chosen style.
2026-12-02 06:23:44 +08:00
code-compliant 6050f3c396 Let the window under the pointer decide who has the keys, even when a list is open
A press counts for the dialog only when the dialog is the topmost window under the pointer, takes nothing from an item of an open list or menu, and takes the keys from the dialog for any other window, the drawing or a bar. So a click on another window's title bar that closes an open list no longer leaves the next Escape with the dialog.
2026-12-02 06:07:15 +08:00
code-compliant 3371028cdf Add a Rename button to Text Style and tighten who has the keys
Rename is now a button beside Delete, so it can be reached by the keyboard, and its field takes the focus when it shows; the focus returns to the styles when the rename ends. A choice made by key in the style filter list and the font style list closes the list. The dialog counts focus on a foreground layer as its own only while a list or menu is open, so an editor over the drawing keeps its Escape; and a click counts only when the dialog is the topmost window under the pointer, so a window over the dialog does not give it the keys.
2026-12-02 05:47:15 +08:00
code-compliant 206d40bc0d Give the focus back after any list or menu closes by a key, and skip a return target that is gone
One check after the dialog draws replaces the three per-box helpers: when a list or menu closed by Escape, Enter or Space while the dialog had the keys, the focus returns to the control of the dialog that last had it. A popup that closed earlier in the same pass still counts as open for the Escape test. The return target saved when the dialog opened is used only if it still exists (a menu item that opened the dialog is gone). The key ownership is updated before a drawing switch rebuilds the state.
2026-12-02 05:19:42 +08:00
code-compliant f796d5c8fc Remember who has the keys in the Text Style dialog
The dialog has the keys while the focus is in it, and keeps them when egui drops the focus (an Escape, a click on blank space, a control that goes away, a list or menu that closes). The focus moving to another window, or a click outside the dialog, takes them away, so an Escape for a command running in the drawing, or for another window, is left alone. A list closed by Escape, Enter or Space gives the focus back to its box only while the dialog has the keys.
2026-12-02 04:38:41 +08:00
code-compliant 03bf451124 Give the focus back to a combo box when Escape closes its list
egui drops the focus as an Escape arrives, so after the font or style list closed, nothing held the focus and the next Escape did not reach the dialog. The three lists now return the focus to their box when Escape closes them. One long line is split as rustfmt wants.
2026-12-02 04:15:50 +08:00
code-compliant 2659b44569 Keep the Text Style dialog's focus handling to its own keys, and name its preview
Escape closes or cancels something in the dialog only when the focus was in it one pass earlier (egui drops the focus as the key arrives), so an Escape for a command running in the drawing is left to the command. The dialog takes the focus again each time it opens, including after another dialog replaced it, and after a drawing switch removed the field that held it; the focus returns to what had it only if the dialog held it. When the filter hides the chosen style, the focus goes to the first style shown, or the filter. The style preview is named by its heading. The Tab test now checks every enabled control and the opposite order back, and the focus-return test checks the focus itself.
2026-12-02 03:53:54 +08:00
code-compliant e5f62c9546 Let Escape cancel the font list, the New page or a rename before it closes Text Style
The font list closes itself on Escape while the dialog draws, so the check that left it alone saw no open popup and the dialog closed as well. The state is now read before the dialog draws. On the New page and during a rename, Escape now acts as Cancel and puts the focus back on the styles, as it already did for the unsaved-changes question.
2026-12-02 03:10:01 +08:00
code-compliant f5a70b0e98 Regenerate the parity checklist for the new style commands
cargo xtask parity now counts 488 registered commands (the Text Style
commands this pull request adds among them) instead of 482. The file is
generated, so it is regenerated rather than edited.
2026-12-02 00:55:45 +08:00
code-compliant 13aa3a5cc6 test(acadver): move the ACADVER tests into the engine's shared integration binary
The five cases move from tests/acadver.rs to tests/it/acadver.rs unchanged, apart from the I/O
setup: the save case installs the suite's real file hooks (refedit_xref::hooks) in place of its
own copy, and uses a folder under Cargo's temporary directory for integration tests.
2026-12-01 23:47:22 +08:00
code-compliant 3fe6d7e954 test(sysvars): make the TEXTEVAL session check able to fail; put the $ names note on its list 2026-12-01 23:47:07 +08:00
code-compliant 5950cbce24 Keep the Chinese command labels main requires complete
Moving these two rows out made chinese_menus_and_commands_are_fully_translated
fail: both are labels of engine commands (-style and style.fonts), and that
test, which main already has, requires the zh catalog to name every command.
They stay here rather than moving to the craft-i18n pull request, rather than
weakening the check. The 26 Ukrainian rows are not required by any check and do
move.
2026-12-01 23:41:49 +08:00
code-compliant 88a3069ea2 Let the keyboard use the Text Style dialog and leave it
The dialog opened without taking the focus, so a person without a pointer was
left on the drawing behind it and every key went past the dialog; Escape did
nothing, so the only way out was to find a button; and the style filter was
named "List", which is not the heading a person sees over it.

The dialog now takes the focus on open, and on each page it shows (the
question, the new style's name, the styles). Escape closes it, cancelling an
unanswered question instead of dropping the edits, and closing gives the focus
back to what had it. The filter is named by its heading.

The tests drive open, choose, apply and the question with key events only, and
fail without these changes.
2026-12-01 22:33:56 +08:00
code-compliant 20e2efebf7 fix(sysvars): refuse text from programs and routines, read unknown DIMASSOC as off, save REGENMODE
DIMASO, TEXTEVAL and REGENMODE now take only a number from a program or a routine: numeric text
and booleans are refused. Digits typed at the SETVAR prompt, by hand or through (command), still
work.

DIMASO reads 1 only for DIMASSOC 1 or 2. For any other stored mode it reads 0, and DIMASO 1 turns
associativity on from it too.

A new drawing now has REGENMODE 1 in its header, so a save writes $REGENMODE.
2026-12-01 20:32:12 +08:00
code-compliant a193f64e04 style(tests): keep the module list in order after the merge 2026-12-01 20:32:11 +08:00
code-compliant 494dbd965b Take the new text fields from the previewed style
Main's Text gained backwards and upside_down; the dialog's preview sets them
from the style it draws, so a preview shows the effects the style has.
2026-12-01 20:17:01 +08:00
code-compliant bea1843497 Move the Text Style translations to the craft-i18n pull request
Feature pull requests add English only (AGENTS.md rule 16). The 26 Ukrainian
and 2 Simplified Chinese rows move to storytold/craft-i18n; the English keys,
the UI wiring and the managers/textstyle entry in the translation report stay
here, so the new strings show in English until the translations land.
2026-12-01 16:49:39 +08:00
code-compliant f9284510ea Merge remote-tracking branch 'origin/main' into assist/pr-1089-text-style 2026-12-01 14:53:48 +08:00
code-compliant 723997489a Merge remote-tracking branch 'origin/main' into fix/acadver-release-text 2026-12-01 14:45:18 +08:00
code-compliant 0bc5f721fb Merge remote-tracking branch 'origin/main' into fix/sysvars-dimaso-texteval-regenmode-popups 2026-12-01 14:45:16 +08:00
Magzhan ZhakudaandClaude Opus 5.5 e9ac879b83 Vertex identifiers: compare in the read orientation, skip application groups
Review follow-ups: the points kept with the identifiers are stored as the
reader gives them (mirrored in x when the normal points down), and only that
orientation matches, so a reversed polyline symmetric about x = 0 no longer
keeps its identifiers. A group 91 inside an application's 102 group is not
read as an identifier. The edit test asserts that no identifier is written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 03:17:09 +05:00
Magzhan ZhakudaandClaude Opus 5.5 ffde4b3bbe DXF/DWG: a lightweight polyline keeps its vertex identifiers
A LWPOLYLINE's vertex identifiers (group 91, DXF 2010 and later) were
dropped on read, so every save wrote the polyline without them. Geometric
constraints name a polyline's segments by them. They are now kept with the
entity's extras and written back (DXF 2010+, and DWG through the bridge)
while every vertex is where it was read; once a vertex is moved, added,
removed or reordered, none are written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 02:43:43 +05:00
code-compliant 0db2d73e02 Fix Text Style lookup for extensionless fonts 2026-11-27 21:39:26 +08:00
code-compliant fcb2188143 Test text style changes before selection 2026-11-27 10:00:56 +08:00
code-compliant ab183249f9 Fix text style prompts and preserve drawing edits 2026-11-27 09:51:27 +08:00
code-compliant cd4912b003 Merge main and adapt text style preview 2026-11-27 08:40:51 +08:00
code-compliant 61d1f267cf Merge latest main into text-follows-style 2026-11-26 15:25:39 +08:00
code-compliant b9c9162b14 Merge main into text-follows-style 2026-11-26 15:18:53 +08:00
code-compliant bbf613e944 Merge remote-tracking branch 'origin/main' into fix/sysvars-dimaso-texteval-regenmode-popups
# Conflicts:
#	crates/engine/src/settings.rs
2026-11-25 20:24:51 +08:00
code-compliant 91acccc36a DIMASO: no change leaves the drawing unmodified; its remembered mode is not a variable and not a roundtrip loss 2026-11-25 20:04:14 +08:00
code-compliant dec54a9ded DIMASO keeps its remembered mode in the drawing header, so undo restores it; any number of $ before the four names 2026-11-25 18:22:02 +08:00
code-compliant 38a239b1e9 Keep DIMASO's remembered mode per drawing and take the DXF $ names
DIMASO remembered the DIMASSOC mode it turned off in the session settings,
so two open drawings switched between restored each other's mode: with 1 in
the first and 2 in the second, the first came back as 2. The remembered mode
now lives in the drawing's own state, which is not saved, so each open
drawing keeps its own.

$DIMASO, $TEXTEVAL, $REGENMODE and $POPUPS were unknown to getvar, and
setvar took $POPUPS and out-of-range $REGENMODE because only the header's
name lookup stripped the $. Those four names now read, take values and
report read-only exactly as their plain forms, in any case and with spaces
around them. No other name changes: $ANGBASE keeps LISP's radians (only the
plain name converts) and setvar $OSMODE is still not the session's OSMODE.

Tests: DIMASO 1 restores 1 in the first drawing and 2 in the second after
switching; each $ form reads, writes and refuses like its plain name,
including $REGENMODE 2 and $POPUPS; and $ANGBASE, $OSMODE keep their own
handling.
2026-11-25 17:55:54 +08:00
code-compliant 60ac79d4b5 Read and set the legacy variables DIMASO, TEXTEVAL, REGENMODE and POPUPS
DIMASO has no value of its own: it reports DIMASSOC as 0 or 1, and setting it to 0 turns DIMASSOC off while remembering the mode it had, so setting it back to 1 restores that mode (2 when none was seen). Every other value is refused and changes nothing.

TEXTEVAL is a session setting (0 by default) kept for routines that switch it around their prompts; no prompt reads it yet. REGENMODE is the drawing's, 1 by default, and is saved as $REGENMODE (group 70) and read back. POPUPS is read-only and always 1.
2026-11-25 17:35:54 +08:00
code-compliant a65a9b36b5 ACADVER: a $ in the name does not get past read-only; listings show the release text without a drawing 2026-11-25 16:46:10 +08:00
code-compliant 808ae34499 sysvars: ACADVER reports the program's release, not the file version
(getvar "ACADVER") and the GETVAR command gave the drawing's $ACADVER file
version code (AC1015), and SETVAR accepted a new value for it. AutoCAD
documents ACADVER as a read-only text variable holding the program's release
number, which (atof) reads back as a number.

GETVAR now gives "24.3s (CADCraft)" (24.3), and SETVAR and SETVAR's typed name
prompt report it as read-only. The drawing's $ACADVER is untouched, so a
drawing read from a 2000 DXF still saves as one.

Tests: crates/engine/tests/acadver.rs.
2026-11-25 16:07:18 +08:00
SlopapaloozaandClaude Opus 5.5 ebeee968b5 Review fixes: TEXT refuses an unknown justification; its params string
From CodeRabbit's reviews of #1089:
- TEXT's Justify question refuses an answer that is no option ("Invalid
  option keyword.") and asks again, as MTEXT's does; it kept the previous
  justification and went on. Enter leaves the question, as Style's does (it
  asked again, with Esc, which ends TEXT, the only way out).
- The `text` params string lost a line continuation (a run of spaces showed
  in the command list, the CLI and MCP).
- The hostile TEXT input test fails on a caught panic (an internal error)
  instead of discarding every result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:22 -05:00
SlopapaloozaandClaude Opus 5.5 2eaf90df4b New text follows its style: fixed and paper heights, width factor, oblique, TEXT's Style option
TEXT, MTEXT and their JSON forms now set text the way its style says, as AutoCAD does:

- A fixed-height style (height > 0) isn't asked for a height: TEXT goes from the start point
  to the rotation, MTEXT starts at that height, and the JSON forms default to it (an explicit
  `height` is kept). TEXTSIZE is left alone. MTEXT's Style option takes a fixed style's height.
- An annotative style asks for "Specify paper text height", the size the text measures on
  paper.
- New TEXT takes the style's width factor and obliquing angle (it had 1 and 0). Later style
  changes don't change existing text, as in AutoCAD.
- TEXT's Style option works: a style name (made current, then the status line again) or ? to
  list the styles; an unknown name is refused and asked again.
- Enter at TEXT's start point continues directly below the last TEXT in the space, with its
  style, height, rotation and justification, and asks only for the text. With no text in
  the drawing it ends the command.
- The status line gives the height the style fixes and the justification in use.
- `text` takes `style` (default: the current style).

Left for later: Align and Fit take one point, not the baseline's two ends, and
the line being typed isn't previewed on the canvas.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:22 -05:00
SlopapaloozaandClaude Opus 5.5 d8cf5fbb62 -STYLE: imports by name, as #2239 requires
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:22 -05:00
SlopapaloozaandClaude Opus 5.5 bf3e607bd6 Review fixes: font files named in capitals; a rename keeps the waiting edits
From CodeRabbit's reviews of #1083:
- The dialog matched a style's font without its extension ("arialn")
  against the installed file's stem in its own case, so ARIALN.TTF wasn't
  found: the dialog said "not installed" and disabled Font Style for a font
  the renderer finds and draws. The stems are compared in any case now.
- Renaming the chosen style renames the edits waiting for Apply with it, so
  setting every value back no longer leaves Apply on (and Close asking)
  because of the old name.
- The preview is drawn on the drawing area's color (theme::Tokens), as the
  canvas is, instead of white or the raster default.
- Closing the dialog clears a New page or a rename left open, so the next
  STYLE opens on the styles.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 6042310fc7 Review fixes: -STYLE's annotative answers and big font, the dialog's rename
From CodeRabbit's review of #1083 (its finding on the text styles that
dimension overrides use is fixed in #954, where the rename that follows
them is):
- -STYLE: Enter at "Create annotative text style?" says yes, as the prompt
  now shows (it showed the style's current setting while Enter said yes),
  and No asks for the text height again instead of a paper height.
- -STYLE keeps the big font of the style a new one starts from.
- The Text Style dialog's Rename takes only a name the rename accepts, so a
  refused one no longer leaves the selection on no style and drops the
  edits waiting for Apply.
- The dialog test's "Styles in use" check now hides a style that exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 1ec5d20c84 Text Style dialog (STYLE) with installed fonts, and -STYLE
STYLE (ST, Format ▸ Text Style...) opens a Text Style dialog like AutoCAD's: the drawing's
text styles (all, or those in use; annotative ones marked) with a preview of the selected one,
and Set Current, New, Rename and Delete (off for Standard, the current style and styles in
use). The selected style's Font Name and Font Style are picked from the installed fonts by
family and style, with a search; Use Big Font is offered for SHX fonts; Annotative switches
Height to Paper Text Height; the effects are Upside down, Backwards, Width Factor and Oblique
Angle. Edits wait for Apply (one undo step), and choosing another style, Set Current, New or
Close with edits not applied asks whether to save them, as AutoCAD does. Match text
orientation to layout and Vertical are shown unavailable: CADCraft doesn't keep or draw them.

The fonts come from the fonts crate's new installed_fonts(), which reads only each font file's
table directory and naming table (typographic family and subfamily first, English names
preferred), so listing every installed font is cheap (145 faces in about 60 ms on Windows 11).
`style.fonts` gives the same list to MCP clients and scripts.

-STYLE asks in AutoCAD's order, so scripts written for AutoCAD run: name (or ? to list),
font, height or Annotative (then orientation and paper height), width factor, obliquing
angle, backwards, upside down, and vertical for SHX fonts; the style then becomes current.
Unusable answers are asked again. As JSON it takes the style command's parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 723810f768 -DIMSTYLE: imports by name, as #2239 requires; the managers' modules in order
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 60e22f38c4 Review fixes: overrides written as taken, style names, the manager keeps a refused edit
From CodeRabbit's second to fourth reviews of #1042:
- dimstyle.overrides writes each header variable with the value the style
  took (a lineweight named ByLayer is -1), so SETVAR can't refuse one
  halfway through, after `clear` and the earlier values.
- -DIMSTYLE Save and Restore check the name before touching the drawing, so
  a refused call leaves no empty undo step, and Apply to objects none of
  which is a dimension makes none either.
- New dimension styles and renames take the names -DIMSTYLE takes (no `~`,
  which its Restore reads as "compare with", and no wildcards), in the
  `dimstyle` and `dimstyle.rename` commands and in the manager's New and
  Rename, which ask the engine (cmd::usable_dim_style_name). A style read
  from a file keeps its name.
- The manager's OK goes back to the list only when its commands succeed: a
  value the engine refuses keeps the editing page open with every edit.
- Compare offers the style overrides too (the current style with them), so
  comparing them with their style shows what they change.
- The manager opens on its list again after its window is closed, not on the
  page left open, and its preview is drawn on the drawing area's color
  (theme::Tokens), as the canvas is.
- The manager's Rename takes only a name the rename accepts, so renaming a
  style onto another's name no longer leaves the list on that other style.
- The -DIMSTYLE tests apply to a line that's there, and the hostile-input
  test fails on a caught panic (an internal error).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 ba63055fd3 Review fixes: -DIMSTYLE matcher, clear after checks, Override's whole set, ~ in names
From CodeRabbit's review of #1042:
- -DIMSTYLE's list matches style names with QSELECT's wildcard matcher (with
  one backtrack point) instead of a recursive one that a pattern of many `*`
  made exponential: one `list` call could hang the session.
- dimstyle.overrides checks every value (against the style alone when
  `clear` is given) before clearing, so a refused call keeps the overrides.
- The Dimension Style Manager's Override sends what differs from the style
  as the whole override set (`clear` first): a value set back to the style's
  drops its override, and undoing every override drops them all.
- A refused answer at -DIMSTYLE asks the same question again (a ~name that
  names no style used to fall back to the first prompt), and words at
  "Select dimension" ask for the dimension again.
- dimstyle.saveas takes names as -DIMSTYLE does, so no `~` (which Restore
  reads as "compare with").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
eldrirandClaude Opus 5.5 cec2e0c04a Dimension Style Manager (DIMSTYLE) and -DIMSTYLE
DIMSTYLE (D, DST, DDIM, Format and Dimension menus) opens AutoCAD's Dimension Style Manager:
the drawing's styles (all, or those in use) with the current style's <style overrides> under it,
a preview drawn with the chosen settings, and Set Current, New, Modify, Override, Compare,
Rename and Delete. Modify, Override and New edit every style variable on AutoCAD's seven tabs
(Lines, Symbols and Arrows, Text, Fit, Primary Units, Alternate Units, Tolerances), from the
engine's table of dimension properties; a fixed-height text style shows the height it fixes.
OK changes the style, sets the current style's overrides, or creates the new style, each as one
undo step; programmatic calls never open the dialog.

-DIMSTYLE asks as AutoCAD does: ANnotative, Save (asks before redefining a name in use),
Restore (~name lists how a style differs from the current settings, or pick a dimension),
STatus, Variables, Apply and ?. As JSON it takes {option, ...}. dimstyle.overrides sets the
current style's overrides in one step, and changes nothing when one value is unusable.

An empty leader arrowhead now reads as closed filled, as it is drawn (it read as DIMBLK's).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 8fb5e95f15 Dimension style shortcut commands: imports by name, as #2239 requires
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
eldrirandClaude Opus 5.5 5f4a17cb7c Dimension shortcut menu: Remove Style Overrides, Dimension Style, Precision, Align Text
With dimensions selected, the canvas shortcut menu adds AutoCAD's dimension items:
Align Text ▸ (DIMTEDIT Home/Angle/Left/Center/Right), Dimension Style ▸ (the drawing's styles,
which the selected dimensions take, then Save as New Style), Precision ▸ (DIMDEC, or DIMADEC
for angular dimensions, as overrides) and Remove Style Overrides (available while one of them
overrides its style).

Two commands behind them: dimoverride.clear clears the selected dimensions' overrides, and
dimstyle.saveas makes a new dimension style of a dimension's settings, its overrides included,
gives it to the dimension and clears its overrides (the current style is unchanged). From the
menu it uses the selected dimension, or asks for one, then asks for the name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 1c02f239c3 Properties palette: the described rows' shared inputs in one struct, within #2239's limit
#2239 denies functions with more than seven arguments. `described_row` took eight; the drawing,
the handles, the angle settings and the shared text style now come together as `Rows`, which
the row destructures under the same names. Nothing changes in behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
SlopapaloozaandClaude Opus 5.5 ea0d0e9595 Review fixes: picking the color a row already has is no edit; directions typed as measured
From CodeRabbit's reviews of #994:
- The palette's color menu sent the color number while the row's value is
  the color's name, so picking the color a row already showed still ran
  properties.set (and made an undo step). The menu now compares by name and
  sends nothing for the color already set.
- A rotation (a direction row) typed in the palette is read as the drawing
  measures directions (AngleSettings::direction): a surveyor's bearing such
  as N45dE is absolute, and `<<a` / `<<<a` measure from +X counterclockwise.
  Both were turned by ANGBASE before (or refused, for `<<`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
eldrirandClaude Opus 5.5 5c24bc3dcf Properties palette: text, mtext and dimension rows from properties.describe
The palette draws the groups the engine describes for text, mtext and dimensions after its own
General group, so a dimension's text height (and every other dimension style setting) is edited
there as an override of the selected dimensions, and TEXT and MTEXT get their style,
justification, obliquing, line spacing and position rows. Several objects of one type edit
together, with *VARIES* where they differ.

Rows read values as the command line does (distances in any unit format, angles in the
drawing's angle units); unreadable text and values the engine refuses are reported. An
overridden dimension row has its label in the accent color, and right-clicking it puts the
style's value back. A fixed-height text style's height shows read-only with the reason.

A few engine labels are renamed to translate cleanly and fit the label column; every label the
engine gives the palette has a Ukrainian row, and `cargo xtask i18n` reports any that go missing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
SlopapaloozaandClaude Opus 5.5 5689203791 Dimensions: an explicit text rotation sizes the dimension line's gap
A linear or aligned dimension broke its line around the text as DIMTIH and DIMTOH turn it,
and only then applied an explicit text rotation (DIMTEDIT Angle, or Text rotation in the
Properties palette). Text turned along a vertical dimension line drew over the line, which
left a gap only the height of horizontal text, whatever the text offset (DIMGAP). The gap, the
fit check and the text's clearance now take the text as turned.

Found by testing #1042 (Dievartis). A test checks that no part of the dimension line crosses
text turned along it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
SlopapaloozaandClaude Opus 5.5 b99ea8905e properties.set: one function per kind of object, within #2239's clippy limits
#2239 denies a cognitive complexity over 30 and wildcard imports. properties.set's per-object
edit (complexity 90) becomes one function per kind of object (line, circle, arc, text and its
position, mtext and its line spacing, insert, dimension and its prefix and suffix, hatch) and
one for the properties every object has; what the call checked before any object changes
travels in a `Call`. set.rs and props.rs import by name. Nothing changes in behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
SlopapaloozaandClaude Opus 5.5 c1c97ed00e Review fixes: SOLID drops the gradient, all objects checked first, Align rotation, DIMPOST rows
From CodeRabbit's second to fourth reviews of #954, and codyvogt (from #1371's):
- The Properties pattern edit and HATCHEDIT share one helper
  (hatch::set_pattern) and one rule for the names a hatch takes: SOLID drops
  a gradient fill too, a blank name changes nothing (it's reported as
  ignored), and a name no pattern has is refused, as HATCHEDIT refuses it (a hatch's own
  name matches in any case).
- properties.set refuses a call that names an object that isn't there before
  it edits any, so a bad handle late in the list no longer leaves the
  earlier objects edited.
- A prefix or suffix edit goes into the DIMPOST/DIMAPOST the dimension has
  after the call's other edits (its new style, cleared overrides), not the
  ones it had before.
- The prefix and suffix rows are marked overridden when DIMPOST or DIMAPOST
  is, and their "Use the style's value" clears that variable.
- Rotating aligned or fit TEXT turns its baseline's second point with it
  (the renderer takes their direction from the two points).
- Justify Align or Fit measures the baseline from the text as the call
  leaves it (its new contents, style, height, width factor and rotation).
- `scale` is an insert's or hatch's scale only; it no longer also becomes a
  DIMSCALE override of a dimension in the selection (that's `dimScale`).
- A text style that only a dimension's text style override names is in use,
  so style.delete refuses it (a rename follows those overrides already).
- Editing a text or dimension style redraws the dimensions read from a file
  only when the style changed: making it current keeps their geometry.
- docs/mcp.md's example finds the dimension's handle with query_entities
  before it describes and sets it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
SlopapaloozaandClaude Opus 5.5 a551f206e8 Review fixes: hatch pattern lines, closed-filled ends, measurements, layer after checks
From CodeRabbit's review of #954:
- A Properties pattern edit follows HATCHEDIT: a library pattern drops the
  hatch's own lines, a loaded .pat pattern brings its lines, and any other
  name keeps them (the moved code cleared them unconditionally).
- Closed filled chosen for Arrow 1 or Arrow 2 is stored as _CLOSEDFILLED: an
  empty per-end arrowhead draws DIMBLK's, so "" changed nothing under a tick.
- The Measurement row writes angles in the dimension's angle format
  (DIMAUNIT, DIMADEC, DIMAZIN) as the renderer does, and equal measurements
  written differently (units, precision) show *VARIES*.
- Text height with fixed-height text styles of different heights shows
  *VARIES* instead of the dimensions' shared DIMTXT.
- properties.set creates a new layer only after every check, so a refused
  call leaves no layer behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
eldrirandClaude Opus 5.5 b70c8609c9 Properties: describe and set every text, mtext and dimension property
properties.describe lists the Properties palette's rows for a selection: General for every
object; Text and Geometry for TEXT and MTEXT; Misc, Lines & Arrows, Text, Fit, Primary Units,
Alternate Units and Tolerances for dimensions. Each row carries the properties.set key that
changes it, the value the objects share (or *VARIES*), the value in the drawing's units, whether
it can be edited (a fixed-height text style makes a dimension's text height read-only and says
so), and for dimensions whether the dimension overrides its style there. A mixed selection gets
the General group; `type` limits the description to one object type.

properties.set takes those keys: TEXT style, justify (keeping the point the text is placed by),
oblique, positionX/Y/Z and the second point of aligned and fit text; MTEXT style, justify,
lineSpacing, lineSpacingDistance and lineSpacingStyle, position; dimension style variables by
field or DIM* name as overrides of each dimension, clearOverrides, clear, textRotation,
textPositionX/Y, prefix and suffix. The reply lists the keys no selected object took.

Editing a dimension style or a text style now redraws the dimensions read from files that use it
(they kept drawing, and saving, the *D block they were read with), and renaming a text style
follows a dimension's own text style override.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
16 changed files with 853 additions and 9 deletions
+26
View File
@@ -45,6 +45,31 @@ pub struct ForeignExtra {
/// Unmodelled groups of the record's own last subclass, written just before its xdata. Filled
/// on save from the entity itself ([`crate::Viewport::extra`]), so that copies keep them.
pub tail: Vec<RawTag>,
/// A lightweight polyline's vertex identifiers (group 91, DXF 2010 and later) as read: one per
/// vertex in the polyline's order; empty when the file gave none. Geometric constraints name the
/// polyline's segments by them, so they are written back while the polyline's vertices are
/// where they were read ([`vertex_ids_for`]).
pub vertex_ids: Vec<VertexId>,
}
/// A vertex of a lightweight polyline as it was read: its identifier and its point as the
/// polyline has it once read (a polyline whose normal points down is read mirrored in x).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct VertexId {
/// The identifier (group 91); 0 for a vertex without one.
pub id: i32,
pub x: f64,
pub y: f64,
}
/// The identifiers `kept` gives the vertices at `points`, in their order, while every vertex is
/// where it was read. `None` once a vertex was added, removed, moved or the order changed: the
/// identifiers no longer say which vertex is which.
pub fn vertex_ids_for(kept: &[VertexId], points: impl ExactSizeIterator<Item = (f64, f64)> + Clone) -> Option<Vec<i32>> {
if kept.is_empty() || kept.len() != points.len() {
return None;
}
kept.iter().zip(points).all(|(k, (x, y))| k.x == x && k.y == y).then(|| kept.iter().map(|k| k.id).collect())
}
impl ForeignExtra {
@@ -55,6 +80,7 @@ impl ForeignExtra {
&& self.color_book.is_none()
&& self.props.is_empty()
&& self.tail.is_empty()
&& self.vertex_ids.is_empty()
}
}
+2
View File
@@ -154,6 +154,8 @@ impl Header {
// Annotation scale of model space; annotative objects of other scales show (1) or not.
h.set_str("CANNOSCALE", "1:1");
h.set_i64("ANNOALLVISIBLE", 1);
// Written to DXF as $REGENMODE; a header variable the drawing lacks is not written.
h.set_i64("REGENMODE", 1);
h
}
+1 -1
View File
@@ -237,7 +237,7 @@ impl Interactive for SetvarM {
}
}
}
(Some(n), Input::Text(t)) => match crate::sysvars::set(s, &n, &Value::String(t)) {
(Some(n), Input::Text(t)) => match crate::sysvars::set(s, &n, &crate::sysvars::typed_value(&n, t)) {
Ok(()) => {
s.touch();
Ok(Step::Done)
+4
View File
@@ -149,6 +149,9 @@ pub struct Settings {
/// ATTDIA: INSERT typed or from a menu asks for attribute values in the Edit Attributes
/// dialog; on by default, as in AutoCAD (Initial value 1).
pub attdia: bool,
/// TEXTEVAL: 1 lets a routine's input be read as LISP where it would be text (default: 0).
/// Kept for routines that switch it around their prompts; no prompt reads it yet.
pub texteval: bool,
}
impl Default for Settings {
@@ -220,6 +223,7 @@ impl Default for Settings {
auditctl: false,
attreq: true,
attdia: true,
texteval: false,
}
}
}
+109 -3
View File
@@ -7,7 +7,14 @@ use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_
mod table;
/// ACADVER: the program's release, as a text AutoCAD documents it and `atof` reads back as a
/// number. A drawing's `$ACADVER` header is its file version, which is what a save writes, so the
/// two are separate values: `get` gives this text, `list` too, and the header stays as read.
pub const ACADVER_TEXT: &str = "24.3s (CADCraft)";
const SESSION_VARS: &[&str] = &[
// The release text, with or without a drawing (the header's `$ACADVER` is the file version).
"ACADVER",
"AUDITCTL",
"ATTREQ",
"OSMODE",
@@ -81,10 +88,54 @@ const SESSION_VARS: &[&str] = &[
"SAVETIME",
"SAVEFILEPATH",
"ISAVEBAK",
"DIMASO",
"TEXTEVAL",
"POPUPS",
];
pub fn get(s: &Session, name: &str) -> Option<Value> {
/// The DIMASSOC mode DIMASO turned off, kept in the drawing's header so undo restores it.
/// `CADCRAFT_` names are not listed by SYSVARS and no file writes this one.
const DIMASO_MODE: &str = "CADCRAFT_DIMASO_MODE";
/// The header key above, under any number of `$`: no variable of that name exists.
fn is_internal(n: &str) -> bool {
n.trim_start_matches('$') == DIMASO_MODE
}
/// The names this session also answers with DXF's `$` in front: the header writes them that way
/// (`$DIMASO`, `$TEXTEVAL`, `$REGENMODE`, `$POPUPS`), so a routine may type either form.
const DOLLAR_VARS: &[&str] = &["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"];
/// [`set`] takes only a number for these: a program's or a routine's text is refused. A value
/// typed at the command line arrives as text and goes through [`typed_value`] first.
const NUMBER_ONLY: &[&str] = &["DIMASO", "TEXTEVAL", "REGENMODE"];
/// The value of `text` typed at a SETVAR prompt for `name`: typed digits are a number for the
/// [`NUMBER_ONLY`] variables. Anything else stays text.
pub(crate) fn typed_value(name: &str, text: String) -> Value {
if NUMBER_ONLY.contains(&bare_name(name).as_str())
&& let Ok(number) = text.trim().parse::<i64>()
{
return json!(number);
}
Value::String(text)
}
/// `name` trimmed and upper case, without the `$` those names take. Every other name keeps the
/// `$` it was typed with: `$ANGBASE` stays a name of its own (LISP converts radians only for the
/// plain name) and `$OSMODE` is not the session's OSMODE.
fn bare_name(name: &str) -> String {
let n = name.trim().to_ascii_uppercase();
// Every leading `$`, as the header drops them all when it stores a value.
let rest = n.trim_start_matches('$');
if rest.len() < n.len() && DOLLAR_VARS.contains(&rest) { rest.to_string() } else { n }
}
pub fn get(s: &Session, name: &str) -> Option<Value> {
let n = bare_name(name);
if is_internal(&n) {
return None;
}
let st = &s.settings;
let v = match n.as_str() {
"OSMODE" => json!(st.osmode),
@@ -177,6 +228,12 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
"SAVETIME" => json!(crate::autosave::savetime()),
"SAVEFILEPATH" => json!(crate::autosave::savefilepath()),
"ISAVEBAK" => json!(i32::from(crate::autosave::isavebak())),
// DIMASO is obsolete in AutoCAD and has no value of its own: it reports DIMASSOC.
"DIMASO" => json!(i32::from(matches!(dimassoc(s)?, 1 | 2))),
// Whether a prompt reads typed text as LISP (routines switch it around their prompts).
"TEXTEVAL" => json!(i32::from(st.texteval)),
// Dialogs are available (read-only; a batch session is still told 1, as AutoCAD does).
"POPUPS" => json!(1),
"CMDNAMES" => json!(s.running.as_ref().map(|r| r.id.to_ascii_uppercase()).unwrap_or_default()),
"DWGNAME" => json!(s.state().map(|d| d.title.clone()).unwrap_or_default()),
"DBMOD" => json!(s.state().map(|d| i32::from(d.is_dirty())).unwrap_or(0)),
@@ -189,6 +246,9 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
"DWGTITLED" => json!(s.state().map(|d| i32::from(d.path.is_some())).unwrap_or(0)),
"CMDACTIVE" => json!(i32::from(s.running.is_some())),
"TILEMODE" => json!(i32::from(s.state().is_ok_and(|d| d.space.layout().is_none()))),
// The release number as AutoCAD reports it, so `(atof (getvar "ACADVER"))` is 24.3; the
// drawing's own `$ACADVER` (its file version) is left alone for the save version.
"ACADVER" => json!(ACADVER_TEXT),
"PLATFORM" => json!(std::env::consts::OS),
"BLOCKEDITOR" => json!(i32::from(s.state().is_ok_and(|d| d.block_edit.is_some()))),
// The template NEW/QNEW start from (a profile setting, like FONTALT; "" = none).
@@ -257,6 +317,11 @@ fn dwg_prefix(path: &str) -> String {
}
}
/// DIMASSOC's value (0 off, 1 or 2 associative), read where DIMASO reports it from.
fn dimassoc(s: &Session) -> Option<i64> {
table::get(s, "DIMASSOC")?.as_i64()
}
fn as_bool(v: &Value) -> Option<bool> {
v.as_bool().or_else(|| v.as_i64().map(|i| i != 0)).or_else(|| v.as_str().and_then(|s| s.trim().parse::<i64>().ok()).map(|i| i != 0))
}
@@ -277,6 +342,7 @@ fn as_pt(v: &Value) -> Option<cadcraft_geom::Vec2> {
/// Variables `get` reports from session or drawing state that `set` can't change.
const READ_ONLY: &[&str] = &[
"ACADVER",
"CMDNAMES",
"DWGNAME",
"DWGPREFIX",
@@ -304,10 +370,15 @@ const READ_ONLY: &[&str] = &[
"UCSXDIR",
"UCSYDIR",
"WORLDUCS",
// Dialogs: a session always has them, so the variable is fixed (not saved).
"POPUPS",
];
pub fn is_read_only(name: &str) -> bool {
READ_ONLY.iter().any(|r| r.eq_ignore_ascii_case(name.trim())) || table::is_read_only(&name.trim().to_ascii_uppercase())
// A header name's `$` is ignored: the header drops it when it stores a value, so `$ACADVER`
// would otherwise change ACADVER, and with it the version a save writes.
let n = name.trim().trim_start_matches('$').trim();
READ_ONLY.iter().any(|r| r.eq_ignore_ascii_case(n)) || table::is_read_only(&n.to_ascii_uppercase())
}
/// POLARADDANG as typed: up to ten angles in degrees separated by `;` (radians out); `None` when
@@ -325,11 +396,17 @@ pub fn format_angle_list(angles: &[f64]) -> String {
/// Set a system variable, refusing values out of its range and folders the automation roots can't hold.
pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
let n = name.trim().to_ascii_uppercase();
let n = bare_name(name);
if is_internal(&n) {
return Err(EngineError::BadParams { cmd: "setvar".into(), msg: format!("unknown variable `{n}`") });
}
if is_read_only(&n) {
return Err(EngineError::BadParams { cmd: "setvar".into(), msg: format!("{n} is read-only") });
}
let bad = || EngineError::BadParams { cmd: "setvar".into(), msg: format!("invalid value for {n}") };
if NUMBER_ONLY.contains(&n.as_str()) && !v.is_number() {
return Err(bad());
}
let st = &mut s.settings;
match n.as_str() {
"OSMODE" => {
@@ -436,6 +513,35 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
}
"SAVEFILEPATH" => crate::autosave::set_savefilepath(v.as_str().ok_or_else(bad)?),
"ISAVEBAK" => crate::autosave::set_isavebak(as_bool(v).ok_or_else(bad)?),
// DIMASO has no value of its own: 0 turns DIMASSOC off (remembering the mode it had),
// 1 restores that mode (2 when none was seen), and 1 while it is on changes nothing. The
// mode it remembers is in the drawing's header ([`DIMASO_MODE`]), so each open drawing
// keeps its own and undo restores it with DIMASSOC; no file writes it.
"DIMASO" => {
let on = as_i(v).filter(|i| matches!(i, 0 | 1)).ok_or_else(bad)? == 1;
let mode = dimassoc(s).ok_or_else(bad)?;
// The drawing is touched only when DIMASSOC changes, so it is not marked modified
// and no undo step is left for a value it already has.
match (on, mode) {
(true, 1 | 2) | (false, 0) => {}
// Turned back on, from off or from a file's unknown mode: the mode it had.
(true, _) => {
let h = &mut s.doc_mut()?.header;
// Only a mode DIMASSOC takes: a file's value of anything else restores 2.
let restore = h.i64(DIMASO_MODE, 2);
h.set_i64("DIMASSOC", if matches!(restore, 1 | 2) { restore } else { 2 });
}
(false, _) => {
let h = &mut s.doc_mut()?.header;
if matches!(mode, 1 | 2) {
h.set_i64(DIMASO_MODE, mode);
}
h.set_i64("DIMASSOC", 0);
}
}
}
// Stored for routines that switch it around their prompts; no prompt reads it yet.
"TEXTEVAL" => st.texteval = small(v, 1).ok_or_else(bad)? == 1,
// A number is in degrees; text is an angle typed in AUNITS (SETVAR at the command line).
"ANGBASE" => {
let a = match v {
+2
View File
@@ -73,6 +73,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
("PLINEWID", Kind::Real { min: 0.0, strict: false }, Def::Real(0.0)),
("POLYSIDES", Kind::Int(3, 1024), Def::Int(4)),
("PROJMODE", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
// 1 regenerates the drawing after a command that changes it (stored, nothing reads it yet).
("REGENMODE", Kind::Choice(&[0, 1]), Def::Int(1)),
("REVCLOUDARCLEN", Kind::Real { min: 0.0, strict: true }, Def::Units(0.5, 15.0)),
("SPLINESEGS", Kind::Int(-32768, 32767), Def::Int(8)),
("SPLKNOTS", Kind::Choice(&[0, 1, 2]), Def::Int(0)),
+111
View File
@@ -0,0 +1,111 @@
//! ACADVER is the program's release as text, as AutoCAD documents it, so `(atof (getvar
//! "ACADVER"))` reads a number from it. It is read-only, and the drawing's `$ACADVER` stays the
//! file version a save writes, so a drawing read from a 2000 DXF saves as one.
use cadcraft_engine::Session;
use cadcraft_engine::lisp::value::Value;
use serde_json::json;
/// The release text `getvar` and `(getvar "ACADVER")` report.
const RELEASE: &str = "24.3s (CADCraft)";
/// A 2000 DXF (`$ACADVER` `AC1015`) holding one line.
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n\
0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n10.0\n21\n0.0\n31\n0.0\n\
0\nENDSEC\n0\nEOF\n";
/// A LISP expression's value, or its error message.
fn lisp(s: &mut Session, code: &str) -> Result<Value, String> {
match s.lisp_eval(code, false, true, Vec::new()) {
Ok(Some(Ok(v))) => Ok(v),
Ok(Some(Err(e))) => Err(e),
Ok(None) => Err("did not finish".into()),
Err(e) => Err(e.to_string()),
}
}
/// GETVAR's value.
fn getvar(s: &mut Session, name: &str) -> serde_json::Value {
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
}
/// The `$ACADVER` a DXF text declares.
fn file_version(text: &str) -> Option<String> {
let l: Vec<&str> = text.lines().map(str::trim).collect();
let at = l.windows(2).position(|w| w == ["9", "$ACADVER"])?;
l.get(at + 2).filter(|c| **c == "1").and_then(|_| l.get(at + 3)).map(|v| (*v).to_string())
}
#[test]
fn getvar_gives_the_release_text_and_atof_reads_the_number() {
let mut s = Session::new();
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
assert_eq!(getvar(&mut s, "acadver"), json!(RELEASE), "lower-case names work");
assert!(matches!(lisp(&mut s, "(getvar \"ACADVER\")"), Ok(Value::Str(t)) if &*t == RELEASE), "a LISP string");
assert!(matches!(lisp(&mut s, "(atof (getvar \"ACADVER\"))"), Ok(Value::Real(r)) if (r - 24.3).abs() < 1e-9), "(atof) reads the release number");
}
#[test]
fn setvar_refuses_acadver_and_changes_nothing() {
let mut s = Session::new();
let before = s.state().unwrap().doc.header.str("ACADVER", "");
let e = s.execute("setvar", &json!({ "name": "ACADVER", "value": "AC1027" })).unwrap_err().to_string();
assert!(e.contains("read-only"), "{e}");
assert!(lisp(&mut s, "(setvar \"ACADVER\" \"AC1027\")").is_err(), "AutoLISP's setvar too");
// Typed at the command line, SETVAR reports the variable as read-only at its name prompt.
s.cmdline("setvar acadver").unwrap();
assert!(s.log.iter().any(|l| l == &format!("ACADVER = {RELEASE} (read only)")), "{:?}", s.log);
// Neither the release text nor the drawing's file version moved.
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), before);
assert_eq!(before, "AC1032");
}
#[test]
fn a_2000_drawing_saves_as_2000() {
crate::refedit_xref::hooks();
let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("acadver-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("r2000.dxf");
let name = path.to_string_lossy().into_owned();
let mut s = Session::empty();
s.open_drawing(cadcraft_io::read_dxf(DXF.as_bytes()).unwrap(), "r2000.dxf", Some(name.clone()));
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1015", "read as 2000");
assert_eq!(cadcraft_io::save_version(&s.state().unwrap().doc), cadcraft_io::Version::R2000);
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE), "still the release text");
s.execute("qsave", &json!({})).unwrap();
let saved = std::fs::read_to_string(&path).unwrap();
assert_eq!(file_version(&saved).as_deref(), Some("AC1015"), "the file keeps its 2000 version");
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1015");
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
assert_eq!(cadcraft_io::read_dxf(saved.as_bytes()).unwrap().header.str("ACADVER", ""), "AC1015", "and reopens as 2000");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_dollar_name_cannot_change_the_file_version() {
let mut s = Session::new();
let e = s.execute("setvar", &json!({ "name": "$ACADVER", "value": "AC1027" })).unwrap_err().to_string();
assert!(e.contains("read-only"), "{e}");
assert!(lisp(&mut s, "(setvar \"$ACADVER\" \"AC1015\")").is_err(), "AutoLISP's setvar too");
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1032", "the save version did not move");
assert!(cadcraft_engine::sysvars::is_read_only("$acadver"), "SETVAR's prompt sees it as read-only too");
// Other `$` names still reach the header as before, in LISP's units.
assert!(lisp(&mut s, "(setvar \"$ANGBASE\" (/ pi 2))").is_ok());
assert!(matches!(lisp(&mut s, "(getvar \"$ANGBASE\")"), Ok(Value::Real(r)) if (r - std::f64::consts::FRAC_PI_2).abs() < 1e-9));
let r = s.execute("setvar", &json!({ "name": "$OSMODE", "value": 9 })).unwrap();
assert_eq!(r["value"], json!(9), "{r}");
}
#[test]
fn listings_show_the_release_text_without_a_drawing() {
let mut s = Session::empty();
let all = s.execute("sysvars", &json!({})).unwrap();
let text = all.to_string();
assert!(text.contains(RELEASE), "{text}");
let mut s = Session::new();
let all = s.execute("sysvars", &json!({})).unwrap().to_string();
assert!(all.contains(RELEASE) && !all.contains("\"AC1032\""), "{all}");
}
+386
View File
@@ -0,0 +1,386 @@
//! Legacy system variables a LISP routine saves and restores around its work: DIMASO (obsolete in
//! AutoCAD, which reports and sets DIMASSOC through it), TEXTEVAL, REGENMODE (kept in the drawing
//! and its DXF header) and POPUPS (read-only). Before them `(getvar "DIMASO")` read nil, so
//! `(setq o (getvar "DIMASO")) … (setvar "DIMASO" o)` failed and the routine left the drawing's
//! associativity changed.
use cadcraft_engine::Session;
use cadcraft_engine::lisp::value::{Value as LispValue, to_text};
use serde_json::{Value, json};
fn getvar(s: &mut Session, name: &str) -> Value {
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
}
fn setvar(s: &mut Session, name: &str, value: Value) -> bool {
s.execute("setvar", &json!({ "name": name, "value": value })).is_ok()
}
/// The value of a LISP expression, or the error it left.
fn eval(s: &mut Session, src: &str) -> Result<LispValue, String> {
match s.lisp_eval(src, false, true, Vec::new()) {
Ok(Some(v)) => v,
Ok(None) => Err("no value".into()),
Err(e) => Err(e.to_string()),
}
}
/// `(getvar name)` as the integer a routine receives.
fn lisp_getvar(s: &mut Session, name: &str) -> i64 {
let v = eval(s, &format!("(getvar \"{name}\")")).unwrap_or_else(|e| panic!("{name}: {e}"));
let n = v.as_number().unwrap_or_else(|| panic!("{name} is not a number"));
assert_eq!(n.fract(), 0.0, "{name} is a whole number");
n as i64
}
/// `(setvar name value)` from LISP: whether it was accepted.
fn lisp_setvar(s: &mut Session, name: &str, value: &str) -> bool {
eval(s, &format!("(setvar \"{name}\" {value})")).is_ok()
}
/// The DXF pairs `(group code, value)` of a file, both trimmed.
fn pairs(text: &str) -> Vec<(i32, String)> {
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let mut out = Vec::new();
for chunk in lines.chunks(2) {
let [code, value] = chunk else { break };
let Ok(c) = code.parse::<i32>() else { continue };
out.push((c, (*value).to_string()));
}
out
}
/// The HEADER variable names a DXF text writes (the value after each group code 9).
fn header_names(text: &str) -> Vec<String> {
pairs(text).iter().filter(|(c, _)| *c == 9).map(|(_, v)| v.trim_start_matches('$').to_string()).collect()
}
/// The integer a header variable is written with, as `(group code, value)` after its name.
fn header_int(text: &str, name: &str) -> Option<(i32, String)> {
let ps = pairs(text);
let i = ps.iter().position(|(c, v)| *c == 9 && v.trim_start_matches('$') == name)?;
ps.get(i + 1).cloned()
}
#[test]
fn fresh_values_are_integers_a_routine_reads() {
let mut s = Session::new();
for (name, want) in [("DIMASO", 1), ("TEXTEVAL", 0), ("REGENMODE", 1), ("POPUPS", 1)] {
assert_eq!(getvar(&mut s, name), json!(want), "{name}");
assert_eq!(lisp_getvar(&mut s, name), want, "{name} through getvar");
let kind = eval(&mut s, &format!("(type (getvar \"{name}\"))")).unwrap();
assert_eq!(to_text(&kind, true), "INT", "{name} is an integer to LISP");
}
// The list a routine sees (`SETVAR ?`) carries them too.
let all = cadcraft_engine::sysvars::list(&s);
for name in ["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"] {
assert_eq!(all.get(name), Some(&getvar(&mut s, name)), "{name} listed");
}
}
#[test]
fn a_routine_saving_and_restoring_each_one_leaves_it_as_it_was() {
let mut s = Session::new();
for (name, changed) in [("DIMASO", "0"), ("TEXTEVAL", "1"), ("REGENMODE", "0")] {
let before = lisp_getvar(&mut s, name);
// (setq o (getvar X)) … (setvar X o) must give back exactly what it read.
assert!(eval(&mut s, &format!("(setq o (getvar \"{name}\"))")).is_ok(), "{name} readable");
assert!(lisp_setvar(&mut s, name, changed), "{name} takes {changed}");
assert_ne!(lisp_getvar(&mut s, name), before, "{name} changed by {changed}");
assert!(eval(&mut s, &format!("(setvar \"{name}\" o)")).is_ok(), "{name} restored");
assert_eq!(lisp_getvar(&mut s, name), before, "{name} back to {before}");
}
// REGENMODE is the drawing's, kept in its header; TEXTEVAL only the session's.
assert_eq!(s.doc().unwrap().header.i64("REGENMODE", 1), 1);
}
#[test]
fn dimaso_restores_the_dimassoc_mode_it_turned_off() {
// The routine's save/restore through DIMASO, for each associative mode.
for mode in [1, 2] {
let mut s = Session::new();
assert!(setvar(&mut s, "DIMASSOC", json!(mode)));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1), "DIMASO follows DIMASSOC {mode}");
let o = eval(&mut s, "(getvar \"DIMASSOC\")").unwrap().as_number().unwrap();
assert!(lisp_setvar(&mut s, "DIMASO", "0"));
assert_eq!(getvar(&mut s, "DIMASO"), json!(0));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "DIMASO 0 turns associativity off");
assert!(lisp_setvar(&mut s, "DIMASO", "1"));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
assert_eq!(eval(&mut s, "(getvar \"DIMASSOC\")").unwrap().as_number(), Some(o), "DIMASO 1 puts back the DIMASSOC {mode} the routine read");
}
// Set directly, without ever switching it off first, DIMASO 1 leaves the mode alone.
let mut s = Session::new();
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1));
// No non-zero mode was seen: turning associativity back on gives AutoCAD's 2.
let mut s = Session::new();
assert!(setvar(&mut s, "DIMASSOC", json!(0)));
assert!(setvar(&mut s, "DIMASO", json!(0)));
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2), "none was seen: the default 2");
// A drawing whose saved DIMASSOC is no mode DIMASO can restore (a hostile file) gives 2.
let mut s = Session::new();
s.doc_mut().unwrap().header.set_i64("DIMASSOC", 5);
assert!(setvar(&mut s, "DIMASO", json!(0)));
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2));
// Such a mode is not associative, and DIMASO 1 turns associativity on from it too.
s.doc_mut().unwrap().header.set_i64("DIMASSOC", 5);
assert_eq!(getvar(&mut s, "DIMASO"), json!(0));
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2));
}
#[test]
fn typed_setvar_still_takes_digits() {
for (name, digits) in [("DIMASO", "0"), ("TEXTEVAL", "1"), ("REGENMODE", "0")] {
let want = json!(digits.parse::<i64>().unwrap());
let dollar = format!("${name}");
// SETVAR with the name, the bare name, and the `$` form, as typed at the command line.
for lines in [vec!["setvar", name, digits], vec![name, digits], vec!["setvar", dollar.as_str(), digits]] {
let mut s = Session::new();
for line in &lines {
s.cmdline(line).unwrap();
}
assert_eq!(getvar(&mut s, name), want, "typed {lines:?}");
}
// A routine that types the command passes its answers the same way.
let mut s = Session::new();
eval(&mut s, &format!("(command \"SETVAR\" \"{name}\" \"{digits}\")")).unwrap();
assert_eq!(getvar(&mut s, name), want, "(command \"SETVAR\" {name})");
// Typed words are still refused.
let mut s = Session::new();
let before = getvar(&mut s, name);
for line in ["setvar", name, "two"] {
s.cmdline(line).unwrap();
}
assert_eq!(getvar(&mut s, name), before, "typed word refused for {name}");
}
}
#[test]
fn a_new_drawing_writes_regenmode() {
let mut s = Session::new();
// The first drawing, then a new metric and a new imperial one.
for metric in [None, Some(true), Some(false)] {
if let Some(metric) = metric {
s.new_drawing(metric);
}
let text = cadcraft_io::write_dxf(s.doc().unwrap());
assert_eq!(header_int(&text, "REGENMODE"), Some((70, "1".to_string())), "new drawing, metric {metric:?}");
}
}
#[test]
fn hostile_values_are_refused_and_change_nothing() {
let mut s = Session::new();
for (name, v) in [
("REGENMODE", json!(2)),
("REGENMODE", json!(-1)),
("REGENMODE", json!(1.5)),
("REGENMODE", json!("two")),
("REGENMODE", Value::Null),
("TEXTEVAL", json!(-1)),
("TEXTEVAL", json!(2)),
("TEXTEVAL", json!("two")),
("TEXTEVAL", Value::Null),
("DIMASO", json!(3)),
("DIMASO", json!(-1)),
("DIMASO", json!(0.5)),
("DIMASO", json!("two")),
("DIMASO", Value::Null),
// Text a program or a routine passes is refused even when it spells a number.
("REGENMODE", json!("0")),
("TEXTEVAL", json!("1")),
("DIMASO", json!("0")),
("TEXTEVAL", json!(true)),
] {
let before = getvar(&mut s, name);
assert!(!setvar(&mut s, name, v.clone()), "{name} = {v} refused");
assert_eq!(getvar(&mut s, name), before, "{name} unchanged by {v}");
}
// The drawing's associativity is untouched by a refused DIMASO.
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(!setvar(&mut s, "DIMASO", json!(3)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1));
// The same through LISP, where nil and a NaN real arrive as values a variable can't take.
assert!(!lisp_setvar(&mut s, "REGENMODE", "nil"), "nil refused");
assert!(!lisp_setvar(&mut s, "DIMASO", "3"), "DIMASO 3 refused");
assert!(!lisp_setvar(&mut s, "DIMASO", "\"two\""), "DIMASO text refused");
for (name, v) in [("DIMASO", "\"0\""), ("TEXTEVAL", "\"1\""), ("REGENMODE", "\"0\"")] {
assert!(!lisp_setvar(&mut s, name, v), "{name} text {v} refused");
}
assert!(!lisp_setvar(&mut s, "TEXTEVAL", "-1"), "TEXTEVAL -1 refused");
// (- (exp 1000) (exp 1000)) is NaN: not a number JSON can hold, so it is refused as one.
assert!(!lisp_setvar(&mut s, "TEXTEVAL", "(- (exp 1000) (exp 1000))"), "NaN refused");
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(0));
}
#[test]
fn popups_is_read_only() {
let mut s = Session::new();
assert!(cadcraft_engine::sysvars::is_read_only("popups"));
for v in [json!(1), json!(0), json!("1")] {
let e = s.execute("setvar", &json!({ "name": "POPUPS", "value": v })).unwrap_err().to_string();
assert!(e.contains("read-only"), "{v}: {e}");
}
assert!(!lisp_setvar(&mut s, "POPUPS", "0"));
assert_eq!(getvar(&mut s, "POPUPS"), json!(1));
}
#[test]
fn regenmode_is_saved_in_the_dxf_header_and_read_back() {
let mut s = Session::new();
assert!(setvar(&mut s, "REGENMODE", json!(0)));
let text = cadcraft_io::write_dxf(s.doc().unwrap());
assert!(header_names(&text).contains(&"REGENMODE".to_string()), "$REGENMODE is in the header (has {:?})", header_names(&text));
assert_eq!(header_int(&text, "REGENMODE"), Some((70, "0".to_string())), "$REGENMODE is group 70, 0");
// A reopened drawing has the value it was saved with, and saves it back.
let mut back = Session::new();
back.open_drawing(cadcraft_io::read_dxf(text.as_bytes()).unwrap(), "regenmode.dxf", None);
assert_eq!(getvar(&mut back, "REGENMODE"), json!(0));
let again = cadcraft_io::write_dxf(back.doc().unwrap());
assert_eq!(header_int(&again, "REGENMODE"), Some((70, "0".to_string())));
}
#[test]
fn texteval_dimaso_and_popups_are_not_saved() {
let mut s = Session::new();
assert!(setvar(&mut s, "TEXTEVAL", json!(1)));
let text = cadcraft_io::write_dxf(s.doc().unwrap());
let names = header_names(&text);
for name in ["TEXTEVAL", "DIMASO", "POPUPS"] {
assert!(!names.contains(&name.to_string()), "{name} is not a header variable (has {names:?})");
}
// TEXTEVAL is the session's: a drawing opened in this session does not bring its own value.
s.open_drawing(cadcraft_io::read_dxf(text.as_bytes()).unwrap(), "no_legacy_vars.dxf", None);
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(1), "opening a drawing leaves the session's value");
}
#[test]
fn dimaso_remembers_the_mode_of_each_open_drawing() {
// The mode DIMASO turns off is the drawing's, not the session's: two open drawings switched
// between each put back the DIMASSOC mode they had.
let mut s = Session::new();
let first = s.active;
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(setvar(&mut s, "DIMASO", json!(0)));
let second = s.new_drawing(true);
assert_eq!(second, first + 1);
assert!(setvar(&mut s, "DIMASSOC", json!(2)));
assert!(setvar(&mut s, "DIMASO", json!(0)));
s.execute("document.switch", &json!({ "index": first })).unwrap();
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "the first drawing restores its own mode");
s.execute("document.switch", &json!({ "index": second })).unwrap();
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2), "the second drawing restores its own mode");
}
#[test]
fn the_dollar_forms_are_the_same_variables() {
// The DXF header writes these names with a `$` ($DIMASO, $TEXTEVAL, $REGENMODE, $POPUPS), so
// the command line takes them that way too, in any case and with spaces around them.
let mut s = Session::new();
for name in ["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"] {
let plain = getvar(&mut s, name);
let dollar = format!("${name}");
assert_eq!(getvar(&mut s, &dollar), plain, "{dollar} reads like {name}");
let typed = format!(" ${} ", name.to_ascii_lowercase());
assert_eq!(getvar(&mut s, &typed), plain, "{typed:?} reads like {name}");
assert_eq!(cadcraft_engine::sysvars::is_read_only(&dollar), cadcraft_engine::sysvars::is_read_only(name), "{dollar} read-only as {name}");
}
// DIMASO through its DXF name still turns DIMASSOC off and puts its mode back.
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(setvar(&mut s, "$DIMASO", json!(0)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "$DIMASO 0 turns associativity off");
assert!(setvar(&mut s, " $dimaso ", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "$DIMASO 1 puts the mode back");
// TEXTEVAL: set under one name, read under the other.
assert!(setvar(&mut s, "$TEXTEVAL", json!(1)));
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(1), "$TEXTEVAL set TEXTEVAL");
assert!(setvar(&mut s, "TEXTEVAL", json!(0)));
assert_eq!(getvar(&mut s, "$TEXTEVAL"), json!(0));
// REGENMODE takes only the values its plain name takes, and stores the ones it takes.
assert!(!setvar(&mut s, "$REGENMODE", json!(2)), "$REGENMODE 2 is out of range");
assert_eq!(getvar(&mut s, "REGENMODE"), json!(1), "a refused $REGENMODE changed nothing");
assert!(!setvar(&mut s, "$REGENMODE", json!(-1)), "$REGENMODE -1 is out of range");
assert!(setvar(&mut s, "$REGENMODE", json!(0)));
assert_eq!(getvar(&mut s, "$REGENMODE"), json!(0));
assert_eq!(getvar(&mut s, "REGENMODE"), json!(0));
assert_eq!(s.doc().unwrap().header.i64("REGENMODE", 1), 0, "$REGENMODE stored the drawing's value");
// POPUPS is read-only under its DXF name too.
for v in [json!(0), json!("1")] {
let e = s.execute("setvar", &json!({ "name": "$POPUPS", "value": v })).unwrap_err().to_string();
assert!(e.contains("read-only"), "$POPUPS {v}: {e}");
}
assert!(!lisp_setvar(&mut s, "$POPUPS", "0"));
assert_eq!(getvar(&mut s, "$POPUPS"), json!(1));
}
#[test]
fn other_dollar_names_keep_their_own_handling() {
// Only those four take a `$`: LISP's angle variables convert radians for the plain name, and
// `$OSMODE` stays a name of its own rather than becoming the session's OSMODE.
let mut s = Session::new();
assert!(eval(&mut s, "(setvar \"$ANGBASE\" (/ pi 2))").is_ok());
let base = eval(&mut s, "(getvar \"$ANGBASE\")").unwrap().as_number().unwrap_or(f64::NAN);
assert!((base - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "(getvar \"$ANGBASE\") gives pi/2, not {base}");
let osmode = eval(&mut s, "(setvar \"$OSMODE\" 9)").unwrap();
assert_eq!(to_text(&osmode, true), "9", "(setvar \"$OSMODE\" 9) returns 9");
assert_eq!(getvar(&mut s, "OSMODE"), json!(4133), "$OSMODE is not the session's OSMODE");
assert_eq!(getvar(&mut s, "$OSMODE"), json!(9), "$OSMODE still reads back what it was set to");
}
#[test]
fn undo_puts_back_the_mode_dimaso_remembers() {
// The mode DIMASO remembers goes back with DIMASSOC when the changes are undone.
let mut s = Session::new();
for (name, v) in [("DIMASSOC", 1), ("DIMASO", 0), ("DIMASSOC", 2), ("DIMASO", 0)] {
assert!(setvar(&mut s, name, json!(v)), "{name} {v}");
}
s.cmdline("u").unwrap();
s.cmdline("u").unwrap();
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "back to after the first DIMASO 0");
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "the mode remembered then, not the later 2");
}
#[test]
fn repeated_dollars_are_the_same_variables() {
let mut s = Session::new();
assert!(!lisp_setvar(&mut s, "$$REGENMODE", "2"), "out of range under any number of $");
assert_eq!(getvar(&mut s, "REGENMODE"), json!(1), "a refused $$REGENMODE changed nothing");
assert!(!setvar(&mut s, "$$$POPUPS", json!(0)), "read-only under any number of $");
assert!(cadcraft_engine::sysvars::is_read_only("$$POPUPS"));
}
#[test]
fn dimaso_on_while_already_on_leaves_the_drawing_unmodified() {
let mut s = Session::new();
assert_eq!(getvar(&mut s, "DBMOD"), json!(0), "a fresh drawing");
assert!(setvar(&mut s, "DIMASO", json!(1)), "already on");
assert_eq!(getvar(&mut s, "DBMOD"), json!(0), "nothing changed, so not modified");
}
#[test]
fn the_remembered_mode_is_not_a_variable_and_is_not_reported_lost() {
let mut s = Session::new();
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(setvar(&mut s, "DIMASO", json!(0)));
for name in ["CADCRAFT_DIMASO_MODE", "$CADCRAFT_DIMASO_MODE", "cadcraft_dimaso_mode"] {
assert!(s.execute("getvar", &json!({ "name": name })).is_err(), "{name} is not a variable");
assert!(!setvar(&mut s, name, json!(2)), "{name} cannot be set");
}
assert!(eval(&mut s, "(getvar \"CADCRAFT_DIMASO_MODE\")").map_or(true, |v| to_text(&v, false) == "nil"));
// Saved and read back, the drawing has lost nothing a save keeps.
let before = s.doc().unwrap().clone();
let after = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&before).as_bytes()).unwrap();
let cmp = cadcraft_io::roundtrip::compare(&before, &after, &cadcraft_io::roundtrip::Options::default());
assert!(!cmp.differences.iter().any(|d| d.place.contains("DIMASO")), "{:?}", cmp.differences.iter().map(|d| &d.place).collect::<Vec<_>>());
}
+2
View File
@@ -1,6 +1,7 @@
#[path = "../support/temp_dir.rs"]
mod temp_dir;
mod acadver;
mod angle_prompts;
mod angle_settings;
mod annotate_options;
@@ -104,6 +105,7 @@ mod layout_prompts;
mod leader_command;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod leader_text_scale;
mod legacy_sysvars;
mod lisp_answer_by_frames;
mod lisp_corpus;
mod lisp_findfile;
+3 -1
View File
@@ -11,7 +11,9 @@ use cadcraft_engine::doc::{Block, Circle, Drawing, Entity, EntityKind, Handle, I
use cadcraft_engine::{Input, Session};
use serde_json::{Value, json};
fn hooks() {
/// The real file formats, for every test in this binary that opens or saves files (the hooks are
/// process-wide and the first ones set stay).
pub(crate) fn hooks() {
set_io(IoHooks {
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
+53 -1
View File
@@ -16,7 +16,9 @@ use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number, proxy_has_string_stream};
use cadcraft_doc::foreign::{
Foreign, ForeignExtra, ForeignKey, ForeignObject, VertexId, class_group, class_index, class_number, proxy_has_string_stream,
};
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown};
use craft_dxf::{SectionRef, Tag, Version};
@@ -83,6 +85,8 @@ fn leader_acad_rest(chunk: &[Tag]) -> Vec<Tag> {
/// Most objects kept from one file.
const MAX_OBJECTS: usize = 1_000_000;
/// Most vertices of one polyline whose identifiers are kept.
const MAX_VERTEX_IDS: usize = 1_000_000;
/// Most xdata groups kept per record (AutoCAD allows 16 KB of xdata per object).
const MAX_XDATA_GROUPS: usize = cadcraft_doc::MAX_XDATA_GROUPS;
/// Longest ownership chain followed.
@@ -345,9 +349,57 @@ fn extra(kind: &str, tags: &[Tag], entity: bool, unknown: bool, kept: &HashSet<S
}
x.props = props.iter().filter(|t| matches!(t.code, 347 | 284)).map(raw).collect();
}
if entity && !unknown && kind == "LWPOLYLINE" {
x.vertex_ids = vertex_ids(tags);
}
x
}
/// A LWPOLYLINE record's vertices with their identifiers (group 91 after a vertex's point): one
/// per vertex, identifier 0 for a vertex without one; empty when no vertex has one
/// ([`ForeignExtra::vertex_ids`]). The points are as the reader gives them: mirrored in x when
/// the normal points down. Groups inside an application's `102 {` … `102 }` are not the
/// polyline's.
fn vertex_ids(tags: &[Tag]) -> Vec<VertexId> {
let mut in_app = false;
let own_tags: Vec<&Tag> = tags
.iter()
.take_while(|t| t.code < 1000)
.filter(|t| {
if t.code == 102 {
in_app = t.str().trim_start().starts_with('{');
return false;
}
!in_app
})
.collect();
let own = || own_tags.iter().copied();
let down = own().any(|t| t.code == 230 && t.f64() < 0.0);
if !own().any(|t| t.code == 91 && t.i64() != 0) {
return Vec::new();
}
let mut ids: Vec<VertexId> = Vec::new();
for t in own() {
match t.code {
// A polyline past the cap keeps none: identifiers for some of its vertices would be wrong.
10 if ids.len() >= MAX_VERTEX_IDS => return Vec::new(),
10 => ids.push(VertexId { id: 0, x: if down { -t.f64() } else { t.f64() }, y: 0.0 }),
20 => {
if let Some(last) = ids.last_mut() {
last.y = t.f64();
}
}
91 => {
if let Some(last) = ids.last_mut() {
last.id = i32::try_from(t.i64()).unwrap_or(0);
}
}
_ => {}
}
}
ids
}
/// Every entity of the drawing (model space, layouts, blocks).
fn all_entities(d: &Drawing) -> impl Iterator<Item = &Entity> {
std::iter::once(&d.model)
+8 -1
View File
@@ -169,7 +169,11 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
w.f(38, elevation);
}
thickness(w, e);
for v in &p.vertices {
// The vertex identifiers the file gave the polyline (DXF 2010 and later), while its
// vertices are where they were read: geometric constraints name its segments by them.
let kept = d.foreign.entities.get(&e.handle).map(|x| x.vertex_ids.as_slice()).filter(|_| cx.target >= Version::R2010);
let ids = kept.and_then(|kept| cadcraft_doc::foreign::vertex_ids_for(kept, p.vertices.iter().map(|v| (v.p.x, v.p.y))));
for (i, v) in p.vertices.iter().enumerate() {
w.p2(10, v.p);
if v.start_width != 0.0 || v.end_width != 0.0 {
w.f(40, v.start_width);
@@ -178,6 +182,9 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
if v.bulge != 0.0 {
w.f(42, v.bulge);
}
if let Some(id) = ids.as_ref().and_then(|ids| ids.get(i)).filter(|id| **id != 0) {
w.i(91, i64::from(*id));
}
}
}
EntityKind::MLine(m) => {
+1
View File
@@ -51,6 +51,7 @@ const HEADER_VARS: &[(&str, i32)] = &[
("PSTYLEMODE", 290),
("INSUNITS", 70),
("MEASUREMENT", 70),
("REGENMODE", 70),
("PSLTSCALE", 70),
// The model view the drawing is saved at, as DXF keeps it in HEADER (the `*ACTIVE` VPORT
// record below repeats it). Written so a drawing opened on its saved view saves it back.
+13 -2
View File
@@ -287,8 +287,19 @@ impl<'o> Out<'o> {
/// Header variables that change on every save (time stamps, the handle seed, GUIDs): not
/// compared.
pub const VOLATILE_HEADER: &[&str] =
&["HANDSEED", "TDCREATE", "TDUCREATE", "TDUPDATE", "TDUUPDATE", "TDINDWG", "TDUSRTIMER", "VERSIONGUID", "FINGERPRINTGUID"];
/// `CADCRAFT_DIMASO_MODE` is the engine's memory of the mode DIMASO turned off; no file keeps it.
pub const VOLATILE_HEADER: &[&str] = &[
"HANDSEED",
"TDCREATE",
"TDUCREATE",
"TDUPDATE",
"TDUUPDATE",
"TDINDWG",
"TDUSRTIMER",
"VERSIONGUID",
"FINGERPRINTGUID",
"CADCRAFT_DIMASO_MODE",
];
/// Compare `before` (the drawing as first opened) with `after` (the same drawing saved and
/// reopened). Differences are reported as what `after` lost, gained or changed.
+130
View File
@@ -0,0 +1,130 @@
//! A lightweight polyline keeps its vertex identifiers (LWPOLYLINE group 91 after a vertex, DXF
//! 2010 and later) through a save while its vertices are where they were read.
//! Geometric constraints name a polyline's segments by these identifiers. CADCraft's polyline has
//! none, so every save wrote the polyline without them, and what the constraints name was gone.
//!
//! The DWG is written here with acadrust, the identifiers out of order and the first vertex not
//! the smallest, as on a polyline that was edited in another program. The harness builds this
//! module only where acadrust builds (see `main.rs`).
use std::io::Cursor;
use acadrust::entities::{EntityType, LwPolyline, LwVertex};
use acadrust::{CadDocument, DxfVersion, Vector2};
use cadcraft_io::{SaveOptions, Version, read, write_with};
const VERTEX_IDS: [i32; 4] = [2, 5, 7, 1];
fn polyline_dwg() -> Vec<u8> {
polyline_dwg_with([(0.0, 0.0), (40.0, 0.0), (40.0, 25.0), (0.0, 25.0)], 1.0)
}
/// A DWG with one closed polyline at `points`, its normal along `normal_z` Z.
fn polyline_dwg_with(points: [(f64, f64); 4], normal_z: f64) -> Vec<u8> {
let mut doc = CadDocument::with_version(DxfVersion::AC1032);
let mut polyline = LwPolyline::new();
polyline.is_closed = true;
polyline.normal = acadrust::Vector3::new(0.0, 0.0, normal_z);
for (id, (x, y)) in VERTEX_IDS.iter().zip(points) {
polyline.vertices.push(LwVertex { vertex_id: *id, ..LwVertex::new(Vector2::new(x, y)) });
}
doc.add_entity(EntityType::LwPolyline(polyline)).expect("add the polyline");
acadrust::DwgWriter::write_to_vec(&doc).expect("write the DWG")
}
/// The vertex identifiers of the one lightweight polyline in DWG bytes.
fn vertex_ids_of(dwg: &[u8]) -> Vec<i32> {
let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg.to_vec())).read().unwrap();
doc.entities()
.find_map(|e| match e {
EntityType::LwPolyline(p) => Some(p.vertices.iter().map(|v| v.vertex_id).collect()),
_ => None,
})
.expect("the polyline is in the DWG")
}
/// The vertex identifiers (groups 91) of the one LWPOLYLINE record in a DXF text.
fn dxf_vertex_ids(dxf: &[u8]) -> Vec<String> {
let text = String::from_utf8_lossy(dxf);
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let mut pairs = lines.chunks(2).filter_map(|pair| Some((*pair.first()?, *pair.get(1)?)));
let record = pairs.by_ref().skip_while(|pair| *pair != ("0", "LWPOLYLINE")).skip(1);
record.take_while(|(code, _)| *code != "0").filter(|(code, _)| *code == "91").map(|(_, value)| value.to_string()).collect()
}
fn save(d: &cadcraft_doc::Drawing, name: &str, version: Version) -> Vec<u8> {
write_with(d, name, &SaveOptions { version: Some(version), binary: false }).unwrap()
}
#[test]
fn a_polyline_keeps_its_vertex_identifiers_through_a_save() {
cadcraft_io::dwg_worker::allow_in_process();
let dwg = polyline_dwg();
assert_eq!(vertex_ids_of(&dwg), VERTEX_IDS, "the fixture as acadrust reads it");
let d = read(&dwg, "polyline.dwg").unwrap();
for version in [Version::R2010, Version::R2018] {
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", version)), VERTEX_IDS, "DWG {version:?}");
}
assert_eq!(dxf_vertex_ids(&save(&d, "saved.dxf", Version::R2018)), ["2", "5", "7", "1"]);
// A DXF before 2010 has no such group.
assert!(dxf_vertex_ids(&save(&d, "saved.dxf", Version::R2000)).is_empty());
let back = read(&save(&d, "saved.dxf", Version::R2018), "saved.dxf").unwrap();
assert_eq!(dxf_vertex_ids(&save(&back, "again.dxf", Version::R2018)), ["2", "5", "7", "1"], "read back from a DXF");
}
/// Once a vertex is elsewhere, the order is another or a vertex is gone, the identifiers no longer
/// say which vertex is which: none are written.
#[test]
fn an_edited_polyline_drops_its_vertex_identifiers() {
cadcraft_io::dwg_worker::allow_in_process();
let mut d = read(&polyline_dwg(), "polyline.dwg").unwrap();
let handle = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap();
let mut after = |edit: fn(&mut cadcraft_doc::LwPolyline)| {
assert!(d.model.modify(handle, |e: &mut cadcraft_doc::Entity| {
if let cadcraft_doc::EntityKind::LwPolyline(p) = &mut e.kind {
edit(p);
}
}));
vertex_ids_of(&save(&d, "edited.dwg", Version::R2018))
};
assert_eq!(after(|p| p.vertices.reverse()), [0; 4], "reversed");
assert_eq!(after(|p| p.vertices.reverse()), VERTEX_IDS, "reversed back: every vertex is where it was read");
assert_eq!(after(|p| p.vertices[1].p.x += 1.0), [0; 4], "a vertex moved");
}
/// A polyline whose normal points down is read mirrored in x; untouched, it keeps its identifiers.
#[test]
fn a_polyline_facing_down_keeps_its_vertex_identifiers() {
cadcraft_io::dwg_worker::allow_in_process();
let d = read(&polyline_dwg_with([(0.0, 0.0), (40.0, 0.0), (40.0, 25.0), (0.0, 25.0)], -1.0), "down.dwg").unwrap();
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", Version::R2018)), VERTEX_IDS);
}
/// Reversed, a polyline symmetric about x = 0 has its mirror image's points: the identifiers still
/// no longer say which vertex is which.
#[test]
fn a_reversed_symmetric_polyline_drops_its_vertex_identifiers() {
cadcraft_io::dwg_worker::allow_in_process();
let mut d = read(&polyline_dwg_with([(-20.0, 0.0), (-20.0, 25.0), (20.0, 25.0), (20.0, 0.0)], 1.0), "sym.dwg").unwrap();
let handle = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap();
assert!(d.model.modify(handle, |e: &mut cadcraft_doc::Entity| {
if let cadcraft_doc::EntityKind::LwPolyline(p) = &mut e.kind {
p.vertices.reverse();
}
}));
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", Version::R2018)), [0; 4]);
}
/// A group 91 inside an application's `102 {` group of the record is not a vertex identifier.
#[test]
fn a_91_inside_an_application_group_is_not_an_identifier() {
cadcraft_io::dwg_worker::allow_in_process();
let d = read(&polyline_dwg(), "polyline.dwg").unwrap();
let dxf = String::from_utf8(save(&d, "saved.dxf", Version::R2018)).unwrap();
let mut lines: Vec<&str> = dxf.lines().collect();
let start = lines.windows(2).position(|pair| pair[0].trim() == "0" && pair[1].trim() == "LWPOLYLINE").unwrap();
// After the first vertex's identifier.
let at = (start..lines.len()).step_by(2).find(|i| lines[*i].trim() == "91").unwrap() + 2;
lines.splice(at..at, ["102", "{SOMEAPP", " 91", "9", "102", "}"]);
let back = read(lines.join("\n").as_bytes(), "app.dxf").unwrap();
assert_eq!(dxf_vertex_ids(&save(&back, "again.dxf", Version::R2018)), ["2", "5", "7", "1"]);
}
+2
View File
@@ -62,6 +62,8 @@ mod low_handseed;
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod ltype_dwg_dash_count;
mod ltype_element_cap;
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod lwpolyline_vertex_ids;
mod minsert_marker;
mod mleader_content;
mod mleader_roundtrip;