Compare commits

..
69 Commits
Author SHA1 Message Date
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
2026-11-04 22:53:20 -05:00
128 changed files with 4684 additions and 7993 deletions
-1
View File
@@ -97,7 +97,6 @@ Generated-in-code assets are original and have no file to list:
| `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) |
| `crates/ui-egui/src/i18n/he.tsv` | Hagai Baram (@hrb9), AI-assisted; shared `craft-i18n#42` rows include contributions by @nocturney with ChatGPT (AI-assisted) | Original Hebrew translations of CADCraft English strings (1,444 rows shared with [storytold/craft-i18n#42](https://github.com/storytold/craft-i18n/pull/42) at `fdff86e3`, `locales/he/common.tsv` and `locales/he/cadcraft.tsv`, plus 443 additional CADCraft UI strings) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | Clean-room translations written from the plain meaning of CADCraft's English strings; no proprietary localization resources copied; terminology and the running app reviewed by @hrb9 (a native Hebrew speaker), while independent line-by-line proofreading by a second native speaker remains pending; no font assets added (Hebrew uses an installed system font or the optional `craft-fonts` face) |
## PDF import
-23
View File
@@ -221,34 +221,11 @@ fn services() -> Services {
pick_pgp: Some(Box::new(|dir: Option<&str>| {
file_dialog(&Pick::Pgp(dir.unwrap_or_default().into())).pick_file().map(|p| p.to_string_lossy().to_string())
})),
open_folder: Some(Box::new(|dir: &str| open_folder(dir).map_err(Into::into))),
// Set in `main` once the Nightly session record exists.
at_exit: None,
}
}
/// Why [`open_folder`] could not show a folder.
#[derive(Debug, thiserror::Error)]
enum OpenFolderError {
#[error("{dir}: {source}")]
Create { dir: String, source: std::io::Error },
#[error("{program}: {source}")]
Launch { program: &'static str, source: std::io::Error },
}
/// Show `dir` in the system's file manager (Finder, Explorer or the desktop's own), creating it
/// first so a folder nothing was saved in yet still opens.
fn open_folder(dir: &str) -> Result<(), OpenFolderError> {
std::fs::create_dir_all(dir).map_err(|source| OpenFolderError::Create { dir: dir.to_string(), source })?;
#[cfg(target_os = "macos")]
let program = "open";
#[cfg(target_os = "windows")]
let program = "explorer";
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
let program = "xdg-open";
std::process::Command::new(program).arg(dir).spawn().map(|_| ()).map_err(|source| OpenFolderError::Launch { program, source })
}
/// The file types `pick` offers: (label, extensions). Shared by the blocking dialogs and the
/// macOS sheets.
fn filters(pick: &Pick) -> Vec<(&'static str, Vec<&'static str>)> {
+1 -1
View File
@@ -50,7 +50,7 @@ mod xdata;
pub use xdata::{
MAX_XDATA_APP_NAME, MAX_XDATA_CHUNK, MAX_XDATA_GROUPS, MAX_XDATA_STRING, RESERVED_XDATA_APPS, XdataError, check_xdata_app_name,
check_xdata_groups, is_model_xdata, is_model_xdata_app, is_reserved_xdata_app, is_xdata_group, set_xdata_app, xdata_apps, xdata_of,
check_xdata_groups, is_model_xdata_app, is_reserved_xdata_app, is_xdata_group, set_xdata_app, xdata_apps, xdata_of,
};
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal};
-5
View File
@@ -197,11 +197,6 @@ pub struct Leader {
pub spline: bool,
#[serde(default = "standard")]
pub style: String,
/// Per-leader style overrides (the `ACAD` DSTYLE xdata of a LEADER): DimStyle field names
/// (camelCase) → values, merged over the named style as a dimension's are. A leader draws
/// with its arrow size, overall scale, leader arrowhead and dimension line colour.
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
pub overrides: serde_json::Map<String, serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-48
View File
@@ -31,34 +31,10 @@ pub fn is_reserved_xdata_app(name: &str) -> bool {
/// than kept raw: the [`RESERVED_XDATA_APPS`] on any entity, and `ACAD` on a dimension, whose
/// `ACAD` run (`DSTYLE`) holds its dimension-style overrides. The reader models those too, so
/// raw groups set under such a name would be dropped on save; they are refused instead.
/// [`is_model_xdata`] also knows the one list of a leader's `ACAD` run that is modelled.
pub fn is_model_xdata_app(name: &str, kind: &super::EntityKind) -> bool {
is_reserved_xdata_app(name) || (name.trim().eq_ignore_ascii_case("ACAD") && matches!(kind, super::EntityKind::Dimension(_)))
}
/// The list in a dimension's or a leader's `ACAD` xdata that holds its dimension-style overrides.
const DSTYLE_LIST: &str = "DSTYLE";
/// Whether `groups` (one application's xdata, its `1001` left out) hold a list named `name`
/// (any case): a `1000 <name>` group followed by `1002 {`. A string that only reads `<name>`
/// starts no list.
fn has_xdata_list(groups: &[RawTag], name: &str) -> bool {
groups.windows(2).any(
|w| matches!(w, [n, open] if n.code == 1000 && n.value.trim().eq_ignore_ascii_case(name) && open.code == 1002 && open.value.trim() == "{"),
)
}
/// Whether `groups`, given as raw xdata of application `name` for an entity of `kind`, hold
/// what is written from the model: all data of an application [`is_model_xdata_app`] names,
/// and on a leader an `ACAD` run with a `DSTYLE` list. A leader's `DSTYLE` list is its
/// dimension-style overrides, read into the leader and written from it; raw groups with one
/// would be dropped on save or contradict the overrides, so they are refused instead. The rest
/// of a leader's `ACAD` data is kept raw and may be set.
pub fn is_model_xdata(name: &str, groups: &[RawTag], kind: &super::EntityKind) -> bool {
is_model_xdata_app(name, kind)
|| (name.trim().eq_ignore_ascii_case("ACAD") && matches!(kind, super::EntityKind::Leader(_)) && has_xdata_list(groups, DSTYLE_LIST))
}
/// Why an application name or a run of xdata groups was refused.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct XdataError(pub String);
@@ -238,30 +214,6 @@ mod tests {
RawTag { code, value: value.into() }
}
/// `ACAD` xdata is modelled as a DSTYLE list on a leader (a name followed by an opening
/// brace, anywhere in the run, any case), and not on another entity or under another name.
#[test]
fn a_leaders_dstyle_list_is_model_data_and_its_other_acad_data_is_not() {
use super::super::{EntityKind, Leader, Line};
use cadcraft_geom::Vec3;
let leader = EntityKind::Leader(Leader {
vertices: vec![Vec3::ZERO, Vec3::new(1.0, 0.0, 0.0)],
arrow: true,
spline: false,
style: "Standard".into(),
overrides: serde_json::Map::new(),
});
let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) });
let list = [t(1000, "MINE"), t(1000, " dstyle "), t(1002, "{"), t(1070, "41"), t(1040, "9.0"), t(1002, "}")];
let loose = [t(1000, "DSTYLE"), t(1070, "41"), t(1000, "OTHER"), t(1002, "{"), t(1002, "}")];
assert!(is_model_xdata("acad", &list, &leader));
assert!(!is_model_xdata("ACAD", &loose, &leader), "a string that only reads DSTYLE starts no list");
assert!(!is_model_xdata("ACAD", &[], &leader));
assert!(!is_model_xdata("ACME", &list, &leader), "another application's list is its own");
assert!(!is_model_xdata("ACAD", &list, &line));
assert!(is_model_xdata("CADCRAFT", &[], &leader) && is_model_xdata("CADCRAFT", &[], &line));
}
#[test]
fn apps_are_split_at_their_names() {
let x = vec![t(1001, "A"), t(1000, "one"), t(1070, "1"), t(1001, "b"), t(1000, "two")];
+23 -49
View File
@@ -242,29 +242,15 @@ pub fn ole_frame_accepts(m: &cadcraft_geom::Mat3) -> bool {
m.b.abs() < t && m.c.abs() < t && m.a > 0.0 && (m.a - m.d).abs() <= t
}
/// What a single-line text value draws, as the fonts read it.
#[derive(Clone, Copy, Default)]
struct Drawn {
/// How many characters take room.
chars: usize,
/// Whether any of them is underlined, and whether any is overlined.
underlined: bool,
overlined: bool,
}
/// What a single-line text value draws, as the fonts read it: a `%%` code is the one character
/// it stands for (`%%d`, `%%p`, `%%c`, `%%%`, `%%nnn`) or none (`%%u` and `%%o`, which turn the
/// underline and the overline on and off for the characters after them), `\U+XXXX` is one
/// character, and invisible formatting characters (joiners, directional marks) take no room.
fn drawn_text(value: &str) -> Drawn {
/// How many characters a single-line text value draws, as the fonts read it: a `%%` code is the
/// one character it stands for (`%%d`, `%%p`, `%%c`, `%%%`, `%%nnn`) or none (the underline and
/// overline toggles `%%u` and `%%o`), `\U+XXXX` is one character, and invisible formatting
/// characters (joiners, directional marks) take no room.
fn drawn_chars(value: &str) -> usize {
let invisible = |c: char| matches!(c, '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2060}'..='\u{2069}' | '\u{FEFF}' | '\u{061C}');
let chars: Vec<char> = value.chars().collect();
let (mut i, mut drawn) = (0usize, 0usize);
// The toggles as they stand, and what the characters drawn so far have had.
let (mut under, mut over) = (false, false);
let mut out = Drawn::default();
while let Some(&c) = chars.get(i) {
let before = drawn;
let escaped = (c == '\\' && matches!(chars.get(i + 1), Some('U' | 'u')) && chars.get(i + 2) == Some(&'+'))
.then(|| chars.get(i + 3..i + 7))
.flatten()
@@ -276,8 +262,7 @@ fn drawn_text(value: &str) -> Drawn {
i += 7;
} else if c == '%' && chars.get(i + 1) == Some(&'%') {
match chars.get(i + 2).map_or(' ', char::to_ascii_lowercase) {
'u' => (under, i) = (!under, i + 3),
'o' => (over, i) = (!over, i + 3),
'u' | 'o' => i += 3,
'd' | 'p' | 'c' | '%' => (drawn, i) = (drawn + 1, i + 3),
digit if digit.is_ascii_digit() => {
let digits = chars.iter().skip(i + 2).take(3).take_while(|d| d.is_ascii_digit()).count();
@@ -290,19 +275,15 @@ fn drawn_text(value: &str) -> Drawn {
drawn += usize::from(!invisible(c));
i += 1;
}
if drawn > before {
(out.underlined, out.overlined) = (out.underlined || under, out.overlined || over);
}
}
Drawn { chars: drawn, ..out }
drawn
}
/// Bounds of a single-line TEXT / ATTDEF / ATTRIB that draws `drawn`, following its
/// Bounds of a single-line TEXT / ATTDEF / ATTRIB of `len` drawn characters, following its
/// justification the same way the renderer places it (the stroke font is about 0.88 of the height
/// per character), its underline and overline included. Empty when nothing is drawn.
fn text_box(t: &crate::Text, drawn: Drawn) -> Bounds2 {
/// per character). Empty when nothing is drawn.
fn text_box(t: &crate::Text, len: usize) -> Bounds2 {
use crate::{HAlign, VAlign};
let len = drawn.chars;
if len == 0 {
return Bounds2::EMPTY;
}
@@ -359,22 +340,15 @@ fn text_box(t: &crate::Text, drawn: Drawn) -> Bounds2 {
HAlign::Center | HAlign::Middle => -w / 2.0,
HAlign::Right => -w,
};
// Where the baseline of a line drawn `drawn_h` high lies. Bottom justification lifts the line
// by a third of the height it is drawn at.
let baseline = |drawn_h: f64| match (t.halign, t.valign) {
(HAlign::Middle, _) | (_, VAlign::Middle) => -drawn_h / 2.0,
(_, VAlign::Baseline) => 0.0,
(_, VAlign::Bottom) => drawn_h / 3.0,
(_, VAlign::Top) => -drawn_h,
// The box from its bottom to its top. Bottom justification lifts the line by a third of the
// height it is drawn at: the box starts where the shortest line would and ends where the
// tallest would.
let (y0, y1) = match (t.halign, t.valign) {
(HAlign::Middle, _) | (_, VAlign::Middle) => (-h / 2.0, h / 2.0),
(_, VAlign::Baseline) => (0.0, h),
(_, VAlign::Bottom) => (low / 3.0, h / 3.0 + h),
(_, VAlign::Top) => (-h, 0.0),
};
// The fonts draw an underline a fifth of the drawn height below the baseline and an overline
// a fifth of it above the line's top.
let below = if drawn.underlined { 0.2 } else { 0.0 };
let above = if drawn.overlined { 1.2 } else { 1.0 };
// The box from its bottom to its top: it starts where the lowest of the shortest and the
// tallest possible line would and ends where the highest of the two would.
let [(b0, t0), (b1, t1)] = [low, h].map(|drawn_h| (baseline(drawn_h) - below * drawn_h, baseline(drawn_h) + above * drawn_h));
let (y0, y1) = (b0.min(b1), t0.max(t1));
let local = [Vec2::new(dx, y0), Vec2::new(dx + w, y0), Vec2::new(dx + w, y1), Vec2::new(dx, y1)];
// Backwards and upside-down text is mirrored about the point it is placed by.
let (mx, my) = (if t.backwards { -1.0 } else { 1.0 }, if t.upside_down { -1.0 } else { 1.0 });
@@ -510,7 +484,7 @@ fn constant_box(a: &crate::Attrib, upright: bool) -> Bounds2 {
let turn = |r: f64| if upright { 0.0 } else { r };
match a.multiline_text() {
Some(m) if !blank(&m.contents) => mtext_box(&crate::MText { rotation: turn(m.rotation), ..m }),
None if !blank(&a.text.value) => text_box(&crate::Text { rotation: turn(a.text.rotation), ..a.text.clone() }, drawn_text(&a.text.value)),
None if !blank(&a.text.value) => text_box(&crate::Text { rotation: turn(a.text.rotation), ..a.text.clone() }, drawn_chars(&a.text.value)),
_ => Bounds2::EMPTY,
}
}
@@ -701,10 +675,10 @@ fn bounds_in<'a>(
EntityKind::Text(t) if blank(&t.value) => Bounds2::EMPTY,
EntityKind::MText(t) if blank(&t.contents) => Bounds2::EMPTY,
// Text that matches the layout's orientation is drawn upright (#2498).
EntityKind::Text(t) if e.common.matches_layout_orientation() => text_box(&crate::Text { rotation: 0.0, ..t.clone() }, drawn_text(&t.value)),
EntityKind::Text(t) if e.common.matches_layout_orientation() => text_box(&crate::Text { rotation: 0.0, ..t.clone() }, drawn_chars(&t.value)),
EntityKind::MText(t) if e.common.matches_layout_orientation() => mtext_box(&crate::MText { rotation: 0.0, ..t.clone() }),
EntityKind::Text(t) => text_box(t, drawn_text(&t.value)),
EntityKind::AttDef(a) => text_box(&a.text, drawn_text(&a.tag)),
EntityKind::Text(t) => text_box(t, drawn_chars(&t.value)),
EntityKind::AttDef(a) => text_box(&a.text, drawn_chars(&a.tag)),
EntityKind::MText(t) => mtext_box(t),
EntityKind::Insert(ins) => {
if depth >= MAX_BLOCK_DEPTH {
@@ -753,7 +727,7 @@ fn bounds_in<'a>(
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, drawn_text(&a.text.value)),
None => text_box(&a.text, drawn_chars(&a.text.value)),
});
}
}
+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
}
+11 -50
View File
@@ -186,11 +186,7 @@ impl PlotStyle {
/// The printed colour of an object drawn in `rgb`: the style's colour (else `rgb`), turned
/// grey when asked, then screened toward white.
pub fn apply_color(&self, rgb: Rgb) -> Rgb {
self.shade(self.color.unwrap_or(rgb))
}
/// `c` turned grey when the style asks for it, then screened toward white: what the style
/// does to a colour it does not replace.
pub fn shade(&self, c: Rgb) -> Rgb {
let c = self.color.unwrap_or(rgb);
let c = if self.grayscale {
let g = (c.luma().clamp(0.0, 1.0) * 255.0).round() as u8;
Rgb(g, g, g)
@@ -376,65 +372,30 @@ impl PlotStyleTable {
}
}
/// The tables of the user's plot style folder, as the host last read them (see
/// [`set_plot_style_folder`]). Empty until a host reads a folder.
static FOLDER: std::sync::RwLock<Option<std::sync::Arc<Vec<PlotStyleTable>>>> = std::sync::RwLock::new(None);
/// Replace the tables of the user's plot style folder that every drawing can use. The host reads
/// the folder (this crate does no file I/O) and calls this again after each change.
pub fn set_plot_style_folder(tables: Vec<PlotStyleTable>) {
if let Ok(mut f) = FOLDER.write() {
*f = Some(std::sync::Arc::new(tables));
}
}
/// The tables of the user's plot style folder (empty when the host has read none).
pub fn plot_style_folder() -> std::sync::Arc<Vec<PlotStyleTable>> {
FOLDER.read().ok().and_then(|f| f.clone()).unwrap_or_default()
}
/// The folder's table called `name` (case-insensitive).
pub fn plot_style_folder_table(name: &str) -> Option<PlotStyleTable> {
let n = name.trim();
plot_style_folder().iter().find(|t| t.name.eq_ignore_ascii_case(n)).cloned()
}
/// Whether a page setup's table name means "no plot style table".
pub fn no_plot_style_table(name: &str) -> bool {
let n = name.trim();
n.is_empty() || n.eq_ignore_ascii_case("none")
}
/// The plot style table a page setup names, if it is one we know: the drawing's own tables first
/// (a folder table a layout chose is copied into the drawing, and the drawing then plots with its
/// copy whatever happens to the file), then the user's plot style folder, then the built-in ones. `None` for no table (empty or "None") and for tables we don't have.
/// The plot style table a page setup names, if it is one we know: the drawing's own tables
/// first, then the built-in ones. `None` for no table (empty or "None") and for tables we don't
/// have.
pub fn plot_style_table(d: &crate::Drawing, name: &str) -> Option<PlotStyleTable> {
if no_plot_style_table(name) {
return None;
}
let n = name.trim();
d.plot_style_tables
.iter()
.find(|t| t.name.eq_ignore_ascii_case(n))
.cloned()
.or_else(|| plot_style_folder_table(n))
.or_else(|| PlotStyleTable::builtin(n))
d.plot_style_tables.iter().find(|t| t.name.eq_ignore_ascii_case(n)).cloned().or_else(|| PlotStyleTable::builtin(n))
}
/// The names of every table a drawing can use: the drawing's own, the folder's, then the built-in
/// ones, each name once.
/// The names of every table a drawing can use: its own, then the built-in ones it doesn't
/// shadow.
pub fn plot_style_table_names(d: &crate::Drawing) -> Vec<String> {
let mut v: Vec<String> = Vec::new();
let folder = plot_style_folder();
let all = d
.plot_style_tables
.iter()
.map(|t| t.name.as_str())
.chain(folder.iter().map(|t| t.name.as_str()))
.chain(BUILTIN_PLOT_STYLE_TABLES.iter().copied());
for n in all {
if !v.iter().any(|x| x.eq_ignore_ascii_case(n)) {
v.push(n.to_string());
let mut v: Vec<String> = d.plot_style_tables.iter().map(|t| t.name.clone()).collect();
for b in BUILTIN_PLOT_STYLE_TABLES {
if !v.iter().any(|n| n.eq_ignore_ascii_case(b)) {
v.push((*b).to_string());
}
}
v
+3 -2
View File
@@ -35,20 +35,20 @@ mod modify2;
mod mtext_opts;
mod overkill;
mod pline_opts;
pub mod plotstyle_folder;
pub mod plotters;
mod props;
pub use blocks::library::{clear_library_cache, list_library, read_library_file};
pub use dimstyle_cli::usable_dim_style_name;
pub use draw2::breakline::BreaklineOptions;
pub use props::MatchProps;
pub(crate) use props::UNIT_RANGES;
pub use props::{MatchProps, text_styles_in_use};
pub(crate) use props::{current_color_value, set_current_color_value};
mod qselect;
mod selecttools;
mod settings;
mod spline_opts;
pub mod table;
mod textstyle_cli;
mod tolerance;
mod trimextend;
pub use trimextend::PREVIEW_MAX_PICKS as TRIM_PREVIEW_MAX_PICKS;
@@ -197,6 +197,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(annotate::specs());
v.extend(dimstyles::specs());
v.extend(dimstyle_cli::specs());
v.extend(textstyle_cli::specs());
v.extend(mleader_edit::specs());
v.extend(annoscale::specs());
v.extend(hatch::specs());
-3
View File
@@ -305,9 +305,6 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
arrow,
spline,
style: style(s),
// The drawing's DIM* overrides, as a new dimension takes them: the arrowhead is then drawn
// with the DIMASZ the hook line above was sized from, and they are saved with the leader.
overrides: s.doc().map(|d| d.dim_overrides()).unwrap_or_default(),
}))?;
let annotation = match ann {
Annotation::Text(lines) => {
+1 -2
View File
@@ -6,7 +6,7 @@ use cadcraft_doc::{Drawing, Entity, EntityKind};
use serde_json::{Value, json};
use super::attribs::{attdefs, synced, update_reference_entities};
use super::purge::{leader_override_arrows, override_arrows, used_blocks};
use super::purge::{override_arrows, used_blocks};
use super::references_block;
use crate::cmd::curves::KW;
use crate::cmd::machines::{SelOutcome, SelectPhase};
@@ -96,7 +96,6 @@ fn referenced(d: &Drawing, name: &str) -> bool {
match &e.kind {
EntityKind::Insert(i) => vec![i.block.clone()],
EntityKind::Dimension(dm) => dm.block.iter().cloned().chain(override_arrows(dm)).collect(),
EntityKind::Leader(l) => leader_override_arrows(l).collect(),
EntityKind::MLeader(m) => m.block.iter().map(|b| b.block.clone()).collect(),
_ => Vec::new(),
}
-3
View File
@@ -230,9 +230,6 @@ impl Session {
/// UI's click on a dynamic grip). A list grip (visibility, lookup) or a flip grip has no
/// drag: the UI offers the choices, or flips, with `blocks.reference.set`.
pub fn start_dyn_grip(&mut self, handle: Handle, node: i32, part: GripPart) -> Result<()> {
// The value of an expression the frames are working out answers its prompt before the
// command it was typed in is cancelled for the grip.
self.lisp_settle_answer();
if self.running.is_some() {
self.cancel();
}
+15 -25
View File
@@ -14,7 +14,7 @@ use serde_json::{Value, json};
use super::super::file::io;
use super::super::modify::explode_kind;
use super::purge::{Kind, candidates, is_arrow_override, leader_override_arrows, override_arrows, override_name, scan_reads_everything};
use super::purge::{Kind, candidates, is_arrow_override, override_arrows, override_name, scan_reads_everything};
use super::{referenced_block, references_block, valid_block_name};
use crate::cmd::{bad, str_param};
use crate::{EngineError, Result, Session};
@@ -200,10 +200,8 @@ fn reachable(d: &Drawing, roots: Vec<String>) -> BTreeSet<String> {
let Some(b) = d.block(&n) else { continue };
for e in b.entities.iter() {
todo.extend(referenced_block(e));
match &e.kind {
EntityKind::Dimension(dm) => todo.extend(override_arrows(dm)),
EntityKind::Leader(l) => todo.extend(leader_override_arrows(l)),
_ => {}
if let EntityKind::Dimension(dm) = &e.kind {
todo.extend(override_arrows(dm));
}
}
}
@@ -216,10 +214,8 @@ fn needed_blocks(src: &Drawing) -> BTreeSet<String> {
let mut roots: Vec<String> = Vec::new();
for e in src.model.iter() {
roots.extend(referenced_block(e));
match &e.kind {
EntityKind::Dimension(dm) => roots.extend(override_arrows(dm)),
EntityKind::Leader(l) => roots.extend(leader_override_arrows(l)),
_ => {}
if let EntityKind::Dimension(dm) = &e.kind {
roots.extend(override_arrows(dm));
}
}
for st in &src.dim_styles {
@@ -323,20 +319,6 @@ fn rename_style_arrows(d: &mut Drawing, own: &BTreeSet<String>, renames: &Rename
}
}
/// Point the arrowhead blocks a dimension's or a leader's `overrides` name at their renamed
/// blocks. Only a block that was renamed changes the value: a number naming a block that kept
/// its name stays as it was given.
fn rename_override_arrows(overrides: &mut serde_json::Map<String, Value>, renames: &Renames) {
for (key, value) in overrides.iter_mut() {
if is_arrow_override(key)
&& let Some(b) = override_name(value)
&& let Some(n) = renames.get(&b).filter(|n| **n != b)
{
*value = json!(n);
}
}
}
/// A copy of a source entity for this drawing: a fresh handle, block references renamed, and
/// links to other source objects (associative dimension points) dropped.
fn adopt(d: &mut Drawing, src: &Drawing, e: &Entity, renames: &Renames) -> Entity {
@@ -364,9 +346,17 @@ fn adopt(d: &mut Drawing, src: &Drawing, e: &Entity, renames: &Renames) -> Entit
if let Some(n) = dm.block.as_ref().and_then(|b| renames.get(b)) {
dm.block = Some(n.clone());
}
rename_override_arrows(&mut dm.overrides, renames);
for (key, value) in dm.overrides.iter_mut() {
// Only a block that was renamed changes the value: a number naming a block that
// kept its name stays as it was given.
if is_arrow_override(key)
&& let Some(b) = override_name(value)
&& let Some(n) = renames.get(&b).filter(|n| **n != b)
{
*value = json!(n);
}
}
}
EntityKind::Leader(l) => rename_override_arrows(&mut l.overrides, renames),
EntityKind::MLeader(m) => {
if let Some(b) = &mut m.block
&& let Some(n) = renames.get(&b.block)
+2 -15
View File
@@ -147,22 +147,11 @@ pub(in crate::cmd) fn override_name(v: &Value) -> Option<String> {
/// The arrowhead block names a dimension's overrides set.
pub(in crate::cmd) fn override_arrows(dm: &cadcraft_doc::Dimension) -> impl Iterator<Item = String> + '_ {
arrows_in(&dm.overrides)
}
/// The arrowhead block names a leader's overrides set (its DIMLDRBLK), as [`override_arrows`]
/// gives a dimension's.
pub(in crate::cmd) fn leader_override_arrows(l: &cadcraft_doc::Leader) -> impl Iterator<Item = String> + '_ {
arrows_in(&l.overrides)
}
/// The arrowhead block names a set of dimension style overrides names.
fn arrows_in(overrides: &serde_json::Map<String, Value>) -> impl Iterator<Item = String> + '_ {
overrides.iter().filter(|(k, _)| is_arrow_override(k)).filter_map(|(_, v)| override_name(v)).filter(|n| !n.is_empty())
dm.overrides.iter().filter(|(k, _)| is_arrow_override(k)).filter_map(|(_, v)| override_name(v)).filter(|n| !n.is_empty())
}
/// Upper-case names of blocks reachable from model space, the layouts and dimensions, and the
/// arrowhead blocks dimension styles and dimension or leader overrides name.
/// arrowhead blocks dimension styles and dimension overrides name.
pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
let mut used = HashSet::new();
let mut frontier: Vec<String> = Vec::new();
@@ -181,7 +170,6 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
frontier.extend(dm.block.clone());
frontier.extend(override_arrows(dm));
}
EntityKind::Leader(l) => frontier.extend(leader_override_arrows(l)),
EntityKind::MLeader(m) => frontier.extend(m.block.as_ref().map(|b| b.block.clone())),
// A dimension kept as read draws, and is saved with, the block it names (#3438).
EntityKind::Unknown(u) => frontier.extend(u.dimension_block().map(str::to_string)),
@@ -201,7 +189,6 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
frontier.extend(dm.block.clone());
frontier.extend(override_arrows(dm));
}
EntityKind::Leader(l) => frontier.extend(leader_override_arrows(l)),
EntityKind::MLeader(m) => frontier.extend(m.block.as_ref().map(|b| b.block.clone())),
EntityKind::Unknown(u) => frontier.extend(u.dimension_block().map(str::to_string)),
_ => {}
+6 -4
View File
@@ -31,9 +31,8 @@ use polygon::{PolygonM, run_polygon};
use solid::{SolidM, run_solid};
pub(super) use spline::SplineM;
use spline::run_spline;
use text::{MTextM, TextM, run_mtext, run_text};
pub(crate) use text::{justify, justify_prompt};
pub(crate) use text::{fixed_height, justify, justify_prompt};
/// Every draw command's spec: JSON parameters, menu path, aliases and the interactive prompt
/// machine each command starts.
@@ -110,13 +109,16 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("text", "Single Line Text", run_text)
.menu(&["Draw", "Text", "Single Line Text"])
.alias(&["dt", "dtext"])
.params("{at, text, height?, rotation? (degrees), justify?: L|C|R|M|TL|TC|TR|ML|MC|MR|BL|BC|BR}")
.params(
"{at, text, height? (default: the style's fixed height, else TEXTSIZE), rotation? (degrees), justify?: L|C|R|M|TL|TC|TR|ML|MC|MR|BL|BC|BR, \
style? (default: the current style; the text takes its width factor and obliquing angle)}",
)
.interactive(|s| Ok(Box::new(TextM::new(s)))),
CommandSpec::new("mtext", "Multiline Text", run_mtext)
.menu(&["Draw", "Text", "Multiline Text..."])
.alias(&["t", "mt"])
.params(
"{at, text, height?, width?, attach?: 1..9 | justify?: TL..BR, rotation?, style?, lineSpacing?, lineSpacingExact?, \
"{at, text, height? (default: the style's fixed height, else TEXTSIZE), width?, attach?: 1..9 | justify?: TL..BR, rotation?, style?, lineSpacing?, lineSpacingExact?, \
list?: bullet|number|lower|upper, indent?, firstIndent?, rightIndent?, tabs?: [..], align?: left|center|right|justify|distributed, \
columns?: {type: static|dynamic, count?, gutter?, height, heights?, reversed?}} (indents and tabs in text heights; width = one column)",
)
+192 -40
View File
@@ -35,11 +35,44 @@ pub(crate) fn justify_prompt(two_points: bool) -> Prompt {
Prompt::new("Enter an option", Accept::TEXT).kw(&options)
}
pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotation: f64, j: (HAlign, VAlign)) -> EntityKind {
let style = s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into());
// New text takes Backwards and Upside down from its style, as AutoCAD's does; later style
// changes don't change them.
let (backwards, upside_down) = s.doc().ok().and_then(|d| d.text_style(&style)).map_or((false, false), |t| (t.backwards, t.upside_down));
/// Justification → the name TEXT's status line gives it.
fn justify_name(j: (HAlign, VAlign)) -> &'static str {
match j {
(HAlign::Left, VAlign::Baseline) => "Left",
(HAlign::Center, VAlign::Baseline) => "Center",
(HAlign::Right, VAlign::Baseline) => "Right",
(HAlign::Aligned, _) => "Align",
(HAlign::Middle, _) => "Middle",
(HAlign::Fit, _) => "Fit",
(HAlign::Left, VAlign::Top) => "TL",
(HAlign::Center, VAlign::Top) => "TC",
(HAlign::Right, VAlign::Top) => "TR",
(HAlign::Left, VAlign::Middle) => "ML",
(HAlign::Center, VAlign::Middle) => "MC",
(HAlign::Right, VAlign::Middle) => "MR",
(HAlign::Left, VAlign::Bottom) => "BL",
(HAlign::Center, VAlign::Bottom) => "BC",
(HAlign::Right, VAlign::Bottom) => "BR",
}
}
/// The height text style `style` fixes for its text (`None`: asked when text is placed).
pub(crate) fn fixed_height(d: &cadcraft_doc::Drawing, style: &str) -> Option<f64> {
d.text_style(style).map(|t| t.height).filter(|h| h.is_finite() && *h > 0.0)
}
/// TEXT in `style`, which gives it its width factor and obliquing angle, as AutoCAD's new text
/// takes them from its style (later style changes don't change them). Backwards and upside down
/// come from the same style, as AutoCAD's do.
pub(crate) fn make_text(s: &Session, style: &str, at: Vec2, value: &str, height: f64, rotation: f64, j: (HAlign, VAlign)) -> EntityKind {
let (width_factor, oblique) = s
.doc()
.ok()
.and_then(|d| d.text_style(style))
.map(|t| (t.width_factor, t.oblique))
.filter(|(w, o)| w.is_finite() && *w > 0.0 && o.is_finite())
.unwrap_or((1.0, 0.0));
let (backwards, upside_down) = s.doc().ok().and_then(|d| d.text_style(style)).map_or((false, false), |t| (t.backwards, t.upside_down));
let (h, v) = j;
let left = h == HAlign::Left && v == VAlign::Baseline;
EntityKind::Text(Text {
@@ -48,9 +81,9 @@ pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotatio
height,
value: value.into(),
rotation,
width_factor: 1.0,
oblique: 0.0,
style,
width_factor,
oblique,
style: style.to_string(),
halign: h,
valign: v,
backwards,
@@ -58,29 +91,38 @@ pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotatio
})
}
/// A `style` parameter: the drawing's style of that name, else the current style.
fn style_param(s: &Session, cmd: &str, p: &Value) -> Result<String> {
let d = s.doc()?;
match str_param(p, "style") {
Some(n) => d.text_style(n).map(|t| t.name.clone()).ok_or_else(|| bad(cmd, format!("no text style \"{n}\""))),
None => Ok(d.header.str("TEXTSTYLE", "Standard")),
}
}
pub(super) fn run_text(s: &mut Session, p: &Value) -> Result<Value> {
let at = point_req("text", p, "at")?;
let text = str_param(p, "text").ok_or_else(|| bad("text", "`text` is required"))?;
let height = f64_or(p, "height", s.doc()?.header.f64("TEXTSIZE", 0.2));
if height <= 0.0 {
let style = style_param(s, "text", p)?;
let d = s.doc()?;
let height = f64_or(p, "height", fixed_height(d, &style).unwrap_or_else(|| d.header.f64("TEXTSIZE", 0.2)));
if !(height > 0.0 && height.is_finite()) {
return Err(bad("text", "height must be positive"));
}
let j = justify(str_param(p, "justify").unwrap_or("L")).ok_or_else(|| bad("text", "unknown justification"))?;
let k = make_text(s, at, text, height, f64_or(p, "rotation", 0.0).to_radians(), j);
let k = make_text(s, &style, at, text, height, f64_or(p, "rotation", 0.0).to_radians(), j);
added(s.add_entity(k)?)
}
pub(super) fn run_mtext(s: &mut Session, p: &Value) -> Result<Value> {
let at = point_req("mtext", p, "at")?;
let text = str_param(p, "text").ok_or_else(|| bad("mtext", "`text` is required"))?;
let height = f64_or(p, "height", s.doc()?.header.f64("TEXTSIZE", 0.2));
if height <= 0.0 {
let style = style_param(s, "mtext", p)?;
let d = s.doc()?;
let height = f64_or(p, "height", fixed_height(d, &style).unwrap_or_else(|| d.header.f64("TEXTSIZE", 0.2)));
if !(height > 0.0 && height.is_finite()) {
return Err(bad("mtext", "height must be positive"));
}
let style = match str_param(p, "style") {
Some(n) => s.doc()?.text_style(n).map(|t| t.name.clone()).ok_or_else(|| bad("mtext", format!("no text style \"{n}\"")))?,
None => s.doc()?.header.str("TEXTSTYLE", "Standard"),
};
let attach = match str_param(p, "justify") {
Some(j) => crate::cmd::mtext_opts::attach_code(j).ok_or_else(|| bad("mtext", "`justify` must be TL, TC, TR, ML, MC, MR, BL, BC or BR"))?,
None => p.get("attach").and_then(Value::as_u64).unwrap_or(1).clamp(1, 9) as u8,
@@ -102,13 +144,23 @@ pub(super) fn run_mtext(s: &mut Session, p: &Value) -> Result<Value> {
added(s.add_entity(k)?)
}
/// A question TEXT asks besides its main prompts.
#[derive(Clone, Copy, PartialEq)]
enum TextAsk {
Justify,
Style,
StyleList,
}
pub(super) struct TextM {
at: Option<Vec2>,
height: Option<f64>,
rotation: Option<f64>,
justify: (HAlign, VAlign),
asking_justify: bool,
ask: Option<TextAsk>,
line: usize,
/// The style of the text continued below (Enter at the start point); else the current one.
style: Option<String>,
/// Run by a LISP routine (`command`): one line of text ends the command, as AutoLISP's
/// `command` runs TEXT; typed and in scripts each line asks for the next.
single_line: bool,
@@ -121,11 +173,58 @@ impl TextM {
height: None,
rotation: None,
justify: (HAlign::Left, VAlign::Baseline),
asking_justify: false,
ask: None,
line: 0,
style: None,
single_line: s.lisp_running(),
}
}
/// The style new lines are set in.
fn style(&self, s: &Session) -> String {
self.style.clone().unwrap_or_else(|| s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into()))
}
/// The status line: the style, the height it fixes (else TEXTSIZE), annotative, justify.
fn status(&self, s: &mut Session) -> Result<()> {
let style = self.style(s);
let d = s.doc()?;
let anno = if d.text_style(&style).is_some_and(|st| st.annotative) { "Yes" } else { "No" };
let height = fixed_height(d, &style).unwrap_or_else(|| d.header.f64("TEXTSIZE", 0.2));
s.echo(format!("Current text style: \"{style}\" Text height: {height:.4} Annotative: {anno} Justify: {}", justify_name(self.justify)));
Ok(())
}
/// Continue directly below the last TEXT in this space, with its style, height, rotation and
/// justification, as Enter at AutoCAD's start point does. False when there is none.
fn continue_below(&mut self, s: &Session) -> bool {
let Ok(d) = s.doc() else { return false };
let last = d.space(&s.space()).and_then(|st| st.iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t) } else { None }).last());
let Some(t) = last else { return false };
let usable = |h: f64| h.is_finite() && h > 0.0;
let h = if usable(t.height) {
t.height
} else {
let size = d.header.f64("TEXTSIZE", 0.2);
// Neither the last text's height nor TEXTSIZE can space the next line: nothing to continue.
if !usable(size) {
return false;
}
size
};
let r = if t.rotation.is_finite() { t.rotation } else { 0.0 };
// Aligned and fit text need two points: the next line is left-justified at the start point.
let (j, from) = match t.halign {
HAlign::Aligned | HAlign::Fit => ((HAlign::Left, VAlign::Baseline), t.insert.xy()),
_ => ((t.halign, t.valign), t.justify_point()),
};
self.at = Some(from + Vec2::from_angle(r - std::f64::consts::FRAC_PI_2) * (h * 5.0 / 3.0));
self.height = Some(h);
self.rotation = Some(r);
self.justify = j;
self.style = d.text_style(&t.style).map(|st| st.name.clone());
true
}
}
impl Interactive for TextM {
@@ -134,43 +233,96 @@ impl Interactive for TextM {
}
fn prompt(&self, s: &Session) -> Prompt {
let th = s.doc().map(|d| d.header.f64("TEXTSIZE", 0.2)).unwrap_or(0.2);
if self.asking_justify {
return justify_prompt(true);
match self.ask {
Some(TextAsk::Justify) => {
return justify_prompt(true);
}
Some(TextAsk::Style) => return Prompt::new("Enter style name", Accept::TEXT).kw(&["?"]).default(self.style(s)),
Some(TextAsk::StyleList) => return Prompt::new("Enter text style(s) to list", Accept::TEXT).default("*"),
None => {}
}
match (self.at, self.height, self.rotation) {
(None, _, _) => Prompt::new("Specify start point of text", Accept::POINT).kw(&["Justify", "Style"]),
(Some(a), None, _) => Prompt::new("Specify height", Accept::POINT_OR_NUMBER).default(format!("{th:.4}")).base(a),
(Some(a), None, _) => {
// An annotative style's text is sized as it measures on paper.
let annotative = s.doc().is_ok_and(|d| d.text_style(&self.style(s)).is_some_and(|st| st.annotative));
let ask = if annotative { "Specify paper text height" } else { "Specify height" };
Prompt::new(ask, Accept::POINT_OR_NUMBER).default(format!("{th:.4}")).base(a)
}
(Some(a), Some(_), None) => Prompt::new("Specify rotation angle of text", Accept::POINT_OR_NUMBER).default("0").base(a),
_ => Prompt::new("Enter text", Accept::TEXT),
}
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
let d = s.doc()?;
let style = d.header.str("TEXTSTYLE", "Standard");
let anno = if d.text_style(&style).is_some_and(|st| st.annotative) { "Yes" } else { "No" };
let msg =
format!("Current text style: \"{style}\" Text height: {:.4} Annotative: {anno} Justify: Left", d.header.f64("TEXTSIZE", 0.2));
s.echo(msg);
self.status(s)?;
Ok(Step::Continue)
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if self.asking_justify {
let code = match &i {
Input::Keyword(k) | Input::Text(k) => k.clone(),
_ => return Ok(Step::Continue),
};
self.justify = justify(&code).unwrap_or(self.justify);
self.asking_justify = false;
return Ok(Step::Continue);
let word = match &i {
Input::Keyword(k) | Input::Text(k) => Some(k.trim().to_string()),
_ => None,
};
match self.ask {
Some(TextAsk::Justify) => {
// Enter leaves the question with the justification as it was (as Style's does).
let Some(code) = word.filter(|w| !w.is_empty()) else {
self.ask = None;
return Ok(Step::Continue);
};
// As MTEXT's: an answer that is no option is refused, and asked again.
self.justify = justify(&code).ok_or_else(|| crate::EngineError::Other("Invalid option keyword.".into()))?;
self.ask = None;
return Ok(Step::Continue);
}
Some(TextAsk::Style) => {
match word.as_deref() {
None | Some("") => self.ask = None,
Some("?") => self.ask = Some(TextAsk::StyleList),
Some(name) => {
let found = s.doc()?.text_style(name).map(|t| t.name.clone());
let name = found.ok_or_else(|| crate::EngineError::Other(format!("Cannot find text style \"{name}\".")))?;
// Like AutoCAD's Style option, the style becomes current.
s.doc_mut()?.header.set_str("TEXTSTYLE", &name);
self.style = None;
self.ask = None;
self.status(s)?;
}
}
return Ok(Step::Continue);
}
Some(TextAsk::StyleList) => {
let pattern = word.filter(|w| !w.is_empty()).unwrap_or_else(|| "*".into());
let d = s.doc()?;
let lines: Vec<String> =
crate::cmd::textstyle_cli::styles_matching(d, &pattern).into_iter().map(crate::cmd::textstyle_cli::listing).collect();
for l in lines {
s.echo(l);
}
self.ask = Some(TextAsk::Style);
return Ok(Step::Continue);
}
None => {}
}
let th = s.doc()?.header.f64("TEXTSIZE", 0.2);
match (self.at, self.height, self.rotation, i) {
(None, _, _, Input::Keyword(k)) if k == "Justify" => self.asking_justify = true,
(None, _, _, Input::Point(p)) => self.at = Some(p),
(None, _, _, Input::Keyword(k)) if k == "Justify" => self.ask = Some(TextAsk::Justify),
(None, _, _, Input::Keyword(k)) if k == "Style" => self.ask = Some(TextAsk::Style),
(None, _, _, Input::Point(p)) => {
self.at = Some(p);
// A fixed-height style isn't asked for a height.
self.height = fixed_height(s.doc()?, &self.style(s));
}
(None, _, _, Input::Enter) => {
if !self.continue_below(s) {
return Ok(Step::Done);
}
}
(Some(_), None, _, Input::Enter) => self.height = Some(th),
(Some(a), None, _, Input::Point(p)) => self.height = Some(a.dist(p).max(1e-9)),
(Some(_), None, _, Input::Text(t)) => {
let h = number(&t).filter(|h| *h > 0.0).ok_or_else(|| crate::EngineError::Other("Requires a positive height.".into()))?;
let h = number(&t)
.filter(|h| *h > 0.0 && h.is_finite())
.ok_or_else(|| crate::EngineError::Other("Requires a positive height.".into()))?;
self.height = Some(h);
s.doc_mut()?.header.set_f64("TEXTSIZE", h);
}
@@ -181,7 +333,7 @@ impl Interactive for TextM {
}
(Some(a), Some(h), Some(r), Input::Text(t)) => {
let at = a + Vec2::from_angle(r - std::f64::consts::FRAC_PI_2) * (h * 5.0 / 3.0 * self.line as f64);
let k = make_text(s, at, &t, h, r, self.justify);
let k = make_text(s, &self.style(s), at, &t, h, r, self.justify);
s.add_entity(k)?;
self.line += 1;
if self.single_line {
-3
View File
@@ -73,10 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
/// A programmatic undo/redo (`engine.execute`, MCP, control channel, scripts) first ends a running
/// command the way Esc does, exactly as `Session::start` does for Cmd+Z, the menu or the command
/// line. Otherwise it would swap the drawing under the command and pop the previous command's step.
/// As there, the value of an expression the frames are working out answers its prompt first: the
/// command it ends is the step to take back.
fn end_running_command(s: &mut Session) {
s.lisp_settle_answer();
if s.running.is_some() {
s.cancel();
}
-58
View File
@@ -382,18 +382,6 @@ pub fn specs() -> Vec<CommandSpec> {
)
.noundo(),
CommandSpec::new("document.switch", "Switch Drawing", run_switch).params("{index}").enabled(always).noundo(),
CommandSpec::new("document.next", "Next Drawing", |s, _| run_cycle(s, true))
.menu(&["Window", "Next Drawing"])
.key(if cfg!(target_os = "macos") { "Ctrl+Tab" } else { "Cmd+Tab" })
.params("{} → {index}: the open drawing after this one, the first after the last")
.enabled(always)
.noundo(),
CommandSpec::new("document.prev", "Previous Drawing", |s, _| run_cycle(s, false))
.menu(&["Window", "Previous Drawing"])
.key(if cfg!(target_os = "macos") { "Ctrl+Shift+Tab" } else { "Cmd+Shift+Tab" })
.params("{} → {index}: the open drawing before this one, the last before the first")
.enabled(always)
.noundo(),
CommandSpec::new("document.bytes", "Drawing as bytes", run_bytes)
.params("{format?: dxf, version?: 2000…2018, binary?: bool, portableFonts?: bool} → {data: base64, warnings?: what an image draws short of the drawing}")
.noundo(),
@@ -681,14 +669,6 @@ fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(usi
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."));
}
// A saved drawing carries the folder's plot style tables its layouts use.
if is_drawing_file(path) {
let st = s.state_mut()?;
let mut d = st.drawing().clone();
if super::layout::keep_used_folder_copies(std::sync::Arc::make_mut(&mut d)) {
*st.drawing_arc_mut() = d;
}
}
let (bytes, notes) = write_bytes(s, cmd, path, opts)?;
let n = commit_save(s, path, &bytes, store)?;
if is_drawing_file(path) {
@@ -1048,17 +1028,6 @@ fn run_switch(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// `document.next` and `document.prev`: switch to the neighbouring open drawing, wrapping round at either end. With one drawing open nothing changes.
fn run_cycle(s: &mut Session, forward: bool) -> Result<Value> {
let count = s.docs.len();
if count < 2 {
return Ok(json!({ "index": s.active }));
}
let i = if forward { (s.active + 1) % count } else { (s.active + count - 1) % count };
run_switch(s, &json!({ "index": i }))?;
Ok(json!({ "index": i }))
}
fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
let fmt = str_param(p, "format").unwrap_or("dxf");
let opts = save_options("document.bytes", p)?;
@@ -1529,33 +1498,6 @@ mod tests {
s.execute("close", &json!({"index": 2})).unwrap();
assert_eq!(active_title(&s), "Drawing2");
}
#[test]
fn next_and_previous_drawing_wrap_round_and_end_the_running_command() {
let mut s = Session::new();
s.execute("new", &json!({})).unwrap();
s.execute("new", &json!({})).unwrap();
assert_eq!((s.docs.len(), s.active), (3, 2));
assert_eq!(s.execute("document.next", &json!({})).unwrap()["index"], 0, "after the last comes the first");
assert_eq!(s.active, 0);
assert_eq!(s.execute("document.prev", &json!({})).unwrap()["index"], 2, "before the first comes the last");
s.execute("document.prev", &json!({})).unwrap();
assert_eq!(s.active, 1);
s.cmdline("line").unwrap();
assert!(s.running.is_some());
s.execute("document.next", &json!({})).unwrap();
assert!(s.running.is_none(), "a command left running belongs to the drawing it started in");
assert_eq!(s.active, 2);
}
#[test]
fn next_drawing_with_one_drawing_open_changes_nothing() {
let mut s = Session::new();
assert_eq!(s.docs.len(), 1);
assert_eq!(s.execute("document.next", &json!({})).unwrap()["index"], 0);
assert_eq!(s.execute("document.prev", &json!({})).unwrap()["index"], 0);
assert_eq!(s.docs.len(), 1);
}
}
#[cfg(test)]
-3
View File
@@ -520,9 +520,6 @@ impl Session {
/// view being edited does not show are left out (the first grip left is the base grip), and it
/// is an error when none is left.
pub fn start_grip_edit(&mut self, hot: &[(Handle, usize)]) -> Result<()> {
// The value of an expression the frames are working out answers its prompt before the
// command it was typed in is cancelled for the grips.
self.lisp_settle_answer();
if self.running.is_some() {
self.cancel();
}
+10 -49
View File
@@ -15,7 +15,6 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
use viewports::MviewM;
mod plotstyle;
pub(crate) use plotstyle::keep_used_folder_copies;
mod prompts;
mod viewports;
@@ -83,18 +82,18 @@ 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\"|\"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}; layout \"Model\" keeps only plotStyleTable",
"{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}",
),
// PLOT and EXPORTPDF are undoable for what a plot keeps in the drawing (a folder table's
// copy, Model's table); a plot that changes nothing leaves no undo step.
CommandSpec::new("plot", "Print...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "plot")?, "plot"))
.menu(&["File", "Print..."])
.key("Cmd+P")
.alias(&["print"])
.params("{path? (else returns base64 `data`), layout?: current|\"Model\", device?: \"CADCraft PDF\"|\"CADCraft PNG\"|\"CADCraft SVG\" | a plotter from PLOTTERMANAGER | \"None\" (default: a layout's page setup device; Model, or \"None\": no device, PDF; a device sets the output format and the papers), paper?: the device's paper (default: a layout keeps its page setup's; Model takes the device's default), landscape?, fit?: bool, scale?: number | \"1:50\", center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?: bool, plotTransparency?: bool (default: the page setup's; PLOTTRANSPARENCYOVERRIDE 0/2 overrides it), plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]]} (typed or from the menu: the Plot dialog)"),
.params("{path? (else returns base64 `data`), layout?: current|\"Model\", device?: \"CADCraft PDF\"|\"CADCraft PNG\"|\"CADCraft SVG\" | a plotter from PLOTTERMANAGER | \"None\" (default: a layout's page setup device; Model, or \"None\": no device, PDF; a device sets the output format and the papers), paper?: the device's paper (default: a layout keeps its page setup's; Model takes the device's default), landscape?, fit?: bool, scale?: number | \"1:50\", center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?: bool, plotTransparency?: bool (default: the page setup's; PLOTTRANSPARENCYOVERRIDE 0/2 overrides it), plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]]} (typed or from the menu: the Plot dialog)")
.noundo(),
CommandSpec::new("exportpdf", "Export to PDF...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "exportpdf")?, "exportpdf"))
.menu(&["File", "Export to PDF..."])
.params("{path? (else returns base64 `data`), layout?, device? (its papers; the output stays PDF), paper?, landscape?, fit?, scale?, center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?, plotTransparency?, plotArea?, window?} (as PLOT)"),
.params("{path? (else returns base64 `data`), layout?, device? (its papers; the output stays PDF), paper?, landscape?, fit?, scale?, center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?, plotTransparency?, plotArea?, window?} (as PLOT)")
.noundo(),
CommandSpec::new("mspace", "Model Space (in viewport)", run_mspace)
.alias(&["ms"])
.params("{handle?: viewport, at?: [x,y] paper point inside a viewport} (default: the last active or first viewport)")
@@ -813,27 +812,13 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
"plotTransparency",
];
let changes = keys.iter().any(|k| p.get(k).is_some());
// Model keeps only its plot style table (the rest of its plot settings are chosen per plot).
if str_param(p, "layout").is_some_and(|n| n.eq_ignore_ascii_case("model")) {
if let Some(k) = keys.iter().find(|k| **k != "plotStyleTable" && p.get(**k).is_some()) {
return Err(bad(cmd, format!("Model keeps only `plotStyleTable`; `{k}` is chosen for each plot")));
}
if let Some(v) = str_param(p, "plotStyleTable")
&& plotstyle::table_choice_changes(s.doc()?, v, true)
&& plotstyle::set_model_table(s.doc_mut()?, v)
{
s.touch();
}
let table = s.doc()?.model_page.as_ref().map(|m| m.plot_style_table.clone()).unwrap_or_default();
return Ok(json!({ "layout": "Model", "page": { "plotStyleTable": table } }));
}
let name = match str_param(p, "layout") {
Some(n) => Some(layout_name(cmd, s.doc()?, n)?),
None => s.space().layout().map(str::to_string),
};
let Some(name) = name else {
if changes {
return Err(bad(cmd, "pass `layout` (Model keeps only its `plotStyleTable`, with `layout: \"Model\"`)"));
return Err(bad(cmd, "pass `layout` (model-space page setups are not stored yet)"));
}
// Report every layout's page setup.
let d = s.doc()?;
@@ -942,8 +927,6 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
}
if let Some(v) = str_param(p, "plotStyleTable") {
page.plot_style_table = v.chars().take(260).collect();
// A table from the user's plot style folder travels with the drawing.
plotstyle::keep_folder_copy(s.doc_mut()?, &page.plot_style_table);
}
if let Some(v) = p.get("displayPlotStyles").and_then(Value::as_bool) {
page.show_plot_styles = v;
@@ -1074,7 +1057,7 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
};
let pages = sheets.as_ref().map_or(1, Vec::len);
let format = opts.get("output").and_then(Value::as_str).map(str::to_ascii_lowercase).unwrap_or_else(|| "pdf".into());
let r = match str_param(p, "path") {
match str_param(p, "path") {
Some(_path) => {
#[cfg(not(target_arch = "wasm32"))]
{
@@ -1087,44 +1070,22 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
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);
r
Ok(r)
}
#[cfg(target_arch = "wasm32")]
{
super::exchange::deliver_file(cmd, _path, &bytes, super::file::deliver())?;
let mut r = json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_notes(s, &mut r, notes);
r
Ok(r)
}
}
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);
r
}
};
// A table from the user's plot style folder that a plot used travels with the drawing, as
// one chosen in a page setup does, and Model, which has no page setup dialog of its own,
// remembers the table it last plotted with. A preview (an image with no file) changes nothing,
// and so does a plot whose output was refused or failed: this runs only once it is written.
if let Some(table) = str_param(p, "plotStyleTable")
&& (str_param(p, "path").is_some() || !is_image)
{
// Model is the sheet plotted when `layouts` names it alone, whatever tab is showing.
let model = match sheets.as_deref() {
Some(names) => matches!(names, [only] if only.eq_ignore_ascii_case("model")),
None => matches!(space, Space::Model),
};
// Checked first: `doc_mut` copies the drawing, which records an undo step even for no change.
if plotstyle::table_choice_changes(s.doc()?, table, model) {
let d = s.doc_mut()?;
let changed = if model { plotstyle::set_model_table(d, table) } else { plotstyle::keep_folder_copy(d, table) };
if changed {
s.touch();
}
Ok(r)
}
}
Ok(r)
}
/// The model-space rectangle a plot of `plotArea` covers: `extents` (default) plots everything,
+40 -296
View File
@@ -1,16 +1,9 @@
//! Plot styles: PLOTSTYLE (an object's or the current named plot style) and STYLESMANAGER (the
//! plot style tables: list, view, create, edit, rename, delete, load and save in our own file
//! format).
//! plot style tables: list, view, create, edit, delete, load and save in our own file format).
//!
//! A table lives in the user's plot style folder ([`super::super::plotstyle_folder`]), which
//! every drawing can use, or in the drawing (`Drawing::plot_style_tables`, saved with it). The
//! drawing's table wins over a folder's of the same name, and both over a built-in one. A page
//! setup (a layout's or Model's) or a plot that uses a folder table takes a copy of it into the
//! drawing, which from then on plots with its copy whatever happens to the file. Editing a
//! built-in table stores an edited copy in the drawing.
//!
//! Changes to the folder's files are written at once: UNDO takes back the drawing's copy, not the
//! file.
//! Tables the drawing keeps live in `Drawing::plot_style_tables` and are saved with it; they
//! shadow built-in tables of the same name. Editing a built-in table stores an edited copy in
//! the drawing.
use cadcraft_doc::{Drawing, PlotStyle, PlotStyleKind, PlotStyleTable};
use serde_json::{Value, json};
@@ -28,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("stylesmanager", "Plot Style Manager...", run_stylesmanager)
.menu(&["File", "Plot Styles..."])
.params(
"{action?: list (default)|get|new|set|rename|delete|load|save|reload, name?: table (\"x.ctb\"/\"x.stb\"), where?: folder|drawing (new, load: default drawing; get, set, rename, delete: default the drawing's table, else the folder's), kind?: colorDependent|named (new), from?: table to copy (new), fromWhere?: folder|drawing (new: where `from` is; default the drawing's table, else the folder's, else built-in), description?, style?: {name, color?: \"#rrggbb\"|null, grayscale?, screening?: 0-100, linetype?: name|null, lineweight?: mm|null, end?, join?, fill?, description?} (set), removeStyle?: name (set, named tables), to?: new name (rename), path? (load/save; save without one returns `text`), text? (load)} (folder tables are files in the settings folder's `plotstyles` folder; list reports it in `folder`)",
"{action?: list (default)|get|new|set|delete|load|save, name?: table (\"x.ctb\"/\"x.stb\"), kind?: colorDependent|named (new), from?: table to copy (new), description?, style?: {name, color?: \"#rrggbb\"|null, grayscale?, screening?: 0-100, linetype?: name|null, lineweight?: mm|null, end?, join?, fill?, description?} (set), removeStyle?: name (set, named tables), path? (load/save; save without one returns `text`), text? (load)}",
),
]
}
@@ -100,165 +93,18 @@ fn run_plotstyle(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- STYLESMANAGER ----------
fn in_drawing(d: &Drawing, name: &str) -> bool {
d.plot_style_tables.iter().any(|x| x.name.eq_ignore_ascii_case(name.trim()))
}
fn in_folder(name: &str) -> bool {
cadcraft_doc::plot_style_folder_table(name).is_some()
}
fn table_summary(d: &Drawing, t: &PlotStyleTable) -> Value {
let drawing = in_drawing(d, &t.name);
let folder = in_folder(&t.name);
let in_drawing = d.plot_style_tables.iter().any(|x| x.name.eq_ignore_ascii_case(&t.name));
json!({
"name": t.name,
"description": t.description,
"kind": if t.is_color_dependent() { "colorDependent" } else { "named" },
"styles": t.styles.len(),
"source": if drawing { "drawing" } else if folder { "folder" } else { "builtin" },
"inFolder": folder,
"inDrawing": drawing,
"builtin": PlotStyleTable::builtin(&t.name).is_some() && !drawing && !folder,
"inDrawing": in_drawing,
"builtin": PlotStyleTable::builtin(&t.name).is_some() && !in_drawing,
})
}
/// Where a table goes or comes from.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Where {
Folder,
Drawing,
}
fn where_param(cmd: &str, p: &Value) -> Result<Option<Where>> {
place_param(cmd, p, "where")
}
/// A place parameter (`where`, or `fromWhere` for `new`'s `from`): folder or drawing.
fn place_param(cmd: &str, p: &Value, key: &str) -> Result<Option<Where>> {
match str_param(p, key).map(str::to_ascii_lowercase).as_deref() {
None => Ok(None),
Some("folder") => Ok(Some(Where::Folder)),
Some("drawing") => Ok(Some(Where::Drawing)),
Some(_) => Err(bad(cmd, format!("`{key}` must be folder or drawing"))),
}
}
/// `name` with the ending a table of `t`'s kind needs (added when it has none), at most 255
/// characters with it: the length every action that looks a table up reads (`table_name`).
fn with_ending(cmd: &str, t: &PlotStyleTable, name: &str) -> Result<String> {
let ext = if t.is_color_dependent() { ".ctb" } else { ".stb" };
let lower = name.to_ascii_lowercase();
if !lower.ends_with(ext) && (lower.ends_with(".ctb") || lower.ends_with(".stb")) {
return Err(bad(cmd, format!("a {} table's name ends in {ext}", if ext == ".ctb" { "colour-dependent" } else { "named" })));
}
let full = if lower.ends_with(ext) { name.to_string() } else { format!("{name}{ext}") };
if full.chars().count() > 255 {
return Err(bad(cmd, "a plot style table's name is at most 255 characters, with its ending"));
}
Ok(full)
}
/// Write `t` to the plot style folder.
fn write_folder(cmd: &str, t: &PlotStyleTable) -> Result<()> {
super::super::plotstyle_folder::write(t).map_err(|e| bad(cmd, e))
}
/// Copy the folder's table `name` into `d` when `d` has no table of that name: a layout that
/// chooses a folder table takes it into the drawing, and the drawing then plots with its copy
/// whatever later happens to the file. A table the drawing already has is left as it is.
/// Returns whether a copy was taken.
pub(super) fn keep_folder_copy(d: &mut Drawing, name: &str) -> bool {
let name = name.trim();
if !needs_folder_copy(d, name) {
return false;
}
match cadcraft_doc::plot_style_folder_table(name) {
Some(t) => {
store(d, t);
true
}
None => false,
}
}
/// Whether the drawing lacks the folder table `name`, which `keep_folder_copy` would copy in.
fn needs_folder_copy(d: &Drawing, name: &str) -> bool {
let name = name.trim();
!cadcraft_doc::no_plot_style_table(name) && !in_drawing(d, name) && cadcraft_doc::plot_style_folder_table(name).is_some()
}
/// `name` as Model's page setup keeps it: empty for no table.
fn model_name(name: &str) -> String {
let name: String = name.trim().chars().take(260).collect();
if cadcraft_doc::no_plot_style_table(&name) { String::new() } else { name }
}
/// Whether Model's table is something other than `name` (as `model_name` keeps it).
fn model_differs(d: &Drawing, name: &str) -> bool {
let current = d.model_page.as_ref().map(|p| p.plot_style_table.trim()).unwrap_or_default();
!current.eq_ignore_ascii_case(name)
}
/// Whether choosing `name` would change `d`: Model's table (`model`), or a folder copy the
/// drawing lacks. Read first, as changing the drawing copies it and records an undo step.
pub(crate) fn table_choice_changes(d: &Drawing, name: &str, model: bool) -> bool {
(model && model_differs(d, &model_name(name))) || needs_folder_copy(d, name)
}
/// Remember `name` as Model's plot style table. Model keeps no other page settings here, so its
/// page setup is the one the DXF writer gives it otherwise, with this table; `"None"` or an empty
/// name clears it. A folder table is copied into the drawing. Returns whether anything changed.
pub(crate) fn set_model_table(d: &mut Drawing, name: &str) -> bool {
let name = model_name(name);
let changed = model_differs(d, &name);
if changed {
d.model_page
.get_or_insert_with(|| cadcraft_doc::PageSetup { plot_area: "extents".into(), scale_to_fit: true, ..Default::default() })
.plot_style_table = name.clone();
}
keep_folder_copy(d, &name) || changed
}
/// Copy into `d` every folder table its page setups (each layout's and Model's) use that it
/// doesn't have yet, so a saved drawing carries all its plot style tables (like the built-in
/// ones, it then plots the same on a computer without the files). Returns whether anything was
/// copied.
pub(crate) fn keep_used_folder_copies(d: &mut Drawing) -> bool {
let used: Vec<String> = d.layouts.iter().map(|l| &l.page).chain(d.model_page.as_ref()).map(|page| page.plot_style_table.clone()).collect();
let mut copied = false;
for name in used {
copied |= keep_folder_copy(d, &name);
}
copied
}
/// Which table `name` an action works on: `where` when given, else the drawing's (the one its
/// layouts plot with), else the folder's. `None` for a table in neither (a built-in one).
fn place_of(cmd: &str, s: &Session, p: &Value, name: &str) -> Result<Option<Where>> {
Ok(match where_param(cmd, p)? {
Some(w) => Some(w),
None if in_drawing(s.doc()?, name) => Some(Where::Drawing),
None if in_folder(name) => Some(Where::Folder),
None => None,
})
}
/// Table `name` from `place`, or as the drawing sees it when `place` is `None`.
fn table_at(cmd: &str, d: &Drawing, name: &str, place: Option<Where>) -> Result<PlotStyleTable> {
let found = match place {
Some(Where::Drawing) => d.plot_style_tables.iter().find(|t| t.name.eq_ignore_ascii_case(name.trim())).cloned(),
Some(Where::Folder) => cadcraft_doc::plot_style_folder_table(name.trim()),
None => cadcraft_doc::plot_style_table(d, name),
};
let here = match place {
Some(Where::Drawing) => " in the drawing",
Some(Where::Folder) => " in the plot style folder",
None => "",
};
found.ok_or_else(|| bad(cmd, format!("no plot style table `{name}`{here}")))
}
fn table_name(cmd: &str, p: &Value) -> Result<String> {
let n = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "`name` (the table) is required"))?;
Ok(n.chars().take(255).collect())
@@ -346,30 +192,18 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "stylesmanager";
let action = str_param(p, "action").unwrap_or("list").to_ascii_lowercase();
match action.as_str() {
"list" | "reload" => {
if action == "reload" {
super::super::plotstyle_folder::reload();
for st in &mut s.docs {
st.revision += 1;
}
}
"list" => {
let d = s.doc()?;
let tables: Vec<Value> = cadcraft_doc::plot_style_table_names(d)
.iter()
.filter_map(|n| cadcraft_doc::plot_style_table(d, n))
.map(|t| table_summary(d, &t))
.collect();
Ok(json!({
"tables": tables,
"folder": super::super::plotstyle_folder::location(),
"warnings": super::super::plotstyle_folder::warnings(),
}))
Ok(json!({ "tables": tables }))
}
"get" => {
let name = table_name(cmd, p)?;
let place = where_param(cmd, p)?;
let d = s.doc()?;
let t = table_at(cmd, d, &name, place)?;
let t = find_table(cmd, d, &table_name(cmd, p)?)?;
let mut v = serde_json::to_value(&t).unwrap_or(Value::Null);
if let (Some(o), Value::Object(sum)) = (v.as_object_mut(), table_summary(d, &t)) {
o.insert("inDrawing".into(), sum.get("inDrawing").cloned().unwrap_or(Value::Null));
@@ -381,8 +215,7 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
let mut name = table_name(cmd, p)?;
let d = s.doc()?;
let mut t = match str_param(p, "from") {
// A name both the drawing and the folder hold: `fromWhere` says which to copy.
Some(from) => table_at(cmd, d, from, place_param(cmd, p, "fromWhere")?)?,
Some(from) => find_table(cmd, d, from)?,
None => {
let named = match str_param(p, "kind").map(str::to_ascii_lowercase).as_deref() {
None if name.to_ascii_lowercase().ends_with(".stb") => true,
@@ -393,13 +226,15 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
if named { PlotStyleTable::named("", "", Vec::new()) } else { PlotStyleTable::color_dependent("", "", |_| None) }
}
};
name = with_ending(cmd, &t, &name)?;
let place = where_param(cmd, p)?.unwrap_or(Where::Drawing);
let taken = match place {
Where::Folder => in_folder(&name),
Where::Drawing => in_drawing(d, &name),
};
if taken {
let ext = if t.is_color_dependent() { ".ctb" } else { ".stb" };
let lower = name.to_ascii_lowercase();
if !lower.ends_with(ext) {
if lower.ends_with(".ctb") || lower.ends_with(".stb") {
return Err(bad(cmd, format!("a {} table's name ends in {ext}", if ext == ".ctb" { "colour-dependent" } else { "named" })));
}
name.push_str(ext);
}
if d.plot_style_tables.iter().any(|x| x.name.eq_ignore_ascii_case(&name)) {
return Err(bad(cmd, format!("plot style table `{name}` already exists")));
}
t.name = name;
@@ -407,19 +242,13 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
t.description = desc.chars().take(255).collect();
}
let t = t.sanitized();
match place {
Where::Folder => {
write_folder(cmd, &t)?;
s.touch();
}
Where::Drawing => store(s.doc_mut()?, t.clone()),
}
Ok(table_summary(s.doc()?, &t))
let out = table_summary(d, &t);
store(s.doc_mut()?, t);
Ok(out)
}
"set" => {
let name = table_name(cmd, p)?;
let place = place_of(cmd, s, p, &name)?;
let mut t = table_at(cmd, s.doc()?, &name, place)?;
let mut t = find_table(cmd, s.doc()?, &name)?;
if let Some(desc) = str_param(p, "description") {
t.description = desc.chars().take(255).collect();
}
@@ -477,18 +306,19 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
o.insert("removedStyle".into(), json!(r.trim()));
}
}
// The folder's file is written, and the drawings that keep a copy of it keep their copy;
// a built-in table edited keeps an edited copy in the drawing.
if place == Some(Where::Folder) {
write_folder(cmd, &t)?;
s.touch();
} else {
store(s.doc_mut()?, t);
}
store(s.doc_mut()?, t);
Ok(out)
}
"rename" => run_rename(s, p, cmd),
"delete" => run_delete(s, p, cmd),
"delete" => {
let name = table_name(cmd, p)?;
let d = s.doc_mut()?;
let before = d.plot_style_tables.len();
d.plot_style_tables.retain(|t| !t.name.eq_ignore_ascii_case(&name));
if d.plot_style_tables.len() == before {
return Err(bad(cmd, format!("the drawing keeps no plot style table `{name}` (built-in tables can't be deleted)")));
}
Ok(json!({ "deleted": name }))
}
"load" => {
let text = match (str_param(p, "text"), str_param(p, "path")) {
(Some(t), _) => t.to_string(),
@@ -512,15 +342,9 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
if t.name.is_empty() {
return Err(bad(cmd, "the table has no name: pass `name`"));
}
t.name = with_ending(cmd, &t, &t.name.clone())?;
match where_param(cmd, p)?.unwrap_or(Where::Drawing) {
Where::Folder => {
write_folder(cmd, &t)?;
s.touch();
}
Where::Drawing => store(s.doc_mut()?, t.clone()),
}
Ok(table_summary(s.doc()?, &t))
let out = table_summary(s.doc()?, &t);
store(s.doc_mut()?, t);
Ok(out)
}
"save" => {
let name = table_name(cmd, p)?;
@@ -540,86 +364,6 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
other => Err(bad(cmd, format!("unknown action `{other}` (list, get, new, set, rename, delete, load, save, reload)"))),
other => Err(bad(cmd, format!("unknown action `{other}` (list, get, new, set, delete, load, save)"))),
}
}
/// STYLESMANAGER rename: the folder's file, or the drawing's table and the layouts (and Model)
/// of this drawing that use it. Renaming the file leaves the drawings' copies as they are.
fn run_rename(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
let name = table_name(cmd, p)?;
let to = str_param(p, "to").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "`to` (the new name) is required"))?;
let Some(place) = place_of(cmd, s, p, &name)? else {
return Err(bad(
cmd,
format!("no plot style table `{name}` in the folder or the drawing (built-in tables can't be renamed: copy one with `new` and `from`)"),
));
};
let mut t = table_at(cmd, s.doc()?, &name, Some(place))?;
let old = t.name.clone();
let to = with_ending(cmd, &t, to)?;
let same = to.eq_ignore_ascii_case(&old);
let taken = match place {
Where::Folder => in_folder(&to),
Where::Drawing => in_drawing(s.doc()?, &to),
};
if !same && taken {
return Err(bad(cmd, format!("plot style table `{to}` already exists")));
}
t.name = to.clone();
let mut layouts = 0usize;
match place {
Where::Folder => {
write_folder(cmd, &t)?;
if !same && let Err(e) = super::super::plotstyle_folder::delete(&old) {
// Take the new file back, so the table isn't held twice and the rename can be tried again.
let undone = super::super::plotstyle_folder::delete(&to);
let left = if undone.is_ok() { "the table keeps its old name" } else { "both files now hold the table" };
return Err(bad(cmd, format!("can't remove `{old}` from the plot style folder ({e}); {left}")));
}
s.touch();
}
Where::Drawing => {
let d = s.doc_mut()?;
for x in d.plot_style_tables.iter_mut().filter(|x| x.name.eq_ignore_ascii_case(&old)) {
x.name = to.clone();
}
for l in d.layouts.iter_mut().filter(|l| l.page.plot_style_table.trim().eq_ignore_ascii_case(&old)) {
l.page.plot_style_table = to.clone();
layouts += 1;
}
if let Some(m) = d.model_page.as_mut().filter(|m| m.plot_style_table.trim().eq_ignore_ascii_case(&old)) {
m.plot_style_table = to.clone();
}
}
}
Ok(json!({ "name": to, "renamed": old, "layouts": layouts, "where": if place == Where::Folder { "folder" } else { "drawing" } }))
}
/// STYLESMANAGER delete: the drawing's table or the folder's file.
fn run_delete(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
let name = table_name(cmd, p)?;
let place = match where_param(cmd, p)? {
Some(w) => w,
None if in_drawing(s.doc()?, &name) => Where::Drawing,
None if in_folder(&name) => Where::Folder,
None => {
return Err(bad(cmd, format!("no plot style table `{name}` in the folder or the drawing (built-in tables can't be deleted)")));
}
};
match place {
Where::Folder => {
super::super::plotstyle_folder::delete(&name).map_err(|e| bad(cmd, e))?;
s.touch();
}
Where::Drawing => {
let d = s.doc_mut()?;
let before = d.plot_style_tables.len();
d.plot_style_tables.retain(|t| !t.name.eq_ignore_ascii_case(&name));
if d.plot_style_tables.len() == before {
return Err(bad(cmd, format!("the drawing keeps no plot style table `{name}` (built-in tables can't be deleted)")));
}
}
}
Ok(json!({ "deleted": name, "where": if place == Where::Folder { "folder" } else { "drawing" } }))
}
+4 -15
View File
@@ -116,10 +116,7 @@ impl SelectThen {
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 => match self.mirror_end(c) {
Some(end) => (Mat3::mirror(base, end), base),
None => return Vec::new(),
},
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
_ => return Vec::new(),
};
let Ok(d) = s.doc() else { return Vec::new() };
@@ -138,9 +135,7 @@ impl SelectThen {
k
})
.collect();
if !self.ask_erase {
out.push(line(rubber_from, c));
}
out.push(line(rubber_from, c));
out
}
/// The drag with the cursor at `c` and the base point at `base`.
@@ -153,10 +148,10 @@ impl SelectThen {
let (f, from) = self.scale_reference_factor(base, c)?;
(Mat3::scale_about(base, f), from)
}
Op::Mirror => (Mat3::mirror(base, self.mirror_end(c)?), base),
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
_ => return None,
};
let mut extra = if self.ask_erase { Vec::new() } else { vec![line(rubber_from, 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 });
}
@@ -494,12 +489,6 @@ impl SelectThen {
s.set_selection(Vec::new());
Ok(Step::Done)
}
/// The second point of MIRROR's line: the cursor while it is picked, then the picked point,
/// so the mirrored copy stays on screen at "Erase source objects?" (#2667).
fn mirror_end(&self, cursor: Vec2) -> Option<Vec2> {
if self.ask_erase { self.pts.get(1).copied() } else { Some(cursor) }
}
}
/// Objects MIRROR must preview individually: readable text and hatches retaining fill direction.
+11 -2
View File
@@ -56,8 +56,14 @@ impl Default for MTextOpts {
impl MTextOpts {
pub(super) fn new(s: &Session) -> Self {
let (height, style) =
s.doc().map(|d| (d.header.f64("TEXTSIZE", 0.2), d.header.str("TEXTSTYLE", "Standard"))).unwrap_or((0.2, "Standard".into()));
let (height, style) = s
.doc()
.map(|d| {
let style = d.header.str("TEXTSTYLE", "Standard");
// A fixed-height style sets the height new text starts with.
(super::draw::fixed_height(d, &style).unwrap_or_else(|| d.header.f64("TEXTSIZE", 0.2)), style)
})
.unwrap_or((0.2, "Standard".into()));
MTextOpts { height, style, ..MTextOpts::default() }
}
@@ -232,6 +238,9 @@ impl MTextAsk {
return Ok(Outcome::Ask(MTextAsk::Style));
}
o.style = d.text_style(&name).map(|t| t.name.clone()).ok_or_else(|| other(format!("Cannot find text style \"{name}\".")))?;
if let Some(h) = super::draw::fixed_height(d, &o.style) {
o.height = h;
}
Ok(Outcome::Back)
}
(MTextAsk::Width, Input::Point(p)) => {
-287
View File
@@ -1,287 +0,0 @@
//! The user's plot style folder: plot style tables kept as files on the computer, which every
//! drawing can use (STYLESMANAGER `where: "folder"`, `docs/plot-styles.md`).
//!
//! Each table is one file in our own format ([`cadcraft_doc::PlotStyleTable::to_file_text`]),
//! named after the table plus `.json`: `studio.ctb.json` holds `studio.ctb`. Native builds use
//! the `plotstyles` folder of the CADCraft settings directory ([`crate::settings_dir::current`]);
//! the web keeps the tables for the session. A host can install another store with
//! [`set_plot_style_store`] (first call wins).
//!
//! The tables read are handed to `cadcraft_doc` ([`cadcraft_doc::set_plot_style_folder`]), so
//! layouts, plots and the screen find them by name like the drawing's own tables.
use std::sync::{Mutex, OnceLock};
use cadcraft_doc::PlotStyleTable;
/// Ending of a table file.
pub const FILE_EXT: &str = ".json";
/// Most table files read from the folder.
pub const MAX_FILES: usize = 1000;
/// Where table files live. Names are file names ending in [`FILE_EXT`]; the engine never passes paths.
#[derive(Clone, Copy)]
pub struct PlotStyleStore {
/// The folder as the user would look for it, if it is a place on disk.
pub location: fn() -> Option<String>,
/// File names in the folder.
pub list: fn() -> std::result::Result<Vec<String>, String>,
pub read: fn(&str) -> std::result::Result<String, String>,
pub write: fn(&str, &str) -> std::result::Result<(), String>,
pub delete: fn(&str) -> std::result::Result<(), String>,
}
static STORE: OnceLock<PlotStyleStore> = OnceLock::new();
static MEMORY: Mutex<Vec<(String, String)>> = Mutex::new(Vec::new());
/// Files skipped by the last read, with the reason.
static WARNINGS: Mutex<Vec<String>> = Mutex::new(Vec::new());
/// Which file holds each table the last read found: (table name, file name). A file need not be
/// named after its table (`studio.json` holds `studio.ctb`), and edits go back to that file.
static SOURCES: Mutex<Vec<(String, String)>> = Mutex::new(Vec::new());
static READ_ONCE: OnceLock<()> = OnceLock::new();
/// Held through a whole read, so a read that started before a change can't hand `cadcraft_doc`
/// its older list after the read that follows the change.
static READING: Mutex<()> = Mutex::new(());
/// Install the host's plot style folder (first call wins).
pub fn set_plot_style_store(s: PlotStyleStore) {
let _ = STORE.set(s);
}
/// Whether `name` can be a table file's name: no path separators, no leading dot, no characters
/// a file system refuses, at most 200 characters (the file name adds its ending).
pub fn valid_table_name(name: &str) -> bool {
let n = name.trim();
!n.is_empty()
&& n == name
&& n.chars().count() <= 200
&& !n.starts_with('.')
&& !n.ends_with('.')
&& !n.chars().any(|c| c.is_control() || matches!(c, '/' | '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*'))
}
/// The file that holds table `name`.
pub fn file_name(name: &str) -> String {
format!("{name}{FILE_EXT}")
}
impl PlotStyleStore {
/// A folder kept in memory for the life of the process.
pub fn memory() -> PlotStyleStore {
fn lock() -> std::result::Result<std::sync::MutexGuard<'static, Vec<(String, String)>>, String> {
MEMORY.lock().map_err(|_| "the plot style folder is unavailable".to_string())
}
PlotStyleStore {
location: || None,
list: || Ok(lock()?.iter().map(|(n, _)| n.clone()).collect()),
read: |n| lock()?.iter().find(|(f, _)| f == n).map(|(_, t)| t.clone()).ok_or_else(|| format!("{n}: no such file")),
write: |n, t| {
let mut m = lock()?;
m.retain(|(f, _)| f != n);
m.push((n.to_string(), t.to_string()));
Ok(())
},
delete: |n| {
let mut m = lock()?;
let before = m.len();
m.retain(|(f, _)| f != n);
if m.len() == before { Err(format!("{n}: no such file")) } else { Ok(()) }
},
}
}
/// The `plotstyles` folder of the CADCraft settings directory.
#[cfg(not(target_arch = "wasm32"))]
pub fn settings_folder() -> PlotStyleStore {
fn dir() -> std::result::Result<std::path::PathBuf, String> {
crate::settings_dir::current()
.map(|r| r.join("plotstyles"))
.ok_or_else(|| "there is no settings folder for plot style tables".to_string())
}
fn file(n: &str) -> std::result::Result<std::path::PathBuf, String> {
let ok = n.strip_suffix(FILE_EXT).is_some_and(valid_table_name);
if !ok {
return Err(format!("`{n}` is not a plot style table file name"));
}
Ok(dir()?.join(n))
}
PlotStyleStore {
location: || dir().ok().map(|d| d.display().to_string()),
list: || {
let d = dir()?;
crate::file_access::check_read(&d)?;
let rd = match std::fs::read_dir(d) {
Ok(rd) => rd,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(e.to_string()),
};
// All of them: `reload` keeps the first [`MAX_FILES`] in name order and says so.
Ok(rd.filter_map(|e| e.ok()?.file_name().into_string().ok()).filter(|n| n.ends_with(FILE_EXT) && !n.starts_with('.')).collect())
},
read: |n| {
let p = file(n)?;
crate::file_access::check_read(&p)?;
let bytes = crate::capped_read::read_capped(&p, cadcraft_doc::MAX_TABLE_FILE).map_err(|e| format!("{n}: {e}"))?;
String::from_utf8(bytes).map_err(|e| format!("{n}: {e}"))
},
write: |n, t| {
let p = file(n)?;
crate::file_access::check_write(&p)?;
std::fs::create_dir_all(dir()?).map_err(|e| e.to_string())?;
crate::atomic_write::write_atomic(&p, t.as_bytes()).map_err(|e| format!("{n}: {e}"))
},
delete: |n| {
let p = file(n)?;
crate::file_access::check_write(&p)?;
std::fs::remove_file(p).map_err(|e| format!("{n}: {e}"))
},
}
}
}
fn store() -> PlotStyleStore {
*STORE.get_or_init(|| {
#[cfg(not(target_arch = "wasm32"))]
{
PlotStyleStore::settings_folder()
}
#[cfg(target_arch = "wasm32")]
{
PlotStyleStore::memory()
}
})
}
/// The folder as the user would look for it (`None` on the web or without a settings folder).
pub fn location() -> Option<String> {
(store().location)()
}
/// Files the last read skipped, and why.
pub fn warnings() -> Vec<String> {
WARNINGS.lock().map(|w| w.clone()).unwrap_or_default()
}
/// The table a file holds: named after the file (so renaming the file renames the table), with
/// the `.ctb`/`.stb` ending its kind asks for.
fn table_from_file(file: &str, text: &str) -> std::result::Result<PlotStyleTable, String> {
let mut t = PlotStyleTable::from_file_text(text)?;
let stem = file.strip_suffix(FILE_EXT).unwrap_or(file);
let ext = if t.is_color_dependent() { ".ctb" } else { ".stb" };
let lower = stem.to_ascii_lowercase();
t.name = if lower.ends_with(ext) {
stem.to_string()
} else if lower.ends_with(".ctb") || lower.ends_with(".stb") {
return Err(format!("the file name ends in {} but the table is {}", &stem[stem.len() - 4..], kind_words(&t)));
} else {
format!("{stem}{ext}")
};
Ok(t)
}
fn kind_words(t: &PlotStyleTable) -> &'static str {
if t.is_color_dependent() { "colour-dependent (.ctb)" } else { "named (.stb)" }
}
/// Read the folder again and hand its tables to `cadcraft_doc`. Unreadable files are skipped and
/// listed in [`warnings`]; a folder that can't be listed counts as empty.
pub fn reload() -> Vec<PlotStyleTable> {
let _reading = READING.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let st = store();
let mut warn = Vec::new();
let mut tables: Vec<PlotStyleTable> = Vec::new();
let mut sources = Vec::new();
match (st.list)() {
Ok(mut files) => {
files.sort();
if files.len() > MAX_FILES {
warn.push(format!("only the first {MAX_FILES} files by name are read; {} more were left out", files.len() - MAX_FILES));
}
for f in files.iter().take(MAX_FILES) {
match (st.read)(f).and_then(|text| table_from_file(f, &text)) {
Ok(t) if tables.iter().any(|x| x.name.eq_ignore_ascii_case(&t.name)) => {
warn.push(format!("{f}: another file already holds `{}`", t.name));
}
Ok(t) => {
sources.push((t.name.clone(), f.clone()));
tables.push(t);
}
Err(e) => warn.push(format!("{f}: {e}")),
}
}
}
Err(e) => warn.push(e),
}
tables.sort_by_key(|t| t.name.to_lowercase());
if let Ok(mut w) = WARNINGS.lock() {
*w = warn;
}
if let Ok(mut x) = SOURCES.lock() {
*x = sources;
}
cadcraft_doc::set_plot_style_folder(tables.clone());
let _ = READ_ONCE.set(());
tables
}
/// Read the folder the first time a session starts; later calls do nothing.
pub fn read_once() {
if READ_ONCE.get().is_none() {
reload();
}
}
/// The file that holds table `name`: the one the last read found it in, else one named after it
/// in any case.
fn held_by(st: &PlotStyleStore, name: &str) -> Option<String> {
let known = SOURCES.lock().ok().and_then(|x| x.iter().find(|(t, _)| t.eq_ignore_ascii_case(name)).map(|(_, f)| f.clone()));
known.or_else(|| {
let file = file_name(name);
(st.list)().unwrap_or_default().into_iter().find(|f| f.eq_ignore_ascii_case(&file))
})
}
/// Write `t` to the folder and read it again. The file that held a table of the same name (under
/// another file name, or another case of it) is replaced, not doubled.
pub fn write(t: &PlotStyleTable) -> std::result::Result<(), String> {
if !valid_table_name(&t.name) {
return Err(format!("`{}` can't be a file name in the plot style folder (no / \\ : < > \" | ? * or leading dot)", t.name));
}
let st = store();
let file = file_name(&t.name);
let text = t.to_file_text();
let old = held_by(&st, &t.name).filter(|f| *f != file);
(st.write)(&file, &text)?;
let result = match old {
None => Ok(()),
Some(old) => {
let files = (st.list)().unwrap_or_default();
if files.contains(&old) && files.contains(&file) {
// Two files: the old one would still win the next read.
(st.delete)(&old).map_err(|e| format!("{file} was written, but {old} still holds the old `{}`: {e}", t.name))
} else {
// One file under two spellings (a disk that ignores case): the write went to the
// old file. Remove it and write again, so the file takes the new spelling; if
// that fails, put the table back under the old one.
(st.delete)(&old).and_then(|()| match (st.write)(&file, &text) {
Ok(()) => Ok(()),
Err(e) => {
let _ = (st.write)(&old, &text);
Err(e)
}
})
}
}
};
reload();
result
}
/// Remove table `name` from the folder and read it again.
pub fn delete(name: &str) -> std::result::Result<(), String> {
let st = store();
let found = held_by(&st, name.trim()).ok_or_else(|| format!("the plot style folder has no table `{name}`"))?;
let result = (st.delete)(&found);
reload();
result
}
+2 -2
View File
@@ -446,7 +446,7 @@ fn styles_json(d: &cadcraft_doc::Drawing) -> Value {
json!({ "current": cur, "styles": d.text_styles.iter().map(|t| style_json(t, &cur)).collect::<Vec<_>>() })
}
fn run_style(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) fn run_style(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("style", "`name` is required"))?.trim().to_string();
if name.is_empty() || name.len() > 255 {
return Err(bad("style", "bad style name"));
@@ -516,7 +516,7 @@ fn run_style_current(s: &mut Session, p: &Value) -> Result<Value> {
/// Text style names used by entities (in model, paper spaces and blocks), dimension,
/// multileader and table styles (their cell styles), and the text of complex linetypes.
pub(super) fn text_styles_in_use(d: &cadcraft_doc::Drawing) -> Vec<String> {
pub fn text_styles_in_use(d: &cadcraft_doc::Drawing) -> Vec<String> {
let mut out: Vec<String> = d.dim_styles.iter().map(|s| s.text_style.clone()).collect();
out.extend(d.mleader_styles.iter().map(|s| s.text_style.clone()));
out.extend(d.table_styles.iter().flat_map(|s| s.cell_styles.iter().map(|c| c.text_style.clone())));
+1 -4
View File
@@ -170,10 +170,7 @@ fn copy_props(src: &Entity, dst: &mut Entity, m: &MatchProps) {
b.overrides.clone_from(&a.overrides);
b.block = None;
}
(EntityKind::Leader(a), EntityKind::Leader(b)) if m.dimension => {
b.style.clone_from(&a.style);
b.overrides.clone_from(&a.overrides);
}
(EntityKind::Leader(a), EntityKind::Leader(b)) if m.dimension => b.style.clone_from(&a.style),
(EntityKind::Text(a), EntityKind::Text(b)) if m.text => {
b.style.clone_from(&a.style);
b.height = a.height;
-14
View File
@@ -345,20 +345,6 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
),
));
}
// On a leader that holds for the DSTYLE list of its `ACAD` run (its overrides); the
// rest of the run is kept raw and may be set.
if let Some((app, _)) =
changes.iter().find(|(app, groups)| cadcraft_doc::is_model_xdata(app, groups.as_deref().unwrap_or_default(), &e.kind))
{
return Err(bad(
"properties.set",
format!(
"{}: the DSTYLE list in xdata application {app} of a {} holds its dimension-style overrides, written from its own properties, and can't be set as raw data",
h.hex(),
e.kind.dxf_name()
),
));
}
let mut after = e.common.xdata.clone();
super::xdata::apply(&mut after, changes);
if after.len() > cadcraft_doc::MAX_XDATA_GROUPS {
+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)
+352
View File
@@ -0,0 +1,352 @@
//! -STYLE, text styles at the command line (scripts, the keyboard): AutoCAD's prompts for a
//! style's name, font, height (or annotative paper height), width factor, obliquing angle,
//! backwards and upside-down text (and vertical text for SHX fonts), which then becomes the
//! current style. Also `style.fonts`, the installed fonts a style can name, by family and style
//! (the Text Style dialog's font lists).
//! Behavior reference: <https://help.autodesk.com/cloudhelp/2023/ENU/AutoCAD-Core/files/GUID-0496BC60-0D07-4982-A395-B83E39EA5CF4.htm>
//! and <https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-Customization/files/GUID-FF206F73-AC7E-4DB0-B9C7-E182DE613A23.htm>.
use cadcraft_doc::{Drawing, TextStyle};
use serde_json::{Value, json};
use super::CommandSpec;
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("-style", "Text Style", super::props::run_style)
.params("same as `style`: {name, font?, bigFont?, height?, widthFactor?, oblique? (degrees), backwards?, upsideDown?, vertical?, annotative?, current?} → styles")
.interactive(|_| Ok(Box::new(DashStyle::default()))),
CommandSpec::new("style.fonts", "List Fonts", run_fonts)
.params("{} → {fonts: [{family, style, file}]} (the built-in stroke font first, then the installed fonts; a text style's `font` takes `file`)")
.noundo(),
]
}
fn run_fonts(_s: &mut Session, _p: &Value) -> Result<Value> {
let builtin = cadcraft_fonts::BUILTIN_FONT;
let mut fonts = vec![json!({ "family": builtin, "style": "Regular", "file": builtin })];
fonts.extend(cadcraft_fonts::ttf::installed_fonts().into_iter().map(|f| json!({ "family": f.family, "style": f.style, "file": f.file })));
Ok(json!({ "fonts": fonts }))
}
fn other(m: impl Into<String>) -> EngineError {
EngineError::Other(m.into())
}
/// Whether `font` names an SHX font (the only kind with a vertical form).
fn is_shx(font: &str) -> bool {
cadcraft_fonts::is_shx_name(font)
}
fn yes(text: Option<&str>, default: bool) -> bool {
match text.map(str::to_ascii_lowercase).as_deref() {
Some("yes" | "y") => true,
Some("no" | "n") => false,
_ => default,
}
}
/// A style's settings in one line, as `?` lists them.
pub(super) fn listing(st: &TextStyle) -> String {
let mut generation: Vec<&str> = Vec::new();
if st.backwards {
generation.push("Backwards");
}
if st.upside_down {
generation.push("Upside-down");
}
if st.vertical {
generation.push("Vertical");
}
let generation = if generation.is_empty() { "Normal".to_string() } else { generation.join(", ") };
let annotative = if st.annotative { " Annotative" } else { "" };
format!(
"Style name: \"{}\" Font files: {} Height: {:.4} Width factor: {:.4} Obliquing angle: {:.0} Generation: {generation}{annotative}",
st.name,
st.font,
st.height,
st.width_factor,
st.oblique.to_degrees()
)
}
/// Text style names matching `pattern` (`*` and `?` wildcards, any case).
pub(super) fn styles_matching<'a>(d: &'a Drawing, pattern: &str) -> Vec<&'a TextStyle> {
let p: Vec<char> = pattern.trim().to_lowercase().chars().take(255).collect();
let p = if p.is_empty() { vec!['*'] } else { p };
d.text_styles.iter().filter(|st| wildcard(&p, &st.name.to_lowercase().chars().collect::<Vec<_>>())).collect()
}
/// `*` and `?` matching without recursion (bounded by the two lengths).
fn wildcard(p: &[char], s: &[char]) -> bool {
let (mut pi, mut si) = (0, 0);
let mut star: Option<(usize, usize)> = None;
while si < s.len() {
match p.get(pi) {
Some('*') => {
star = Some((pi, si));
pi += 1;
}
Some(c) if *c == '?' || Some(c) == s.get(si) => {
pi += 1;
si += 1;
}
_ => match star {
Some((sp, ss)) => {
pi = sp + 1;
si = ss + 1;
star = Some((sp, ss + 1));
}
None => return false,
},
}
}
p.get(pi..).is_some_and(|rest| rest.iter().all(|c| *c == '*'))
}
#[derive(Default)]
enum Ask {
#[default]
Name,
ListPattern,
Font,
Height,
Annotative,
Orientation,
PaperHeight,
Width,
Oblique,
Backwards,
UpsideDown,
Vertical,
}
/// The style being defined: its settings so far, starting from the existing style (or, for a
/// new one, the current style).
#[derive(Default)]
struct DashStyle {
ask: Ask,
style: TextStyle,
}
impl DashStyle {
fn finish(&self, s: &mut Session) -> Result<Step> {
let st = &self.style;
super::props::run_style(
s,
&json!({
"name": st.name,
"font": st.font,
// A new style keeps the big font of the style it starts from.
"bigFont": st.big_font,
"height": st.height,
"widthFactor": st.width_factor,
"oblique": st.oblique.to_degrees(),
"backwards": st.backwards,
"upsideDown": st.upside_down,
"vertical": st.vertical,
"annotative": st.annotative,
"current": true,
}),
)?;
s.echo(format!("\"{}\" is now the current text style.", st.name));
Ok(Step::Done)
}
}
fn number(t: &str) -> Option<f64> {
t.trim().parse::<f64>().ok().or_else(|| crate::units::parse_distance(t)).filter(|v| v.is_finite())
}
impl Interactive for DashStyle {
fn name(&self) -> &'static str {
"-STYLE"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
let d = s.doc()?;
let current = d.header.str("TEXTSTYLE", "Standard");
self.style = d.text_style(&current).cloned().unwrap_or_default();
Ok(Step::Continue)
}
fn prompt(&self, s: &Session) -> Prompt {
let st = &self.style;
let (lu, lp) = s.doc().map(|d| (d.header.i64("LUNITS", 2), d.header.i64("LUPREC", 4))).unwrap_or((2, 4));
let dist = |v: f64| crate::units::format_distance(v, lu, lp);
let yes_no = |b: bool| if b { "Yes" } else { "No" };
match self.ask {
Ask::Name => Prompt::new("Enter name of text style", Accept::TEXT).kw(&["?"]).default(st.name.clone()),
Ask::ListPattern => Prompt::new("Enter text style(s) to list", Accept::TEXT).default("*"),
Ask::Font => Prompt::new("Specify full font name or font filename (TTF or SHX)", Accept::TEXT).default(st.font.clone()),
Ask::Height => Prompt::new("Specify height of text", Accept::TEXT).kw(&["Annotative"]).default(dist(st.height)),
// Asked after Annotative was picked: Enter says yes.
Ask::Annotative => Prompt::new("Create annotative text style?", Accept::TEXT).kw(&["Yes", "No"]).default("Yes"),
Ask::Orientation => Prompt::new("Match text orientation to layout?", Accept::TEXT).kw(&["Yes", "No"]).default("No"),
Ask::PaperHeight => Prompt::new("Specify paper text height", Accept::TEXT).default(dist(st.height)),
Ask::Width => Prompt::new("Specify width factor", Accept::TEXT).default(format!("{:.4}", st.width_factor)),
Ask::Oblique => Prompt::new("Specify obliquing angle", Accept::TEXT).default(format!("{:.0}", st.oblique.to_degrees())),
Ask::Backwards => Prompt::new("Display text backwards?", Accept::TEXT).kw(&["Yes", "No"]).default(yes_no(st.backwards)),
Ask::UpsideDown => Prompt::new("Display text upside-down?", Accept::TEXT).kw(&["Yes", "No"]).default(yes_no(st.upside_down)),
Ask::Vertical => Prompt::new("Vertical?", Accept::TEXT).kw(&["Yes", "No"]).default(yes_no(st.vertical)),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let ask = std::mem::take(&mut self.ask);
let text = match &i {
Input::Text(t) | Input::Keyword(t) => Some(t.trim().to_string()).filter(|t| !t.is_empty()),
_ => None,
};
let t = text.as_deref();
match ask {
Ask::Name => match t {
Some("?") => self.ask = Ask::ListPattern,
_ => {
let name = t.map_or_else(|| self.style.name.clone(), str::to_string);
if name.len() > 255 || name.contains(['<', '>', '/', '\\', '"', ':', ';', '?', '*', '|', ',', '=', '`']) {
self.ask = Ask::Name;
return Err(other("Invalid text style name."));
}
let d = s.doc()?;
match d.text_style(&name) {
Some(existing) => {
self.style = existing.clone();
s.echo("Existing style.".to_string());
}
None => {
// A new style starts with the current style's settings.
self.style.name = name;
s.echo("New style.".to_string());
}
}
self.ask = Ask::Font;
}
},
Ask::ListPattern => {
let d = s.doc()?;
let lines: Vec<String> = styles_matching(d, t.unwrap_or("*")).into_iter().map(listing).collect();
let current = d.header.str("TEXTSTYLE", "Standard");
for l in lines {
s.echo(l);
}
s.echo(format!("Current text style: {current}"));
return Ok(Step::Done);
}
Ask::Font => {
if let Some(f) = t {
let (normal, big) = f.split_once(',').map_or((f, None), |(normal, big)| (normal, Some(big)));
let clean = |name: &str| name.trim().trim_matches('"').trim().chars().take(255).collect::<String>();
let normal = clean(normal);
if !normal.is_empty() {
if cadcraft_fonts::ttf::find(&normal).is_none()
&& !is_shx(&normal)
&& !normal.eq_ignore_ascii_case(cadcraft_fonts::BUILTIN_FONT)
{
s.echo(format!("Font {normal} is not installed; text is drawn with a substitute."));
}
self.style.font = normal;
}
match big {
Some(big) if !big.trim().is_empty() => self.style.big_font = clean(big),
None => self.style.big_font.clear(),
_ => {}
}
}
self.ask = Ask::Height;
}
Ask::Height => match t {
Some(k) if k.eq_ignore_ascii_case("annotative") || k.eq_ignore_ascii_case("a") => self.ask = Ask::Annotative,
Some(v) => match number(v).filter(|h| *h >= 0.0) {
Some(h) => {
self.style.height = h;
self.ask = Ask::Width;
}
None => {
self.ask = Ask::Height;
return Err(other("Requires a distance, or Annotative."));
}
},
None => self.ask = Ask::Width,
},
Ask::Annotative => {
self.style.annotative = yes(t, true);
// No asks for the height again, as it measures in the drawing.
self.ask = if self.style.annotative { Ask::Orientation } else { Ask::Height };
}
// CADCraft doesn't model the layout orientation; the answer is taken and not kept.
Ask::Orientation => self.ask = Ask::PaperHeight,
Ask::PaperHeight => match t.map(number) {
Some(Some(h)) if h >= 0.0 => {
self.style.height = h;
self.ask = Ask::Width;
}
Some(_) => {
self.ask = Ask::PaperHeight;
return Err(other("Requires a positive distance or 0."));
}
None => self.ask = Ask::Width,
},
Ask::Width => match t.map(number) {
Some(Some(w)) if w > 0.0 && w <= 100.0 => {
self.style.width_factor = w;
self.ask = Ask::Oblique;
}
Some(_) => {
self.ask = Ask::Width;
return Err(other("Requires a width factor greater than 0 and at most 100."));
}
None => self.ask = Ask::Oblique,
},
Ask::Oblique => {
let angle = t.map(|v| {
v.trim().parse::<f64>().ok().or_else(|| {
crate::units::parse_angle(v).map(|a| {
let d = a.to_degrees().rem_euclid(360.0);
if d > 180.0 { d - 360.0 } else { d }
})
})
});
match angle {
Some(Some(a)) if a.abs() <= 85.0 => {
self.style.oblique = a.to_radians();
self.ask = Ask::Backwards;
}
Some(_) => {
self.ask = Ask::Oblique;
return Err(other("Requires an angle between -85 and 85."));
}
None => self.ask = Ask::Backwards,
}
}
Ask::Backwards => {
self.style.backwards = yes(t, self.style.backwards);
self.ask = Ask::UpsideDown;
}
Ask::UpsideDown => {
self.style.upside_down = yes(t, self.style.upside_down);
if !is_shx(&self.style.font) {
self.style.vertical = false;
return self.finish(s);
}
self.ask = Ask::Vertical;
}
Ask::Vertical => {
self.style.vertical = yes(t, self.style.vertical);
return self.finish(s);
}
}
Ok(Step::Continue)
}
}
#[cfg(test)]
mod tests {
use super::wildcard;
#[test]
fn wildcards() {
let m = |p: &str, s: &str| wildcard(&p.chars().collect::<Vec<_>>(), &s.chars().collect::<Vec<_>>());
assert!(m("*", "anything") && m("st*", "standard") && m("s?andard", "standard") && m("*d", "standard"));
assert!(!m("st", "standard") && !m("x*", "standard"));
assert!(m(&"*".repeat(10_000), "abc"));
}
}
+16 -11
View File
@@ -397,7 +397,7 @@ impl TrimM {
let e = d.entity(h)?;
// Half a pixel: finer than the eye can tell apart, coarse enough to stay quick.
let tol = (s.pixel_size() / 2.0).max(1e-9);
let extending = self.extend ^ (s.shift_down && s.person_input());
let extending = self.extend ^ s.shift_down;
let part = if extending {
let grown = Entity { kind: extended(s, h, cursor, cut).ok()?, ..(**e).clone() };
uncovered(d, &grown, std::slice::from_ref(&e.kind), tol)
@@ -415,7 +415,7 @@ impl TrimM {
Edges { only: self.edges.as_deref(), implied: !quick && implied }
}
fn select_edges(&mut self, s: &mut Session) {
let extending = self.extend ^ (s.shift_down && s.person_input());
let extending = self.extend ^ s.shift_down;
s.echo(if extending { "Select boundary edges ..." } else { "Select cutting edges ..." });
s.set_selection(Vec::new());
self.stage = Stage::Edges(Vec::new());
@@ -505,15 +505,20 @@ impl Interactive for TrimM {
fn prompt(&self, s: &Session) -> Prompt {
match &self.stage {
Stage::Pick => {
let shift = s.shift_down && s.person_input();
let extending = self.extend ^ shift;
let extending = self.extend ^ s.shift_down;
let (msg, first) = if extending {
let msg =
if shift { "Select object to extend or release Shift to trim" } else { "Select object to extend or shift-select to trim" };
let msg = if s.shift_down {
"Select object to extend or release Shift to trim"
} else {
"Select object to extend or shift-select to trim"
};
(msg, "Boundary edges")
} else {
let msg =
if shift { "Select object to trim or release Shift to extend" } else { "Select object to trim or shift-select to extend" };
let msg = if s.shift_down {
"Select object to trim or release Shift to extend"
} else {
"Select object to trim or shift-select to extend"
};
(msg, "cuTting edges")
};
let mut kw = vec![first, "Fence", "Crossing", "mOde", "Project"];
@@ -536,7 +541,7 @@ impl Interactive for TrimM {
Stage::Crossing(None) => Prompt::new("Specify first corner", Accept::POINT),
Stage::Crossing(Some(_)) => Prompt::new("Specify opposite corner", Accept::POINT),
Stage::Mode => {
let extending = self.extend ^ (s.shift_down && s.person_input());
let extending = self.extend ^ s.shift_down;
let msg = if extending { "Enter an extend mode option" } else { "Enter a trim mode option" };
Prompt::new(msg, KW).kw(&["Quick", "Standard"]).default(if quick_mode(s) { "Quick" } else { "Standard" })
}
@@ -560,7 +565,7 @@ impl Interactive for TrimM {
self.cut.take();
let quick = quick_mode(s);
let implied = edge_mode(s);
let extending = self.extend ^ (s.shift_down && s.person_input());
let extending = self.extend ^ s.shift_down;
match self.stage.clone() {
Stage::Mode | Stage::Project | Stage::Edge => self.option(s, i),
Stage::Edges(mut picked) => {
@@ -729,7 +734,7 @@ impl Interactive for TrimM {
return None;
}
let px = (s.pixel_size() / 2.0).max(1e-9);
let extending = self.extend ^ (s.shift_down && s.person_input());
let extending = self.extend ^ s.shift_down;
Some(picks_preview(s, &work, extending, self.edges(quick, implied), quick, tol, px))
}
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
+2 -2
View File
@@ -69,6 +69,7 @@ pub const FILES: &[&str] = &[
/// Commands that can't be held to the roots, and why.
pub const REFUSED: &[(&str, &str)] = &[
("style.fonts", "it reads installed fonts outside the automation roots"),
("drawingrecovery", "it works on the autosave folder (SAVEFILEPATH), which is the server's own"),
("blocklibraries", "it keeps its list of libraries in the settings folder, which is the server's own"),
];
@@ -87,14 +88,13 @@ pub const NO_FILES: &[&str] = &[
"blockspalette",
"dimoverride.clear",
"-dimstyle",
"-style",
"dimstyle.overrides",
"dimstyle.saveas",
"properties.describe",
"close",
"closeall",
"document.switch",
"document.next",
"document.prev",
"document.bytes",
"u",
"undo",
+1 -4
View File
@@ -164,8 +164,7 @@ pub struct Session {
/// this instead of receiving modifiers through `Input`, which stays free of UI state.
pub ctrl_down: bool,
/// Whether Shift is held right now (from the UI, overwritten every frame). TRIM/EXTEND read
/// this to temporarily toggle the active mode, as in AutoCAD; commands should gate it through
/// [`Session::person_input`], which is false for program-fed input.
/// this to temporarily toggle the active mode, as in AutoCAD.
pub shift_down: bool,
/// Origin of the point currently being fed by `input_snapped`; never reused by typed points.
picked_viewport: Option<snap::ViewportPoint>,
@@ -224,8 +223,6 @@ impl Session {
}
/// A session with no open drawing (the Start tab).
pub fn empty() -> Self {
// The user's plot style folder, read once per process (STYLESMANAGER reads it again).
cmd::plotstyle_folder::read_once();
Session {
docs: Vec::new(),
active: 0,
+8 -93
View File
@@ -156,8 +156,6 @@ pub struct LispState {
/// pass: the lowest of its own and its callers' allowances, and of what is left to an
/// expression typed at a prompt.
pub(crate) callback_ceiling: Option<u64>,
/// The host draws frames and calls [`Session::lisp_tick`] in each ([`Session::lisp_by_frames`]).
frames: bool,
}
/// What U and REDO inside the running routine take back: the commands it ran, each as the drawing
@@ -171,10 +169,6 @@ struct RoutineSteps {
/// Where the routine's undo step starts, when U or REDO inside it went on to the drawing's
/// own steps; else where the routine started.
base: Option<(Arc<Drawing>, Vec<Handle>)>,
/// The commands the routine was started in that still run: the one an expression was typed
/// at the prompt of, and the one that command interrupted when it is transparent. What they
/// did is their own undo step, not the routine's ([`Session::lisp_host_ends`]).
hosts: u8,
}
/// What a run may use (see [`value`]'s memory notes).
@@ -222,9 +216,6 @@ struct Run {
/// An expression typed at a command's prompt ([`Session::lisp_eval_answer`]): blocking, with
/// [`ANSWER_CAP`] steps instead of [`BLOCKING_CAP`].
answer: bool,
/// An answer the frames carry on ([`Session::lisp_by_frames`]): its value goes to the prompt
/// when it ends, since the call that started it has returned.
deferred: bool,
/// Steps taken, for the caps on blocking runs and on routines run on without frames.
steps: u64,
/// The `*error*` handler is the one running.
@@ -240,11 +231,9 @@ struct Run {
const SLICE: u64 = 400_000;
/// Steps a blocking run (a programmatic call) may take before it is stopped.
const BLOCKING_CAP: u64 = 500_000_000;
/// Steps an expression typed at a command's prompt may take, the callbacks it runs included. Its
/// value is the prompt's answer, so every input but Esc waits for it. Without frames it runs
/// blocking; with them ([`Session::lisp_by_frames`]) it runs a slice per frame, as a routine at
/// `Command:` does, so Esc stops it. A callback runs inside one step either way, so Esc doesn't
/// reach it before it ends.
/// Steps an expression typed at a command's prompt may take, the callbacks it runs included. It
/// runs blocking, since its value is the prompt's answer, so the interface draws no frame and
/// Esc doesn't reach it until it ends; a routine at `Command:` runs a slice per frame instead.
const ANSWER_CAP: u64 = 20_000_000;
impl Session {
@@ -314,9 +303,7 @@ impl Session {
}
/// Evaluate an expression typed at a command's prompt, whose value is the answer: it runs to
/// the end as a programmatic call does, within [`ANSWER_CAP`] steps. Where the host draws
/// frames ([`Session::lisp_by_frames`]) and the first slice doesn't end it, this returns
/// `None` and the frames carry it on; its value then answers the prompt by itself.
/// the end as a programmatic call does, within [`ANSWER_CAP`] steps.
pub(crate) fn lisp_eval_answer(&mut self, src: &str) -> crate::Result<Option<std::result::Result<Value, String>>> {
let forms = read::read_all(src).map_err(|e| crate::EngineError::Other(format!("; error: {}", e.msg)))?;
self.lisp_start(Machine::forms(forms), false, true, Vec::new(), "LISP".into(), true)
@@ -343,11 +330,7 @@ impl Session {
let st = self.state()?;
let before = Some((st.doc.clone(), st.selection.clone()));
let uid = st.uid;
let hosts = u8::from(self.running.is_some()) + u8::from(self.suspended.is_some());
self.lisp.steps = RoutineSteps { uid, hosts, ..RoutineSteps::default() };
// What an earlier routine left when it ended in a later frame or at a later input, where
// no call was waiting for it, is not this one's.
self.lisp_last = None;
self.lisp.steps = RoutineSteps { uid, ..RoutineSteps::default() };
self.lisp.run = Some(Box::new(Run {
machine,
uid,
@@ -358,7 +341,6 @@ impl Session {
inputs: inputs.into(),
blocking,
answer,
deferred: false,
steps: 0,
handler: false,
string_bytes: 0,
@@ -367,8 +349,7 @@ impl Session {
self.lisp_drive();
if blocking {
// A blocking run that waits for a command's input (`pause`) can't get it: cancel.
// An answer the frames carry on is not waiting for input.
if self.lisp.run.as_ref().is_some_and(|r| !r.deferred) {
if self.lisp.run.is_some() {
self.lisp_abort("Function cancelled");
}
}
@@ -396,24 +377,6 @@ impl Session {
}
}
/// Say whether the host draws frames and calls [`Session::lisp_tick`] in each. Where it does,
/// an expression typed at a command's prompt runs a slice per frame, so Esc
/// ([`Session::cancel`]) stops it; elsewhere it runs to its end before the call returns.
pub fn lisp_by_frames(&mut self, on: bool) {
self.lisp.frames = on;
}
/// An input other than Esc comes after the answer the frames are working out, as it did when
/// the answer ran blocking: run the expression to its end first, within its allowance. The
/// input entry points call this themselves; a host calls it before it reads the command's
/// state ([`Session::prompting`]) to choose where an input goes, so the choice is the one it
/// would make with the answer in.
pub fn lisp_settle_answer(&mut self) {
if self.lisp.run.as_ref().is_some_and(|r| r.deferred && matches!(r.waiting, Some(Need::Yield))) {
self.lisp_run_until_input();
}
}
/// Whether the routine needs ticks ([`Session::lisp_tick`]) to go on.
pub fn lisp_busy(&self) -> bool {
self.lisp.run.as_ref().is_some_and(|r| matches!(r.waiting, Some(Need::Yield)))
@@ -523,14 +486,10 @@ impl Session {
return;
}
Outcome::Wait(Need::Yield) => {
// An answer gives the interface a frame where there is one, so Esc reaches
// it. A script's line is answered before its next one, so it runs on.
let by_frames = run.answer && self.lisp.frames && !self.in_script;
if run.blocking && !by_frames {
if run.blocking {
self.lisp.run = Some(run);
continue;
}
run.deferred |= by_frames;
run.waiting = Some(Need::Yield);
self.lisp.run = Some(run);
return;
@@ -551,8 +510,7 @@ impl Session {
return;
}
Outcome::Wait(Need::Get(req)) => {
let (req, given) = self.lisp_supplied(&mut run.inputs, req);
if let Some(v) = given {
if let Some(v) = run.inputs.pop_front() {
run.machine.resume(v);
self.lisp.run = Some(run);
continue;
@@ -570,25 +528,6 @@ impl Session {
}
}
/// The value a `get…` call takes from the inputs given up front, `None` when they ran out, and
/// the request as it then stands. `getangle` and `getorient` read each input as the prompt
/// would ([`input::GetRequest::supplied`]): one the prompt refuses is echoed with the reason
/// and the next one is taken, and the first of two points makes the request ask for the
/// second. The other calls take the input as their value.
fn lisp_supplied(&mut self, inputs: &mut std::collections::VecDeque<Value>, mut req: input::GetRequest) -> (input::GetRequest, Option<Value>) {
if !req.reads_supplied() {
return (req, inputs.pop_front());
}
while let Some(v) = inputs.pop_front() {
match req.supplied(self, &v) {
input::Answer::Value(v) => return (req, Some(v)),
input::Answer::Again(msg) => self.echo(msg),
input::Answer::Second(p) => req = input::with_first(&req, p),
}
}
(req, None)
}
/// Move printed text to the command history: complete lines, and with `all` the rest too.
fn lisp_flush(&mut self, env: &mut Env, all: bool) {
// One pass over the buffer, dropping the printed lines once at the end: draining each line
@@ -617,7 +556,6 @@ impl Session {
/// The routine finished: print its value (command-line expressions), record its undo step.
fn lisp_end(&mut self, result: std::result::Result<Value, String>) {
let Some(run) = self.lisp.run.take() else { return };
let (deferred, handler) = (run.deferred, run.handler);
self.lisp.active = false;
let steps = std::mem::take(&mut self.lisp.steps);
let mut env = self.lisp.envs.remove(&run.uid).unwrap_or_default();
@@ -637,16 +575,6 @@ impl Session {
st.revision += 1;
}
self.lisp_last = Some(result);
// The call that started an answer the frames carried on has returned: nothing reads how
// it ended, and its value answers the prompt here. A failed answer's `*error*` handler
// returns no answer.
if deferred
&& let Some(Ok(v)) = self.lisp_last.take()
&& !handler
&& let Err(e) = self.lisp_answer(v)
{
self.echo(e.to_string());
}
}
/// A LISP error: run `*error*` when the routine defined one, else print it.
@@ -791,19 +719,6 @@ impl Session {
self.lisp.active
}
/// A command ends, `nested` when it ran inside another. Whether the running routine was
/// started in it (an expression typed at its prompt, or at the prompt of a transparent command
/// inside it) rather than having started it: such a command began before the routine, so its
/// undo step is its own.
pub(crate) fn lisp_host_ends(&mut self, nested: bool) -> bool {
let depth = 1 + u8::from(nested);
if !self.lisp.active || depth > self.lisp.steps.hosts {
return false;
}
self.lisp.steps.hosts = depth - 1;
true
}
/// A command the running routine ran changed the drawing (`snap` holds it as it was): U inside
/// the routine takes it back, as AutoCAD's does, while the routine stays one undo step. UNDO
/// Control One keeps only the last, None none.
-1
View File
@@ -253,7 +253,6 @@ static BUILTINS: &[Builtin] = &[
ctx!("ENTUPD", drawing::entupd),
ctx!("HANDENT", drawing::handent),
ctx!("REGAPP", drawing::regapp),
ctx!("TEXTBOX", drawing::textbox),
ctx!("SSGET", drawing::ssget),
ctx!("SSADD", drawing::ssadd),
ctx!("SSDEL", drawing::ssdel),
+4 -169
View File
@@ -836,73 +836,6 @@ pub fn regapp(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
Ok(Flow::Value(Value::str(name.trim())))
}
/// `(textbox elist)`: the smallest box around a TEXT that `elist` describes (an `entget` list, or
/// a partial one with at least the string, group 1), as its lower-left and upper-right corners
/// relative to the insertion point, the text unrotated and left-justified. Groups the list
/// leaves out take the current text style (TEXTSTYLE) and that style's height (TEXTSIZE when
/// the style's is 0), width factor and obliquing. The text is shaped as it is drawn, so the box
/// is that of the drawn glyphs (control codes such as `%%u` as drawn): its first corner is the
/// insertion point unless letters reach below the baseline or lean left of it. A string that
/// draws nothing (spaces) gives the line's advance by the text height. nil for a list that is
/// not a TEXT.
pub fn textbox(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 1, 1)?;
let list = &a[0];
let nil = || Ok(Flow::Value(Value::Nil));
if !matches!(list, Value::Cons(_)) {
return nil();
}
let group = |code: i32| list.iter().find(|p| matches!(p.car(), Value::Int(c) if c == code)).map(|p| p.cdr());
if group(1).is_none() || group(0).is_some_and(|k| !matches!(&k, Value::Str(s) if s.eq_ignore_ascii_case("TEXT"))) {
return nil();
}
let Ok(d) = ctx.s.doc() else { return nil() };
let style = match group(7) {
Some(Value::Str(s)) => s.to_string(),
_ => d.header.str("TEXTSTYLE", "Standard"),
};
let ts = d.text_style(&style).cloned().unwrap_or_default();
let pair = |c: i32, v: Value| Value::cons(Value::Int(c), v);
let mut items = vec![pair(0, Value::str("TEXT"))];
if group(7).is_none() {
items.push(pair(7, Value::str(&style)));
}
if group(40).is_none() {
let h = if ts.height.is_finite() && ts.height > 0.0 { ts.height } else { d.header.f64("TEXTSIZE", 0.2) };
items.push(pair(40, Value::Real(h)));
}
if group(41).is_none() {
items.push(pair(41, Value::Real(ts.width_factor)));
}
if group(51).is_none() {
items.push(pair(51, Value::Real(ts.oblique)));
}
items.extend(list.iter().filter(|p| !matches!(p.car(), Value::Int(0))));
let Ok((_, _, cadcraft_doc::EntityKind::Text(t), _)) = entity_from_list(ctx, &Value::list(items)) else { return nil() };
let t = cadcraft_doc::Text {
insert: Default::default(),
align_pt: None,
rotation: 0.0,
halign: cadcraft_doc::HAlign::Left,
valign: cadcraft_doc::VAlign::Baseline,
backwards: false,
upside_down: false,
..t
};
let Ok(d) = ctx.s.doc() else { return nil() };
// The line's box runs from the font's descent to the text height over the advance; the
// drawn points give the smallest box. With nothing drawn, the advance from the baseline up.
let (sh, line) = cadcraft_render::place_text_entity(d, &t, &t.value);
let mut b = cadcraft_geom::Bounds2::from_points(sh.strokes.iter().flatten().chain(sh.glyphs.iter().flatten().flatten()).copied());
if b.is_empty() {
b = cadcraft_geom::Bounds2::from_points([cadcraft_geom::Vec2::new(0.0, 0.0), line.max]);
}
if b.is_empty() || ![b.min.x, b.min.y, b.max.x, b.max.y].iter().all(|v| v.is_finite()) {
return nil();
}
Ok(Flow::Value(Value::list([Value::point(&[b.min.x, b.min.y, 0.0]), Value::point(&[b.max.x, b.max.y, 0.0])])))
}
/// The upper-case names of every application registered in the drawing or carrying xdata on an object.
fn xdata_app_names(d: &cadcraft_doc::Drawing) -> std::collections::BTreeSet<String> {
std::iter::once(&d.model)
@@ -931,9 +864,8 @@ fn entity_from_list(ctx: &Ctx<'_>, list: &Value) -> Result<ListedEntity, LispErr
Some((mut common, k)) => {
if let Some(apps) = &xdata {
for (app, groups) in apps {
// `ACAD` on a dimension holds its overrides (DSTYLE), written from the model; on
// a leader its DSTYLE list does, and the rest of the run is kept.
if cadcraft_doc::is_model_xdata(app, groups, &k) {
// `ACAD` on a dimension holds its overrides (DSTYLE), written from the model.
if cadcraft_doc::is_model_xdata_app(app, &k) {
return Err(LispError::new(format!("bad DXF group: xdata application {app} of a {kind} is written from its own properties")));
}
cadcraft_doc::set_xdata_app(&mut common.xdata, app, Some(groups));
@@ -1092,12 +1024,6 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
{
new.attribs = was.attribs.clone();
}
// A leader's style overrides are read from its `ACAD` DSTYLE xdata with the file's handle
// tables, which a list has not: they are kept from the leader, and a list that gives a
// DSTYLE list as raw xdata was refused above (`entity_from_list`).
if let (cadcraft_doc::EntityKind::Leader(new), cadcraft_doc::EntityKind::Leader(was)) = (&mut kind, &old.kind) {
new.overrides.clone_from(&was.overrides);
}
let Ok(d) = ctx.s.doc_mut() else { return Ok(Flow::Value(Value::Nil)) };
d.ensure_layer(&common.layer);
let ok = d
@@ -1965,7 +1891,7 @@ pub fn load_source(s: &Session, name: &str) -> Option<String> {
// startup files) a relative name is read as given.
let dir = match s.lisp_support_dir() {
Some(d) if !std::path::Path::new(name).is_absolute() => d,
_ => return read_module(candidates.iter().map(std::path::PathBuf::from)),
_ => return candidates.iter().find_map(super::builtins::read_text_file),
};
// A relative name stays inside the support folder: plain folder and file names only. `..` would
// climb out of it, and on Windows a rooted name (`\tools`) or a drive-relative one (`C:tools`,
@@ -1974,98 +1900,7 @@ pub fn load_source(s: &Session, name: &str) -> Option<String> {
if !std::path::Path::new(name).components().all(|c| matches!(c, Component::Normal(_) | Component::CurDir)) {
return None;
}
read_module(candidates.iter().map(|c| dir.join(c)))
}
/// Read the first candidate that exists, trying each exact name first. A module written on Windows
/// names its include in one case and ships the file in another: Windows resolved that for free and
/// a case-sensitive file system does not, so when no candidate matched, retry with the case of the
/// name ignored. The folders in a candidate are used exactly as given.
fn read_module(paths: impl Iterator<Item = std::path::PathBuf>) -> Option<String> {
let paths: Vec<std::path::PathBuf> = paths.collect();
if let Some(text) = paths.iter().find_map(super::builtins::read_text_file) {
return Some(text);
}
paths.iter().find_map(|path| resolve_name_ignoring_case(path).and_then(|found| super::builtins::read_text_file(&found)))
}
/// Find `path` when only the case of its last component differs from what is on disk.
///
/// Where a folder holds more than one spelling that matches, the smallest name wins, so the answer
/// does not depend on directory order.
#[cfg(not(target_arch = "wasm32"))]
fn resolve_name_ignoring_case(path: &std::path::Path) -> Option<std::path::PathBuf> {
let wanted = path.file_name()?.to_str()?.to_lowercase();
let dir = match path.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent,
_ => std::path::Path::new("."),
};
// Listing a folder opens it, and for a network path contacts its host: ask first.
crate::file_access::check_read(dir).ok()?;
let mut best: Option<std::path::PathBuf> = None;
for entry in std::fs::read_dir(dir).ok()?.flatten() {
let name = entry.file_name();
let Some(candidate) = name.to_str() else { continue };
if candidate.to_lowercase() != wanted {
continue;
}
let full = dir.join(candidate);
// A link counts as the file it leads to. Following it opens its target, so ask first.
if crate::file_access::check_read(&full).is_err() || !std::fs::metadata(&full).is_ok_and(|meta| meta.is_file()) {
continue;
}
if best.as_ref().is_none_or(|prev| full < *prev) {
best = Some(full);
}
}
best
}
/// The web has no file system for path lookup.
#[cfg(target_arch = "wasm32")]
fn resolve_name_ignoring_case(_path: &std::path::Path) -> Option<std::path::PathBuf> {
None
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod case_lookup_tests {
use super::resolve_name_ignoring_case;
use crate::file_access::{AutomationRoots, confine};
/// Under automation roots the case fallback lists only a folder the roots let it read, and a
/// link that leaves them is not a match.
#[test]
fn the_case_fallback_stays_inside_the_automation_roots() {
let base = std::env::temp_dir().join(format!("cadcraft-case-roots-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let (inside, outside) = (base.join("in"), base.join("outside"));
std::fs::create_dir_all(&inside).unwrap();
std::fs::create_dir_all(&outside).unwrap();
std::fs::write(inside.join("Tool.lsp"), "").unwrap();
std::fs::write(outside.join("Tool.lsp"), "").unwrap();
let roots = AutomationRoots::new(Some(&inside), None).unwrap();
let find = |path: std::path::PathBuf| confine(roots.as_ref(), || resolve_name_ignoring_case(&path));
assert!(find(inside.join("tool.lsp")).is_some(), "found inside the read root");
assert!(find(outside.join("tool.lsp")).is_none(), "nothing is found outside the roots");
#[cfg(unix)]
{
// A link's target is read from the link's own folder, so these hold even where the
// temporary folder's path is relative.
std::os::unix::fs::symlink("../outside/Tool.lsp", inside.join("Away.lsp")).unwrap();
assert!(inside.join("Away.lsp").is_file(), "the link has a target");
assert!(find(inside.join("away.lsp")).is_none(), "a link that leaves the roots");
// This link may be read, since it leads back inside: only the check on the folder
// itself keeps the fallback from listing that folder and finding it.
std::os::unix::fs::symlink("../in/Tool.lsp", outside.join("Back.lsp")).unwrap();
let back = confine(roots.as_ref(), || crate::file_access::check_read(outside.join("Back.lsp")));
assert_eq!(back, Ok(()));
assert!(find(outside.join("back.lsp")).is_none(), "a folder outside the roots is not listed");
}
// Without roots nothing is confined.
assert!(resolve_name_ignoring_case(&outside.join("tool.lsp")).is_some());
let _ = std::fs::remove_dir_all(&base);
}
candidates.iter().find_map(|c| super::builtins::read_text_file(dir.join(c)))
}
#[cfg(test)]
-45
View File
@@ -86,51 +86,6 @@ impl GetRequest {
}
}
/// Whether an answer given up front (`lisp {code, inputs}`) is read as the prompt reads one
/// ([`GetRequest::supplied`]) instead of being the value as it is: `getangle` and `getorient`
/// return radians whatever the form of the answer.
pub fn reads_supplied(&self) -> bool {
matches!(self.kind, GetKind::Angle { .. })
}
/// What an answer given up front gives, read as the same answer at the prompt: a number as
/// that number typed (in AUNITS), a string as the text typed ([`GetRequest::typed`]), a point
/// as a point picked, nil as Enter. The point is in the UCS, as the routine sees points.
pub fn supplied(&self, s: &mut Session, v: &Value) -> Answer {
let r = match v {
Value::Nil => self.answer_value(s, Input::Enter),
Value::Int(i) => self.text(s, &i.to_string()),
Value::Real(x) => self.text(s, &x.to_string()),
Value::Str(t) => self.typed(s, t),
other => match other.as_point() {
Some(p) => self.point(s, p),
None => Err("Requires valid numeric angle or second point.".into()),
},
};
match r {
Ok(v) => Answer::Value(v),
Err(Again::Second(p)) => Answer::Second(p),
Err(Again::Msg(m)) => Answer::Again(m),
}
}
/// What text gives, read as the command line reads it typed at the prompt
/// (`Session::typed_token`): empty or blank text is Enter, a keyword is that keyword,
/// coordinates are a point (`1,1`, `@1,1`, `1<45`, `*1,1`: in the current UCS, the relative
/// forms from the last point), and anything else is text (`45`, `45d`, `0.5r`, `50g`).
fn typed(&self, s: &mut Session, t: &str) -> Result<Value, Again> {
let t = t.trim();
if t.is_empty() {
return self.answer_value(s, Input::Enter);
}
if keyword(&self.initget.keywords, t).is_none()
&& let Some(p) = s.parse_typed_point(t, s.last_point)
{
return self.answer_value(s, Input::Point(p));
}
self.text(s, t)
}
fn answer_value(&self, s: &mut Session, input: Input) -> Result<Value, Again> {
let ig = &self.initget;
let no_null = ig.bits & 1 != 0;
-130
View File
@@ -619,91 +619,6 @@ fn entmod_of_a_block_reference_keeps_its_attributes() {
assert_eq!(insert(&s).1, want);
}
/// entmod of a leader keeps its own dimension style overrides: they come from its DSTYLE xdata,
/// read with the file's handle tables, and a list rebuilds the leader without them (#3721).
#[test]
fn entmod_of_a_leader_keeps_its_style_overrides() {
let mut s = session();
let overrides = serde_json::json!({ "arrowSize": 1.5, "leaderArrowBlock": "_ArchTick" });
let overrides = overrides.as_object().cloned().unwrap();
let leader = cadcraft_doc::Leader {
vertices: vec![cadcraft_geom::Vec3::ZERO, cadcraft_geom::Vec3::new(10.0, 0.0, 0.0)],
arrow: true,
spline: false,
style: "Standard".into(),
overrides: overrides.clone(),
};
s.doc_mut().unwrap().add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), cadcraft_doc::EntityKind::Leader(leader)).unwrap();
let leader = |s: &Session| {
s.doc()
.unwrap()
.model
.iter()
.find_map(|e| match &e.kind {
cadcraft_doc::EntityKind::Leader(l) => Some((e.common.layer.clone(), l.overrides.clone())),
_ => None,
})
.unwrap()
};
ok(&mut s, "(setq d (entget (entlast))) (entmod (subst (cons 8 \"UGO\") (assoc 8 d) d))");
assert_eq!(leader(&s), ("UGO".to_string(), overrides));
}
/// A session with one leader that has `overrides`.
fn session_with_leader(overrides: serde_json::Value) -> Session {
let mut s = session();
let leader = cadcraft_doc::Leader {
vertices: vec![cadcraft_geom::Vec3::ZERO, cadcraft_geom::Vec3::new(10.0, 0.0, 0.0)],
arrow: true,
spline: false,
style: "Standard".into(),
overrides: overrides.as_object().cloned().unwrap(),
};
s.doc_mut().unwrap().add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), cadcraft_doc::EntityKind::Leader(leader)).unwrap();
s
}
/// The overrides of the one leader of a drawing.
fn leader_overrides(d: &cadcraft_doc::Drawing) -> serde_json::Map<String, serde_json::Value> {
d.model
.iter()
.find_map(|e| match &e.kind {
cadcraft_doc::EntityKind::Leader(l) => Some(l.overrides.clone()),
_ => None,
})
.unwrap()
}
/// A leader's DSTYLE list is its style overrides, written from the model: `ACAD` xdata that
/// holds one is refused by entmod and entmake (nil, nothing changes), with or without overrides
/// on the leader. Other `ACAD` data on a leader is taken and survives a save beside them.
#[test]
fn a_dstyle_list_in_a_leaders_acad_xdata_is_refused_and_other_acad_data_kept() {
const DSTYLE: &str = "(-3 (\"ACAD\" (1000 . \"DSTYLE\") (1002 . \"{\") (1070 . 41) (1040 . 9.0) (1002 . \"}\")))";
for overrides in [serde_json::json!({}), serde_json::json!({ "arrowSize": 1.5 })] {
let mut s = session_with_leader(overrides.clone());
let want = overrides.as_object().cloned().unwrap();
let count = s.doc().unwrap().model.len();
assert_eq!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '({DSTYLE})))")), "nil", "{overrides}");
assert_eq!(ok(&mut s, "(assoc -3 (entget (entlast) '(\"*\")))"), "nil", "{overrides}");
assert_eq!(leader_overrides(s.doc().unwrap()), want);
// The same list after other groups of the run, and a new leader made with it.
let later = DSTYLE.replace("(\"ACAD\" ", "(\"ACAD\" (1000 . \"MINE\") ");
assert_eq!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '({later})))")), "nil", "{overrides}");
assert_eq!(ok(&mut s, &format!("(entmake (append (entget (entlast)) '({DSTYLE})))")), "nil", "{overrides}");
assert_eq!(s.doc().unwrap().model.len(), count, "nothing was made");
// Other ACAD data, also a string that only reads DSTYLE, is foreign data and stays.
let other = "(\"ACAD\" (1000 . \"DSTYLE\") (1000 . \"MINE\") (1070 . 42))";
assert!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '((-3 {other}))))")).contains("LEADER"));
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"ACAD\"))))"), format!("({other})"));
assert_eq!(leader_overrides(s.doc().unwrap()), want);
let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap();
assert_eq!(leader_overrides(&back), want, "the overrides after a save and reopen");
s.open_drawing(back, "back", None);
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"ACAD\"))))"), format!("({other})"), "{overrides}");
}
}
/// An edit that leaves every handle where it was (a layer change) keeps entlast's cached order;
/// one that adds an entity rebuilds it.
#[test]
@@ -1461,51 +1376,6 @@ fn a_leading_newline_ends_the_command_line_instead_of_adding_an_empty_one() {
assert_eq!(&s.log[from..], ["Hello", "", "After a blank"]);
}
/// A module written on Windows names its include in one case and ships the file in another.
/// Windows resolved that for free; a case-sensitive file system does not.
#[test]
fn load_finds_a_support_file_named_in_another_case() {
let dir = std::env::temp_dir().join(format!("cadcraft-lisp-case-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("UpperCase.lsp"), "(setq case-test-loaded 1)").unwrap();
let mut s = session();
s.set_lisp_support_dir(Some(dir.clone()));
let _ = ok(&mut s, "(load \"uppercase\")");
assert_eq!(to_text(&s.lisp_var("CASE-TEST-LOADED"), true), "1", "(load \"uppercase\") reads UpperCase.lsp");
// An exact name still wins when the folder also holds a spelling that differs only by case.
// Where the folder ignores case (Windows and macOS by default) the two names are one file, so
// there is nothing to choose between.
std::fs::write(dir.join("case-probe"), "").unwrap();
if !dir.join("CASE-PROBE").exists() {
std::fs::write(dir.join("variant.lsp"), "(setq picked 1)").unwrap();
std::fs::write(dir.join("Variant.lsp"), "(setq picked 2)").unwrap();
let _ = ok(&mut s, "(load \"variant\")");
assert_eq!(to_text(&s.lisp_var("PICKED"), true), "1", "the exact name wins");
}
let _ = std::fs::remove_dir_all(&dir);
}
/// A support file may be a link: it counts as the file it leads to.
#[cfg(unix)]
#[test]
fn load_finds_a_linked_support_file_named_in_another_case() {
let dir = std::env::temp_dir().join(format!("cadcraft-lisp-case-link-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("kept")).unwrap();
std::fs::write(dir.join("kept/real.lsp"), "(setq linked-loaded 1)").unwrap();
// The target is read from the link's own folder, so it holds even where `dir` is relative.
std::os::unix::fs::symlink("kept/real.lsp", dir.join("Linked.lsp")).unwrap();
let mut s = session();
s.set_lisp_support_dir(Some(dir.clone()));
let _ = ok(&mut s, "(load \"linked\")");
assert_eq!(to_text(&s.lisp_var("LINKED-LOADED"), true), "1", "(load \"linked\") reads through Linked.lsp");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn startup_files_load_from_the_support_folder() {
let dir = std::env::temp_dir().join(format!("cadcraft-lisp-startup-{}", std::process::id()));
+1 -3
View File
@@ -189,9 +189,7 @@ mod tests {
for b in cadcraft_doc::BUILTIN_PLOT_STYLE_TABLES {
assert!(e.contains(b), "{b}: {e}");
}
// At least the 490 of the drawing's own that are not listed (the user's plot style folder may add some).
let more = e.split(" and ").last().and_then(|t| t.split_whitespace().next()).and_then(|n| n.parse::<usize>().ok());
assert!(more.is_some_and(|n| n >= 490), "{e}");
assert!(e.contains("and 490 more"), "{e}");
assert!(e.len() < 1000, "{} bytes: {e}", e.len());
assert!(RenderLook::from_params(&d, &json!({"plot_style": d.plot_style_tables[7].name.clone()})).is_ok());
}
+16 -121
View File
@@ -262,11 +262,9 @@ fn in_text(d: &Drawing, e: &Entity, view: &ViewportBounds<'_>, p: Vec2) -> bool
// the text there, not the text the dimension's own geometry would place.
EntityKind::Dimension(dm) => match dm.block.as_ref().and_then(|n| d.block(n)) {
// The block draws translated by the insertion point (group 12): test there (#2634).
// A text the block does not draw, on a layer frozen for the drawing or turned off, is
// not there to pick (#3218).
Some(blk) => {
let p = p - dm.insertion_point.xy();
blk.entities.iter().filter(|be| !view.leaves_out(be) && block_object_drawn(d, e, be)).any(|be| match &be.kind {
blk.entities.iter().filter(|be| !view.leaves_out(be)).any(|be| match &be.kind {
EntityKind::MText(t) => in_box(cadcraft_render::layout_mtext_entity(d, t).strokes.into_iter().flatten(), t.rotation, p),
EntityKind::Text(_) => entity_bounds(d, be, 0).contains(p),
_ => false,
@@ -284,18 +282,6 @@ fn in_text(d: &Drawing, e: &Entity, view: &ViewportBounds<'_>, p: Vec2) -> bool
}
}
/// Whether a block's object `be` is drawn on its layer: its own visibility and its layer's, layer
/// "0" inside a block taking the layer of the reference `e` that draws it, as the renderer resolves
/// them (`crates/render/src/props.rs`). A layer frozen for the whole drawing, or turned off, draws
/// nothing there, so nothing there is picked.
fn block_object_drawn(d: &Drawing, e: &Entity, be: &Entity) -> bool {
if !be.common.visible {
return false;
}
let layer = if be.common.layer == "0" { e.common.layer.as_str() } else { be.common.layer.as_str() };
d.layer(layer).is_none_or(cadcraft_doc::Layer::visible)
}
/// Whether `p` is inside the box around `pts` turned by `angle` (the box of text set at `angle`).
fn in_box(pts: impl Iterator<Item = Vec2>, angle: f64, p: Vec2) -> bool {
let turn = |q: Vec2| q.rotate(-angle);
@@ -475,58 +461,6 @@ fn touch_box_in<'a>(d: &'a Drawing, e: &Entity, known: Option<Bounds2>, view: &m
outline_in(d, e, view, b)
}
/// The strokes and glyph outlines a top-level TEXT, ATTDEF or MTEXT draws, where the renderer
/// places them: turned with the text, at the size it draws at the current annotation scale (none
/// when that scale hides it), upright when it matches the layout's orientation. `None` for any
/// other entity, for a blank MTEXT, which is selected by its frame ([`blank_mtext_box`]), and for
/// text that draws nothing (hidden by the annotation scale, or with no finite point).
///
/// The document's box for text ([`entity_bounds`]) is an estimate from the number of characters
/// (and of lines). It differs from what the fonts draw, and on the side a justified line or an
/// attachment point leaves open it reaches past the text, so a window that held all of a text,
/// turned or not, missed it when it tested only that box (#3731). A selection that must hold the
/// text (a window, a window polygon) takes it when it holds the box, as before, or else when it
/// holds these. A selection that only has to touch the text tests the box alone.
fn drawn_text(d: &Drawing, e: &Entity) -> Option<Vec<Vec<Vec2>>> {
match &e.kind {
EntityKind::Text(_) | EntityKind::AttDef(_) => {}
EntityKind::MText(t) if !is_blank_mtext(t) => {}
_ => return None,
}
let scaled;
let e = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Plain => e,
cadcraft_doc::AnnoDraw::Hidden => return None,
cadcraft_doc::AnnoDraw::Scaled(f) => {
scaled = cadcraft_doc::anno_scaled(e, f);
&scaled
}
};
let line = |sh: cadcraft_fonts::Shaped| sh.strokes.into_iter().chain(sh.glyphs.into_iter().flatten()).collect::<Vec<_>>();
let strokes = match &e.kind {
EntityKind::Text(t) if e.common.matches_layout_orientation() => {
line(cadcraft_render::place_text_entity(d, &cadcraft_doc::Text { rotation: 0.0, ..t.clone() }, &t.value).0)
}
EntityKind::Text(t) => line(cadcraft_render::place_text_entity(d, t, &t.value).0),
EntityKind::AttDef(a) => line(cadcraft_render::place_text_entity(d, &a.text, &a.tag).0),
EntityKind::MText(t) => {
let upright;
let t = if e.common.matches_layout_orientation() && t.rotation != 0.0 {
upright = cadcraft_doc::MText { rotation: 0.0, ..t.clone() };
&upright
} else {
t
};
cadcraft_render::layout_mtext_entity(d, t).strokes
}
_ => return None,
};
// Points that aren't finite are left out; a text left with none draws nothing to hold.
let strokes: Vec<Vec<Vec2>> =
strokes.into_iter().map(|s| s.into_iter().filter(|p| p.is_finite()).collect::<Vec<_>>()).filter(|s| !s.is_empty()).collect();
(!strokes.is_empty()).then_some(strokes)
}
pub(crate) fn is_infinite(e: &Entity) -> bool {
matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_))
}
@@ -740,14 +674,7 @@ fn in_window_in<'a>(
if !infinite && bx.contains_box(&eb) {
return true;
}
// A window also holds a text whose box it doesn't hold when it holds what the text draws
// ([`drawn_text`], #3731). Only a text whose box reaches into the window is shaped.
if !crossing {
return !infinite
&& eb.intersects(bx)
&& drawn_text(d, e).is_some_and(|strokes| bx.contains_box(&Bounds2::from_points(strokes.into_iter().flatten())));
}
if !infinite && !outline_in(d, e, view, eb).intersects(bx) {
if !crossing || (!infinite && !outline_in(d, e, view, eb).intersects(bx)) {
return false;
}
let polys = hit_polylines_in(d, e, view, tol, true);
@@ -851,26 +778,21 @@ pub fn select_polygon_in(d: &Drawing, space: &Space, frozen: &[String], poly: &[
continue;
}
let eb = if crossing { touch_box_in(d, e, known, &mut view) } else { bounds_in(d, e, known, &mut view) };
let boxed = infinite || if crossing { eb.intersects(&pb) } else { pb.contains_box(&eb) };
let test = |polys: &[Vec<Vec2>]| {
let crosses = polys.iter().any(|pl| {
pl.windows(2).any(|w| {
w.first().zip(w.get(1)).is_some_and(|(p, q)| edges.iter().any(|f| cadcraft_geom::line_line(f, &Line::new(*p, *q)).is_some()))
})
});
let mut pts = polys.iter().flatten();
if crossing {
crosses || pts.any(|p| point_in_polygon(poly, *p))
} else {
!crosses && !polys.is_empty() && pts.all(|p| point_in_polygon(poly, *p))
}
};
let mut hit = boxed && test(&hit_polylines_in(d, e, &mut view, tol, crossing));
// A window polygon also holds a text whose box it doesn't hold when it holds what the text
// draws ([`drawn_text`], #3731).
if !hit && !crossing && eb.intersects(&pb) {
hit = drawn_text(d, e).is_some_and(|strokes| test(&strokes));
if !infinite && if crossing { !eb.intersects(&pb) } else { !pb.contains_box(&eb) } {
continue;
}
let polys = hit_polylines_in(d, e, &mut view, tol, crossing);
let crosses = polys.iter().any(|pl| {
pl.windows(2).any(|w| {
w.first().zip(w.get(1)).is_some_and(|(p, q)| edges.iter().any(|f| cadcraft_geom::line_line(f, &Line::new(*p, *q)).is_some()))
})
});
let mut pts = polys.iter().flatten();
let hit = if crossing {
crosses || pts.any(|p| point_in_polygon(poly, *p))
} else {
!crosses && !polys.is_empty() && pts.all(|p| point_in_polygon(poly, *p))
};
if hit {
out.push(e.handle);
}
@@ -1028,33 +950,6 @@ mod tests {
assert_eq!(pick(&d, &Space::Model, Vec2::new(41.3, 50.0), 1.0), Some(line));
}
/// A text whose points are all not finite (its insertion point is NaN) draws nothing a window
/// polygon could hold: no empty stroke list is passed on for it to hold by default.
#[test]
fn text_with_no_finite_point_draws_nothing_to_hold() {
let mut d = Drawing::new_metric();
let at = Vec3::new(f64::NAN, f64::NAN, 0.0);
let t = cadcraft_doc::Text {
insert: at,
align_pt: None,
height: 1.0,
value: "AB".into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: cadcraft_doc::HAlign::Left,
valign: cadcraft_doc::VAlign::Baseline,
backwards: false,
upside_down: false,
};
let h = d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap();
let e = d.entity(h).unwrap().as_ref().clone();
assert!(drawn_text(&d, &e).is_none());
let square = [Vec2::new(-1e6, -1e6), Vec2::new(1e6, -1e6), Vec2::new(1e6, 1e6), Vec2::new(-1e6, 1e6)];
assert!(select_polygon(&d, &Space::Model, &square, false).is_empty());
}
fn mtext_at(contents: &str, attach: u8, rotation: f64) -> EntityKind {
EntityKind::MText(cadcraft_doc::MText {
insert: Vec3::new(0.0, 0.0, 0.0),
+14 -23
View File
@@ -5,8 +5,6 @@ impl Session {
/// script line (see [`Session::script`]), so `MOVE L 0,0 5,5` ends the selection with the
/// second space and `ERASE L ` with the trailing one. Input after the command ends is ignored.
pub fn cmdline(&mut self, text: &str) -> Result<()> {
// The line is typed at the prompt that follows the value the frames are working out.
self.lisp_settle_answer();
let t = text.trim_end_matches(['\r', '\n']);
// The command line types spaces literally at free-text prompts: the line is one input.
if self.current_prompt().is_some_and(|p| p.accept.text && !p.accept.point && !p.accept.number) {
@@ -46,8 +44,6 @@ impl Session {
// comes after that routine: carry it on first, as the window's frames would.
if script {
self.lisp_run_until_input();
} else {
self.lisp_settle_answer();
}
if self.running.is_none() {
if !script && !first {
@@ -126,7 +122,20 @@ impl Session {
return Ok(());
}
};
return self.lisp_answer(v);
return match v {
lisp::value::Value::Nil => Ok(()),
lisp::value::Value::Int(i) => self.typed_token(&i.to_string(), false),
lisp::value::Value::Real(r) => self.typed_token(&format!("{r}"), false),
lisp::value::Value::Str(s) => self.typed_token(&s, false),
other => match other.as_point() {
// A point from LISP is in the current UCS, as typed coordinates are.
Some(p) => self.input(Input::Point(self.input_ucs().to_wcs(Vec2::new(p[0], p[1])))),
None => {
self.echo(format!("Invalid input: {}", lisp::value::to_text(&other, true)));
Ok(())
}
},
};
}
// At "Select objects" prompts the selection modes (Previous, Last, ALL) win over a command
// keyword sharing the letter (HATCH's "picK internal point" against `P`). A word typed with
@@ -187,24 +196,6 @@ impl Session {
self.input(Input::Text(tt.to_string()))
}
/// Answer the running command's prompt with the value of a LISP expression typed at it.
pub(crate) fn lisp_answer(&mut self, v: lisp::value::Value) -> Result<()> {
match v {
lisp::value::Value::Nil => Ok(()),
lisp::value::Value::Int(i) => self.typed_token(&i.to_string(), false),
lisp::value::Value::Real(r) => self.typed_token(&format!("{r}"), false),
lisp::value::Value::Str(s) => self.typed_token(&s, false),
other => match other.as_point() {
// A point from LISP is in the current UCS, as typed coordinates are.
Some(p) => self.input(Input::Point(self.input_ucs().to_wcs(Vec2::new(p[0], p[1])))),
None => {
self.echo(format!("Invalid input: {}", lisp::value::to_text(&other, true)));
Ok(())
}
},
}
}
/// Run a script, as AutoCAD reads one: a space or a line end ends an input, and an empty
/// input (two spaces in a row, a space at the end of a line, an empty line) is Enter. At
/// free-text prompts spaces are part of the text. Lines starting with `;` are comments.
+1 -30
View File
@@ -43,15 +43,12 @@ impl Session {
/// Launch a non-nested interactive state machine through the standard command-start checks
/// (`enabled`, `refused_in_editor`, `commands_started`, `last_command`, `Guarded`, `feed`).
/// As in [`Session::start`], the value of an expression the frames are working out answers
/// its prompt before the command it was typed in is cancelled for this one.
pub(crate) fn launch_interactive(
&mut self,
id: &str,
enabled: fn(&Session) -> std::result::Result<(), String>,
machine: Box<dyn crate::Interactive>,
) -> Result<()> {
self.lisp_settle_answer();
self.last_polar = None;
self.pick_hint = None;
if self.running.is_some() {
@@ -81,12 +78,6 @@ impl Session {
self.command_origin
}
/// Whether the input now arriving is the person's own, not a script, LISP routine or
/// JSON/MCP call. Source only: it does not read Shift.
pub fn person_input(&self) -> bool {
self.command_origin == Origin::Person && !self.in_script && !self.program_input
}
/// Whether an AutoLISP routine is feeding the command line now: the `(command …)` call it makes,
/// or the token it types into a command that is already running. A script's own lines are the
/// program's input too ([`Session::start`] records [`Origin::Program`] for them), so this tells a
@@ -113,7 +104,6 @@ impl Session {
/// [`Session::start`] with the command's origin recorded for its whole life.
fn start_from(&mut self, name: &str, origin: Origin) -> Result<()> {
self.lisp_settle_answer();
self.last_polar = None;
self.pick_hint = None;
let name = name.trim();
@@ -227,9 +217,6 @@ impl Session {
/// Feed an object-snap pick, retaining its viewport origin for measurements. Point modifiers
/// that combine or constrain coordinates produce ordinary drawing-space points.
pub fn input_snapped(&mut self, hit: snap::SnapHit) -> Result<()> {
// The value of an expression the frames are working out comes before this pick, and is a
// typed one: it answers its prompt before the pick's origin is in place.
self.lisp_settle_answer();
let source = hit.viewport.filter(|_| self.point_mods.iter().all(|f| matches!(f, pointmod::Frame::Snap { mode } if *mode != 0)));
let previous = std::mem::replace(&mut self.picked_viewport, source);
let result = self.input(hit.input());
@@ -241,7 +228,6 @@ impl Session {
/// command (as in AutoCAD) and points do nothing. A LISP routine waiting in a `get…`
/// function takes the input instead; one paused in `command` carries on after it.
pub fn input(&mut self, input: Input) -> Result<()> {
self.lisp_settle_answer();
self.inputs = self.inputs.wrapping_add(1);
if self.lisp_input(input.clone()) {
return Ok(());
@@ -492,7 +478,6 @@ impl Session {
}
Err(EngineError::Internal(id, m)) => {
// Restore and end the command.
self.lisp_host_ends(self.suspended.is_some());
if let Ok(st) = self.state_mut() {
st.restore_drawing(run.before.clone());
}
@@ -527,9 +512,6 @@ impl Session {
// A typed selection mode or SIngle never outlives its command.
self.select_mode = None;
self.select_single = false;
// The command an expression was typed at the prompt of ends inside that expression's
// routine (Esc, or the expression failed): it is no command of the routine's.
let host = self.lisp_host_ends(self.suspended.is_some());
if find_command(&run.id).is_some_and(|c| c.undoable)
&& let Err(e) = self.refuse_non_finite(None, &run.before, &run.selection_before, &run.id)
{
@@ -552,7 +534,7 @@ impl Session {
// A transparent command's changes belong to the command it ran inside, and a command a
// LISP routine ran belongs to the routine's single undo step (the routine keeps it for U
// inside it).
if self.suspended.is_some() || (self.lisp_groups_undo() && !host) {
if self.suspended.is_some() || self.lisp_groups_undo() {
if let Ok(st) = self.state_mut()
&& !Arc::ptr_eq(&run.before, &st.doc)
{
@@ -569,10 +551,6 @@ impl Session {
st.push_undo(Snapshot { label: label.to_string(), doc: run.before, selection: run.selection_before });
st.revision += 1;
}
// The routine's own undo step starts after the command it was started in.
if host {
self.lisp_rebase();
}
}
/// The post-command passes, in order, run after every command — by [`Session::execute`] and
@@ -762,9 +740,6 @@ impl Session {
/// Change the running array's live parameters. With no array running this does nothing; an
/// invalid value is refused and leaves the command as it was.
pub fn set_array_live(&mut self, v: &crate::ArrayLive) -> Result<()> {
// An edit in the array window comes after the value the frames are working out, which
// can change the array or end the command.
self.lisp_settle_answer();
if self.array_live().is_none() {
return Ok(());
}
@@ -777,16 +752,12 @@ impl Session {
/// Ask the running polar array for its centre as the next canvas point
/// ([`Interactive::array_pick_center`]).
pub fn array_pick_center(&mut self) -> bool {
// The value the frames are working out answers the prompt it was typed at, not the centre's.
self.lisp_settle_answer();
self.running.as_mut().is_some_and(|r| r.machine.array_pick_center())
}
/// Finish the running array: `Ok(true)` when the command ended, `Ok(false)` when there is no
/// array command or it is still selecting objects.
pub fn commit_array(&mut self) -> Result<bool> {
// The value the frames are working out is part of the array that is finished.
self.lisp_settle_answer();
if self.array_live().is_none() {
return Ok(false);
}
-11
View File
@@ -8,9 +8,6 @@ impl Session {
/// the next point, where the drag ends, closes it). Only while objects are being selected: no
/// command running, or a command asking for objects. Returns whether a window was opened.
pub fn begin_window(&mut self, corner: Vec2) -> bool {
// The drag comes after the value the frames are working out: that value answers its
// prompt first, and may be the corner of a window of its own or end the command.
self.lisp_settle_answer();
let during_command = self.running.is_some();
if !self.settings.pickdrag || !corner.is_finite() || (during_command && !self.current_prompt().is_some_and(|p| p.accept.select)) {
return false;
@@ -31,8 +28,6 @@ impl Session {
/// PICKADD on (the default): picks add to the selection and Shift removes. PICKADD off: each pick
/// replaces the selection and Shift adds (Shift+pick on a selected object removes it).
pub fn idle_click(&mut self, p: Vec2, shift: bool) -> Result<()> {
// A click comes after the value the frames are working out, as every input does.
self.lisp_settle_answer();
let space = self.space();
let pickadd = self.settings.pickadd;
if let Some(pw) = self.pending_window.take() {
@@ -119,9 +114,6 @@ impl Session {
/// Pick `h` from the selection cycling list, as a click on it alone would have: into the
/// command at "Select objects", else into the selection (Shift as for [`Self::idle_click`]).
pub fn pick_cycled(&mut self, h: Handle, shift: bool) -> Result<()> {
// Whether a command takes the pick is known once the value the frames are working out
// has answered its prompt: that value can end the command.
self.lisp_settle_answer();
// The list may be older than an undo or an erase.
if self.doc()?.entity(h).is_none() {
return Ok(());
@@ -152,9 +144,6 @@ impl Session {
/// only: a later pick at the same point finds what lies there. Other prompts take the object
/// as a pick.
pub fn input_object(&mut self, h: Handle, at: Option<Vec2>) -> Result<()> {
// What the prompt takes is read once the value the frames are working out has answered
// its own prompt: the object is for the prompt after it.
self.lisp_settle_answer();
let one = self.current_prompt().is_some_and(|p| p.accept.point && !p.accept.select && p.picks_objects());
let p = if one { at.or_else(|| self.doc().ok().and_then(|d| group_10(d, d.entity(h)?))) } else { None };
let Some(p) = p.filter(|p| p.is_finite()) else { return self.input(Input::Pick(vec![h])) };
+4
View File
@@ -146,6 +146,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 {
@@ -216,6 +219,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",
@@ -80,10 +87,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),
@@ -172,6 +223,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)),
@@ -184,6 +241,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).
@@ -252,6 +312,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))
}
@@ -272,6 +337,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",
@@ -299,10 +365,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
@@ -320,11 +391,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" => {
@@ -430,6 +507,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)),
-15
View File
@@ -483,21 +483,6 @@ fn copy_and_rotate_drag_as_a_transform_of_the_selection() {
let EntityKind::Text(t) = &extra[1].kind else { panic!("expected the text") };
assert!(t.insert.xy().near(Vec2::new(-2.0, 2.0), 1e-9) && t.rotation.abs() < 1e-9, "mirrored, still reading left to right");
// At "Erase source objects?" the copy stays mirrored in the picked line, wherever the cursor
// goes, and the rubber band is gone (#2667).
s.cmdline("0,1").unwrap();
assert!(s.prompt_text().contains("Erase source objects?"));
let (d, extra) = s.drag(Vec2::new(7.0, -3.0)).expect("MIRROR still shows the mirrored copy");
assert_eq!(d.handles.len(), 1);
assert!(d.matrix.apply(Vec2::new(1.0, 0.0)).near(Vec2::new(-1.0, 0.0), 1e-9), "mirrored in the line from 0,0 to 0,1");
assert_eq!(extra.len(), 1, "only the text, no line to the cursor");
let preview = s.preview(Vec2::new(7.0, -3.0));
assert!(
preview.iter().any(|e| matches!(&e.kind, EntityKind::Line(l) if l.b.xy().near(Vec2::new(-1.0, 0.0), 1e-9))),
"the preview without a GPU shows the mirrored line too"
);
assert_eq!(preview.len(), 2, "the line and the text, no rubber band");
// PASTECLIP drags the clipboard.
let mut s = Session::new();
let l = s.execute("line", &json!({"points": [[0, 0], [1, 0]]})).unwrap();
+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}");
}
-69
View File
@@ -439,72 +439,3 @@ fn live_rect_excludes_levels_when_not_associative() {
s.set_array_live(&v).unwrap();
assert_eq!(s.array_live().unwrap().levels, 50);
}
/// How wide the drawing in model space is.
fn drawn_width(s: &Session) -> f64 {
let b = s.doc().unwrap().extents(&cadcraft_engine::doc::Space::Model);
b.max.x - b.min.x
}
/// OK in the array window while the frames work out a count typed at the command line: the count
/// answers its prompt first, as it has when it was worked out at once, and the array has it.
#[test]
fn commit_comes_after_a_pending_expressions_value() {
let committed = [false, true].map(|frames| {
let mut s = selected();
s.lisp_by_frames(frames);
s.start("arrayrect").unwrap();
s.cmdline("columns").unwrap();
s.cmdline(&super::lisp_answer_by_frames::slow("6")).unwrap();
assert_eq!(s.lisp_busy(), frames);
assert!(s.commit_array().unwrap(), "frames {frames}");
assert!(!s.lisp_running(), "frames {frames}: nothing of the expression is left");
drawn_width(&s)
});
let mut plain = selected();
plain.start("arrayrect").unwrap();
assert!(plain.commit_array().unwrap());
assert!(committed[0] > drawn_width(&plain), "six columns are wider than the default four");
assert_eq!(committed[1], committed[0], "over frames, and at once");
}
/// "Pick center" in the array window while the frames work out an item count: the count answers
/// the prompt it was typed at, then the command asks for the centre.
#[test]
fn pick_center_comes_after_a_pending_expressions_value() {
for frames in [false, true] {
let mut s = selected();
s.lisp_by_frames(frames);
s.start("arraypolar").unwrap();
s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap();
s.cmdline("items").unwrap();
s.cmdline(&super::lisp_answer_by_frames::slow("8")).unwrap();
assert_eq!(s.lisp_busy(), frames);
assert!(s.array_pick_center(), "frames {frames}");
assert_eq!(s.array_live().unwrap().items, 8, "frames {frames}: the count answered its own prompt");
assert!(s.current_prompt().unwrap().message.contains("center point of array"), "frames {frames}: {}", s.prompt_text());
}
}
/// An edit in the array window while the frames work out a column count typed at the command
/// line comes after that count, as it does when the count was worked out at once: the window's
/// values are the last ones given, so the array has them.
#[test]
fn an_edit_comes_after_a_pending_expressions_value() {
let lives = [false, true].map(|frames| {
let mut s = selected();
s.lisp_by_frames(frames);
s.start("arrayrect").unwrap();
let mut edited = s.array_live().unwrap();
edited.rows += 2;
s.cmdline("columns").unwrap();
s.cmdline(&super::lisp_answer_by_frames::slow("9")).unwrap();
assert_eq!(s.lisp_busy(), frames);
s.set_array_live(&edited).unwrap();
assert!(!s.lisp_running(), "frames {frames}: nothing of the expression is left");
let live = s.array_live().unwrap();
assert_eq!((live.cols, live.rows), (edited.cols, edited.rows), "frames {frames}");
live
});
assert_eq!(lives[1], lives[0], "over frames, and at once");
}
@@ -1,78 +0,0 @@
//! A dimension drawn from a block is picked on the text of that block only where the text is
//! drawn: text on a layer frozen for the whole drawing, or turned off, is not there to pick (#3218).
//! What the block draws on a drawn layer is still picked, and with the layer thawed or on the text
//! is picked as before.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{EntityKind, Handle};
use serde_json::{Value, json};
/// What the LISP `code` evaluates to, as LISP prints it.
fn lisp(s: &mut Session, code: &str) -> String {
let r = s.execute("lisp", &json!({ "code": code })).unwrap();
r["value"].as_str().unwrap().to_string()
}
/// Whether the pick at `p` finds an object.
fn picks(s: &mut Session, p: [f64; 2]) -> bool {
lisp(s, &format!("(ssget (list {} {}))", p[0], p[1])) != "nil"
}
fn handle(r: &Value) -> Handle {
r["handle"].as_str().or_else(|| r["handles"][0].as_str()).and_then(Handle::parse_hex).unwrap()
}
/// A drawing with a dimension drawn from the block "DT", as AutoCAD saves one: the block holds the
/// dimension's line and its text, and the text alone is on the layer "Hidden".
fn dimension_with_block_text() -> (Session, Handle) {
// Metric, as the issue draws it: the ISO-25 text height makes the dimension's box reach the
// block's text.
let mut s = Session::empty();
s.new_drawing(true);
s.execute("layer.new", &json!({ "name": "Hidden" })).unwrap();
let line = handle(&s.execute("line", &json!({ "points": [[0, 40], [40, 40]] })).unwrap());
s.execute("mtext", &json!({ "at": [20, 44], "text": "40", "height": 3, "attach": 5 })).unwrap();
let text = s.doc().unwrap().model.last().unwrap().handle;
s.execute("properties.set", &json!({ "handles": [text.hex()], "layer": "Hidden" })).unwrap();
assert_eq!(s.doc().unwrap().entity(text).unwrap().common.layer, "Hidden");
s.execute("block", &json!({ "name": "DT", "base": [0, 0], "handles": [line.hex(), text.hex()], "keep": "delete" })).unwrap();
let dim = handle(&s.execute("dimlinear", &json!({ "p1": [0, 5], "p2": [40, 15], "at": [20, 40] })).unwrap());
// The block the dimension draws from, as DXF group 2 of a dimension carries it.
s.doc_mut()
.unwrap()
.modify_entity(dim, |e| {
if let EntityKind::Dimension(dm) = &mut e.kind {
dm.block = Some("DT".into());
}
})
.unwrap();
(s, dim)
}
/// Sets the layer "Hidden" frozen or thawed, and off or on.
fn layer_state(s: &mut Session, frozen: bool, on: bool) {
s.execute("layer.set", &json!({ "name": "Hidden", "frozen": frozen })).unwrap();
s.execute("layer.set", &json!({ "name": "Hidden", "on": on })).unwrap();
}
#[test]
fn a_pick_inside_a_dimension_blocks_text_follows_the_text_layers_state() {
let (mut s, dim) = dimension_with_block_text();
// Thawed: the pick in the middle of the text finds the dimension, as the text is drawn.
layer_state(&mut s, false, true);
assert!(picks(&mut s, [20.0, 44.0]), "the text is drawn, so the pick inside it finds the dimension");
// Beside the text's box, and on the block's line, are as they were.
assert!(!picks(&mut s, [30.0, 44.0]), "the pick beside the text's box is on nothing");
assert!(picks(&mut s, [10.0, 40.0]), "the dimension line the block draws is picked");
// Frozen for the whole drawing: the text is not drawn, so the pick inside it finds nothing.
layer_state(&mut s, true, true);
assert!(!picks(&mut s, [20.0, 44.0]), "the text on a frozen layer is not picked");
assert!(picks(&mut s, [10.0, 40.0]), "the line the block draws on a drawn layer is still picked");
assert_eq!(s.doc().unwrap().entity(dim).unwrap().common.layer, "0", "the dimension itself stays on a drawn layer");
// Turned off: the same.
layer_state(&mut s, false, false);
assert!(!picks(&mut s, [20.0, 44.0]), "the text on a layer turned off is not picked");
assert!(picks(&mut s, [10.0, 40.0]), "the line the block draws on a drawn layer is still picked");
}
-17
View File
@@ -198,20 +198,3 @@ fn an_alignment_grip_aligns_with_the_line_at_the_cursor() {
let Some(cadcraft_engine::doc::EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| &e.kind) else { panic!("a reference") };
assert!((i.rotation.to_degrees() - 30.0).abs() < 1e-6 && i.insert.x.abs() < 1e-9 && (i.insert.y + 50.0).abs() < 1e-9);
}
/// A click on a dynamic grip while the frames work out a value typed at a command's prompt: the
/// value answers its prompt first, as it has when it was worked out at once, then the drag starts.
#[test]
fn a_grip_drag_comes_after_a_pending_expressions_value() {
for frames in [false, true] {
let (mut s, h) = session();
s.lisp_by_frames(frames);
s.cmdline("circle 0,0").unwrap();
s.cmdline(&super::lisp_answer_by_frames::slow("5")).unwrap();
assert_eq!(s.lisp_busy(), frames);
s.start_dyn_grip(h, 2, GripPart::End).unwrap();
assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("grip"), "frames {frames}");
let circles = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_engine::doc::EntityKind::Circle(_))).count();
assert_eq!(circles, 1, "frames {frames}: the radius ended CIRCLE first");
}
}
-62
View File
@@ -338,65 +338,3 @@ fn the_prompts_are_autocads_and_one_point_draws_nothing() {
let s = run("", "(command \"_.LEADER\" '(0.0 0.0) \"\")");
assert!(leaders(&s).is_empty() && mtexts(&s).is_empty());
}
/// A drawing whose current dimension style has an arrow size of 120 and whose header overrides it
/// with `SETVAR DIMASZ 1.5`, as the other DIM* variables of [`session`] are overrides too.
fn session_with_arrow_override() -> Session {
let mut s = session("");
for st in &mut s.doc_mut().unwrap().dim_styles {
st.arrow_size = 120.0;
}
s.execute("setvar", &json!({ "name": "DIMASZ", "value": 1.5 })).unwrap();
assert_eq!(s.doc().unwrap().dim_overrides().get("arrowSize"), Some(&json!(1.5)), "DIMASZ is a header override");
s
}
/// A new leader takes the drawing's DIM* overrides as a new dimension does, whichever command
/// draws it: its hook line and its arrowhead are then the same DIMASZ long.
#[test]
fn a_new_leader_takes_the_headers_dimension_overrides() {
type Draw = fn(&mut Session);
let ways: [(&str, Draw); 4] = [
("LEADER", |s| s.cmdline("(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) '(35.0 30.0) \"\" \"ABC\" \"\")").unwrap()),
("leader (JSON)", |s| drop(s.execute("leader", &json!({ "points": [[0, 0], [20, 15], [35, 30]], "text": "ABC" })).unwrap())),
("QLEADER", |s| {
for t in ["QLEADER", "0,0", "20,15", "35,30", "0", "ABC", ""] {
s.cmdline(t).unwrap();
}
}),
("qleader (JSON)", |s| drop(s.execute("qleader", &json!({ "points": [[0, 0], [20, 15], [35, 30]], "text": "ABC" })).unwrap())),
];
for (way, draw) in ways {
let mut s = session_with_arrow_override();
draw(&mut s);
assert!(s.running.is_none(), "{way}: {}", s.prompt_text());
let l = leaders(&s).remove(0);
// The hook line is the overriding DIMASZ long…
assert!(same_points(&vertices(&l), &[[0.0, 0.0], [20.0, 15.0], [33.5, 30.0], [35.0, 30.0]]), "{way}: {l:?}");
// …and the leader holds the overrides, so its arrowhead is too.
assert_eq!(l.overrides, s.doc().unwrap().dim_overrides(), "{way}");
assert_eq!(l.overrides.get("arrowSize"), Some(&json!(1.5)), "{way}");
let d = s.doc().unwrap();
let drawn = d.dim_style(&l.style).unwrap().with_overrides(&l.overrides);
assert!(near(drawn.arrow_size, 1.5), "{way}: the arrowhead is drawn {} long", drawn.arrow_size);
}
}
/// The overrides a new leader took from the header are saved as one DSTYLE list on it, and a
/// reopen reads them back.
#[test]
fn a_new_leaders_overrides_are_saved_as_one_dstyle_list() {
let mut s = session_with_arrow_override();
s.cmdline("(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) '(35.0 30.0) \"\" \"ABC\" \"\")").unwrap();
let want = leaders(&s).remove(0).overrides;
assert_eq!(want.get("arrowSize"), Some(&json!(1.5)));
let bytes = cadcraft_io::write(s.doc().unwrap(), "out.dxf").unwrap();
let text = String::from_utf8(bytes.clone()).unwrap();
assert_eq!(text.lines().filter(|l| l.trim() == "DSTYLE").count(), 1, "one DSTYLE list in the drawing, the leader's");
let back = cadcraft_io::read(&bytes, "out.dxf").unwrap();
let l = back.model.iter().find_map(|e| if let EntityKind::Leader(l) = &e.kind { Some(l.clone()) } else { None }).unwrap();
assert_eq!(l.overrides.get("arrowSize"), Some(&json!(1.5)));
let was = s.doc().unwrap().dim_style(&l.style).unwrap().with_overrides(&want);
let now = back.dim_style(&l.style).unwrap().with_overrides(&l.overrides);
assert_eq!(now, was, "the leader draws the same after a save and reopen");
}
+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<_>>());
}
@@ -1,435 +0,0 @@
//! An AutoLISP expression typed at a command's prompt, in a host that draws frames (#3666): it
//! runs a slice per frame, so Esc stops it, and nothing else about its answer changes.
use cadcraft_engine::doc::EntityKind;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::{Input, Session};
/// A loop that never ends within any allowance, counting in `i`.
const ENDLESS: &str = "(setq i 0) (while (< i 2000000000) (setq i (1+ i)))";
/// A session whose host draws frames, when `frames`.
fn session(frames: bool) -> Session {
let mut s = Session::new();
s.lisp_by_frames(frames);
s
}
/// How far the loop counted.
fn counted(s: &Session) -> f64 {
s.lisp_var("I").as_number().unwrap_or(0.0)
}
/// The radii of the drawing's circles.
fn radii(s: &Session) -> Vec<f64> {
let circle = |k: &EntityKind| if let EntityKind::Circle(c) = k { Some(c.radius) } else { None };
s.doc().unwrap().model.iter().filter_map(|e| circle(&e.kind)).collect()
}
/// The line that says the expression ran out of its allowance, if the log has one.
fn stopped_by_allowance(s: &Session) -> Option<&String> {
s.log.iter().find(|l| l.starts_with("; error:") && l.contains("steps"))
}
/// Draw frames until the routine needs no more; how many it took.
fn frames_to_the_end(s: &mut Session) -> usize {
let mut frames = 0;
while s.lisp_busy() && frames < 10_000 {
s.lisp_tick();
frames += 1;
}
assert!(!s.lisp_busy(), "the routine ended");
frames
}
/// How far [`ENDLESS`] counts as CIRCLE's radius before its allowance stops it, where no frame is
/// drawn.
fn counted_to_the_allowance() -> f64 {
let mut s = session(false);
s.cmdline(&format!("circle 0,0 (progn {ENDLESS} 5)")).unwrap();
assert!(stopped_by_allowance(&s).is_some(), "{:?}", s.log);
counted(&s)
}
/// Esc between two frames stops the expression well before its allowance does, and ends the
/// command it was typed in as a failed expression does. Without frames nothing can come between.
#[test]
fn esc_stops_an_expression_typed_at_a_prompt() {
let mut s = session(true);
s.cmdline("circle 0,0").unwrap();
s.cmdline(&format!("(progn {ENDLESS} 5)")).unwrap();
assert!(s.lisp_busy(), "the expression waits for the next frame: {:?}", s.log);
assert!(s.running.is_some(), "CIRCLE still waits for its radius");
s.lisp_tick();
assert!(s.lisp_busy(), "one more frame did not end it");
s.cancel();
assert!(!s.lisp_running(), "Esc stopped the expression");
assert!(s.running.is_none(), "and the command with it: {}", s.prompt_text());
assert_eq!(stopped_by_allowance(&s), None, "Esc stopped it, not the allowance");
assert!(counted(&s) < counted_to_the_allowance() / 2.0, "it stopped early");
assert!(radii(&s).is_empty(), "the stopped expression gave no radius");
// The command line takes the next command.
s.cmdline("circle 0,0 2").unwrap();
assert_eq!(radii(&s), [2.0]);
}
/// A value that takes several frames answers the prompt it was typed at, as one worked out at
/// once does.
#[test]
fn a_value_worked_out_over_frames_answers_the_prompt() {
let rounds = (counted_to_the_allowance() / 4.0) as i64;
let expr = format!("(progn (setq i 0) (while (< i {rounds}) (setq i (1+ i))) 5)");
let mut by_frames = session(true);
by_frames.cmdline(&format!("circle 0,0 {expr}")).unwrap();
assert!(radii(&by_frames).is_empty(), "no radius before the frames worked it out");
assert!(frames_to_the_end(&mut by_frames) > 1);
assert!(by_frames.running.is_none(), "the radius ended CIRCLE: {}", by_frames.prompt_text());
let mut at_once = session(false);
at_once.cmdline(&format!("circle 0,0 {expr}")).unwrap();
assert_eq!(radii(&by_frames), radii(&at_once));
assert_eq!(radii(&by_frames), [5.0]);
}
/// The allowance holds across frames too: an endless expression ends where it does without them,
/// with the same message, and takes its command with it.
#[test]
fn frames_do_not_lengthen_the_allowance() {
let mut s = session(true);
s.cmdline(&format!("circle 0,0 (progn {ENDLESS} 5)")).unwrap();
assert!(frames_to_the_end(&mut s) > 1);
let mut at_once = session(false);
at_once.cmdline(&format!("circle 0,0 (progn {ENDLESS} 5)")).unwrap();
assert!(stopped_by_allowance(&s).is_some(), "{:?}", s.log);
assert_eq!(stopped_by_allowance(&s), stopped_by_allowance(&at_once));
assert_eq!(counted(&s), counted(&at_once));
assert!(s.running.is_none() && radii(&s).is_empty());
}
/// What is typed while the frames work out a value comes after that value, as it did when the
/// prompt took nothing until the expression ended: LINE's second point is the expression's and the
/// typed point is its third.
#[test]
fn an_input_during_the_expression_comes_after_its_value() {
let rounds = (counted_to_the_allowance() / 4.0) as i64;
let mut s = session(true);
s.cmdline("line 0,0").unwrap();
s.cmdline(&format!("(progn (setq i 0) (while (< i {rounds}) (setq i (1+ i))) (list 5 5))")).unwrap();
assert!(s.lisp_busy(), "the expression waits for the next frame");
s.cmdline("10,0").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let ends: Vec<(Vec2, Vec2)> =
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None }).collect();
assert_eq!(ends, [(Vec2::new(0.0, 0.0), Vec2::new(5.0, 5.0)), (Vec2::new(5.0, 5.0), Vec2::new(10.0, 0.0))]);
}
/// A script's line is answered before its next line is read, in a host with frames too: nothing
/// would draw a frame inside the script.
#[test]
fn a_script_gets_the_value_before_its_next_line() {
let rounds = (counted_to_the_allowance() / 4.0) as i64;
let mut s = session(true);
s.script(&format!("circle 0,0 (progn (setq i 0) (while (< i {rounds}) (setq i (1+ i))) 5)\ncircle 0,0 2\n")).unwrap();
assert_eq!(radii(&s), [5.0, 2.0]);
}
/// An expression that takes several frames to work out `value`.
pub(super) fn slow(value: &str) -> String {
let rounds = (counted_to_the_allowance() / 4.0) as i64;
format!("(progn (setq i 0) (while (< i {rounds}) (setq i (1+ i))) {value})")
}
/// The ends of the drawing's lines, in draw order.
fn lines(s: &Session) -> Vec<(Vec2, Vec2)> {
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None }).collect()
}
/// A session with one circle, its own undo step, drawn before anything else.
fn session_with_a_circle(frames: bool) -> Session {
let mut s = session(frames);
s.cmdline("circle 50,50 1").unwrap();
s
}
/// The value of a routine that ended in an earlier frame is not the answer of an expression the
/// frames are still working out: the prompt gets that expression's own value, once.
#[test]
fn a_deferred_answer_is_not_an_earlier_routines_value() {
let mut s = session(true);
s.cmdline(&slow("(list 99 99)")).unwrap();
assert!(frames_to_the_end(&mut s) > 1, "the routine at Command: ended in a later frame");
s.cmdline("line 0,0").unwrap();
s.cmdline(&slow("(list 5 5)")).unwrap();
assert!(s.lisp_busy(), "the expression waits for the next frame: {:?}", lines(&s));
assert!(lines(&s).is_empty(), "nothing has answered the prompt yet");
frames_to_the_end(&mut s);
s.cmdline("").unwrap();
assert_eq!(lines(&s), [(Vec2::new(0.0, 0.0), Vec2::new(5.0, 5.0))]);
}
/// A routine that goes on in later frames has no value yet: the call that started it returns
/// none, whatever an earlier routine left.
#[test]
fn a_routine_that_goes_on_returns_no_earlier_value() {
let mut s = session(true);
s.cmdline(&slow("(list 99 99)")).unwrap();
frames_to_the_end(&mut s);
let started = s.lisp_eval(&slow("7"), false, false, Vec::new()).unwrap();
assert!(s.lisp_busy(), "the routine waits for the next frame");
assert!(started.is_none(), "{started:?}");
}
/// Esc in an expression the frames are working out ends its command as Esc at the prompt does:
/// what the command drew stays, as one undo step of its own.
#[test]
fn esc_in_an_expression_keeps_the_commands_undo_step() {
let mut s = session_with_a_circle(true);
s.cmdline("line 0,0 5,5").unwrap();
s.cmdline(&format!("(progn {ENDLESS} (list 9 9))")).unwrap();
assert!(s.lisp_busy(), "the expression waits for the next frame");
s.cancel();
assert!(s.running.is_none() && !s.lisp_running(), "{}", s.prompt_text());
let mut plain = session_with_a_circle(true);
plain.cmdline("line 0,0 5,5").unwrap();
plain.cancel();
assert_eq!(lines(&s), lines(&plain), "Esc keeps the segment");
for step in ["the segment", "the circle"] {
assert_eq!(s.undo().unwrap(), plain.undo().unwrap(), "U takes back {step}");
assert_eq!((lines(&s), radii(&s)), (lines(&plain), radii(&plain)), "U takes back {step}");
}
assert!(lines(&s).is_empty() && radii(&s).is_empty());
}
/// The same when the expression was typed at the prompt of a transparent command inside LINE:
/// Esc ends both, and LINE's segment is still LINE's undo step.
#[test]
fn esc_in_an_expression_at_a_transparent_prompt_keeps_the_outer_commands_undo_step() {
let mut s = session_with_a_circle(true);
s.cmdline("line 0,0 5,5").unwrap();
s.cmdline("'zoom").unwrap();
assert!(s.suspended.is_some(), "ZOOM runs inside LINE: {}", s.prompt_text());
s.cmdline(&format!("(progn {ENDLESS} 2)")).unwrap();
assert!(s.lisp_busy(), "the expression waits for the next frame: {}", s.prompt_text());
s.cancel();
assert!(s.running.is_none() && s.suspended.is_none() && !s.lisp_running(), "{}", s.prompt_text());
assert_eq!(lines(&s).len(), 1, "Esc keeps the segment");
s.undo().unwrap();
assert!(lines(&s).is_empty(), "U takes the segment back");
assert_eq!(radii(&s), [1.0], "and nothing before it");
}
/// An expression that fails ends its command, with frames (found out when the next input waits
/// for it) and without: what the command drew is still its own undo step.
#[test]
fn a_failed_expression_keeps_the_commands_undo_step() {
for frames in [false, true] {
let mut s = session_with_a_circle(frames);
s.cmdline("line 0,0 5,5").unwrap();
s.cmdline(&slow("(car 1)")).unwrap();
assert_eq!(s.lisp_busy(), frames);
if frames {
s.input(Input::Point(Vec2::new(9.0, 9.0))).unwrap();
}
assert!(s.running.is_none() && !s.lisp_running(), "frames {frames}: the failed expression ended LINE: {}", s.prompt_text());
assert_eq!(lines(&s).len(), 1, "frames {frames}: the segment stays");
s.undo().unwrap();
assert!(lines(&s).is_empty(), "frames {frames}: U takes the segment back");
assert_eq!(radii(&s), [1.0], "frames {frames}: and nothing before it");
}
}
/// A value the frames worked out leaves the command one undo step, as a value worked out at once
/// does: U takes back every segment of the LINE.
#[test]
fn a_command_answered_over_frames_is_one_undo_step() {
for frames in [false, true] {
let mut s = session_with_a_circle(frames);
s.cmdline("line 0,0 5,5").unwrap();
s.cmdline(&slow("(list 9 9)")).unwrap();
if frames {
assert!(frames_to_the_end(&mut s) > 1);
}
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s).len(), 2, "frames {frames}");
s.undo().unwrap();
assert!(lines(&s).is_empty(), "frames {frames}: one U takes back both segments");
assert_eq!(radii(&s), [1.0], "frames {frames}: and nothing before them");
}
}
/// A session with one circle where CIRCLE at 0,0 was given the expression `value` as its radius:
/// with frames the expression is still being worked out, without them it has answered.
fn circle_given(frames: bool, value: &str) -> Session {
let mut s = session_with_a_circle(frames);
s.cmdline("circle 0,0").unwrap();
s.cmdline(&slow(value)).unwrap();
assert_eq!(s.lisp_busy(), frames, "only frames leave the expression waiting");
s
}
/// A session with one circle where LINE, one segment drawn, was given the expression `value` as
/// its next point: with frames the expression is still being worked out.
fn line_given(frames: bool, value: &str) -> Session {
let mut s = session_with_a_circle(frames);
s.cmdline("line 0,0 5,5").unwrap();
s.cmdline(&slow(value)).unwrap();
assert_eq!(s.lisp_busy(), frames, "only frames leave the expression waiting");
s
}
/// The name of the command that waits for input.
fn running(s: &Session) -> Option<&str> {
s.running.as_ref().map(|r| r.id.as_str())
}
/// A table pasted from the clipboard starts its command after the value the frames are working
/// out has answered its prompt, as a command typed meanwhile does: a value that ends the waiting
/// command ends it, and one that leaves it running is in the drawing before that command is
/// cancelled for the paste.
#[test]
fn a_pasted_table_comes_after_a_pending_expressions_value() {
for frames in [false, true] {
let mut s = circle_given(frames, "5");
s.start_paste_table("a\tb\n1\t2", None).unwrap();
assert_eq!(radii(&s), [1.0, 5.0], "frames {frames}: the radius ended CIRCLE first");
assert_eq!(running(&s), Some("pastetable"), "frames {frames}");
let mut s = line_given(frames, "(list 9 9)");
s.start_paste_table("a\tb\n1\t2", None).unwrap();
assert_eq!(running(&s), Some("pastetable"), "frames {frames}");
assert!(!s.lisp_running(), "frames {frames}: nothing of the expression is left");
let (a, b, c) = (Vec2::new(0.0, 0.0), Vec2::new(5.0, 5.0), Vec2::new(9.0, 9.0));
assert_eq!(lines(&s), [(a, b), (b, c)], "frames {frames}: the point was LINE's before the paste cancelled it");
s.cancel();
s.undo().unwrap();
assert!(lines(&s).is_empty(), "frames {frames}: both segments are LINE's one undo step");
assert_eq!(radii(&s), [1.0], "frames {frames}: and nothing before them");
}
}
/// An expression that fails while a pasted table waits behind it ends its command as it does
/// without frames, and the paste starts.
#[test]
fn a_pasted_table_comes_after_a_pending_expression_that_fails() {
for frames in [false, true] {
let mut s = line_given(frames, "(car 1)");
s.start_paste_table("a\tb\n1\t2", None).unwrap();
assert_eq!(running(&s), Some("pastetable"), "frames {frames}");
assert!(!s.lisp_running(), "frames {frames}");
assert!(s.log.iter().any(|l| l.starts_with("; error: bad argument")), "frames {frames}: the failure is reported as it is: {:?}", s.log);
assert_eq!(lines(&s).len(), 1, "frames {frames}");
}
}
/// A click on a grip starts its edit after the pending value has answered its prompt.
#[test]
fn a_grip_edit_comes_after_a_pending_expressions_value() {
for frames in [false, true] {
let mut s = circle_given(frames, "5");
let first = s.doc().unwrap().model.iter().next().unwrap().handle;
s.start_grip_edit(&[(first, 0)]).unwrap();
assert_eq!(radii(&s), [1.0, 5.0], "frames {frames}: the radius ended CIRCLE first");
assert_eq!(running(&s), Some("grip"), "frames {frames}");
}
}
/// A programmatic undo or redo ends the running command first, and the command a pending value
/// ends has ended with that value: U takes back that command, not the step before it, and REDO
/// finds what it finds without frames.
#[test]
fn a_programmatic_undo_comes_after_a_pending_expressions_value() {
for frames in [false, true] {
let mut s = circle_given(frames, "5");
s.execute("u", &serde_json::json!({})).unwrap();
assert_eq!(radii(&s), [1.0], "frames {frames}: U took back the CIRCLE the value ended");
assert!(!s.lisp_running() && s.running.is_none(), "frames {frames}");
}
let redone = [false, true].map(|frames| {
let mut s = session_with_a_circle(frames);
s.cmdline("circle 0,0 2").unwrap();
s.execute("u", &serde_json::json!({})).unwrap();
s.cmdline("circle 0,0").unwrap();
s.cmdline(&slow("5")).unwrap();
s.execute("redo", &serde_json::json!({})).unwrap();
radii(&s)
});
assert_eq!(redone[1], redone[0], "REDO after a value worked out over frames, and at once");
assert!(redone[0].contains(&5.0), "{redone:?}");
}
/// An object picked from the selection-cycling list while the frames work out the value that
/// ends the command is picked with no command running, as it is without frames: it is selected.
#[test]
fn a_cycled_pick_comes_after_a_pending_expressions_value() {
for frames in [false, true] {
let mut s = circle_given(frames, "5");
let first = s.doc().unwrap().model.iter().next().unwrap().handle;
s.pick_cycled(first, false).unwrap();
assert_eq!(radii(&s), [1.0, 5.0], "frames {frames}");
assert_eq!(s.selection(), [first], "frames {frames}: the pick selected the object");
}
}
/// A line typed while the frames work out the value before a free-text prompt is that prompt's
/// text, spaces included, as it is when the value was worked out at once.
#[test]
fn a_line_typed_during_the_expression_is_the_text_of_the_prompt_after_it() {
for frames in [false, true] {
let mut s = session(frames);
s.cmdline("text 0,0 2.5").unwrap();
s.cmdline(&slow("0")).unwrap();
assert_eq!(s.lisp_busy(), frames);
s.cmdline("two words").unwrap();
s.cmdline("").unwrap();
let texts: Vec<String> =
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.value.clone()) } else { None }).collect();
assert_eq!(texts, ["two words"], "frames {frames}: {}", s.prompt_text());
}
}
/// Reading the drawing through `execute`, as panels do while they are open, is no input: the
/// expression goes on waiting for its frames, and Esc still stops it.
#[test]
fn a_read_through_execute_leaves_the_expression_to_its_frames() {
let mut s = session_with_a_circle(true);
s.cmdline("circle 0,0").unwrap();
s.cmdline(&format!("(progn {ENDLESS} 5)")).unwrap();
s.execute("drawing.inspect", &serde_json::json!({})).unwrap();
assert!(s.lisp_busy(), "the read did not run the expression to its allowance");
assert_eq!(stopped_by_allowance(&s), None);
s.cancel();
assert!(!s.lisp_running() && s.running.is_none());
assert_eq!(radii(&s), [1.0]);
}
/// The centres of the drawing's circles.
fn centres(s: &Session) -> Vec<Vec2> {
let circle = |k: &EntityKind| if let EntityKind::Circle(c) = k { Some(c.center.xy()) } else { None };
s.doc().unwrap().model.iter().filter_map(|e| circle(&e.kind)).collect()
}
/// A press-and-drag selection window started while the frames work out a point for ERASE's
/// "Select objects" comes after that point, as it does without frames: the drag's two corners
/// make the window, so the circle inside it is erased and the one between the expression's
/// point and the drag's first corner stays.
#[test]
fn a_dragged_window_comes_after_a_pending_expressions_point() {
let (kept, inside) = (Vec2::new(5.0, 5.0), Vec2::new(15.0, 15.0));
for frames in [false, true] {
let mut s = session(frames);
s.settings.pickdrag = true;
s.cmdline("circle 5,5 1").unwrap();
s.cmdline("circle 15,15 1").unwrap();
s.cmdline("erase").unwrap();
s.cmdline(&slow("(list 0 0)")).unwrap();
assert_eq!(s.lisp_busy(), frames, "only frames leave the expression waiting");
assert!(s.begin_window(Vec2::new(10.0, 10.0)), "frames {frames}: the drag opened a window");
assert!(!s.lisp_running(), "frames {frames}: nothing of the expression is left");
s.input(Input::Point(Vec2::new(20.0, 20.0))).unwrap();
assert!(s.pending_window.is_none(), "frames {frames}: the drag's end closed its window");
s.input(Input::Enter).unwrap();
assert!(s.running.is_none(), "frames {frames}: {}", s.prompt_text());
assert_eq!(centres(&s), [kept], "frames {frames}: only the circle at {inside:?} was in the window");
}
}
@@ -1,202 +0,0 @@
//! `getangle` and `getorient` answered from the `lisp` command's `inputs` return radians (#3398):
//! an input is read as the same answer at the prompt, a number as that number typed, so the
//! result works in `polar` and `cos`.
use std::f64::consts::{FRAC_PI_2, FRAC_PI_4, PI};
use cadcraft_engine::Session;
use serde_json::{Value, json};
/// How far two numbers may differ and still be the same angle or length.
const TOL: f64 = 1e-9;
/// The `lisp` command's result for `code` answered with `inputs`.
fn run(s: &mut Session, code: &str, inputs: Value) -> Value {
s.execute("lisp", &json!({ "code": code, "inputs": inputs })).unwrap()
}
/// The printed value of `code` answered with `inputs`.
fn value(s: &mut Session, code: &str, inputs: Value) -> String {
let r = run(s, code, inputs);
r["value"].as_str().unwrap_or_else(|| panic!("{code}: {r}")).to_string()
}
/// How far the number `code` gives is from `want`. LISP takes the difference, at full precision,
/// since a printed real keeps six digits.
fn off(s: &mut Session, code: &str, inputs: Value, want: f64) -> f64 {
let text = value(s, &format!("(- {code} {want:?})"), inputs);
text.parse::<f64>().unwrap_or_else(|_| panic!("{code}: {text}")).abs()
}
/// A number given as an input is read as that number typed: degrees by default, returned in
/// radians, as a whole number, a real and a string.
#[test]
fn a_number_given_to_getangle_is_degrees_typed_and_comes_back_in_radians() {
let mut s = Session::new();
// The report's case: 45 came back as 45.
assert!(off(&mut s, "(getangle '(0 0) \"Angle: \")", json!([45]), FRAC_PI_4) < TOL);
assert!(off(&mut s, "(getangle)", json!([22.5]), FRAC_PI_4 / 2.0) < TOL);
// The same answer as text came back as the string.
assert!(off(&mut s, "(getangle '(0 0) \"Angle: \")", json!(["45"]), FRAC_PI_4) < TOL);
}
/// The angle `getangle` returns can go straight to `polar`: 10 units along a typed 45 lands on
/// the 45 degree point.
#[test]
fn polar_takes_the_angle_getangle_returns() {
let mut s = Session::new();
let (x, y) = (10.0 * FRAC_PI_4.cos(), 10.0 * FRAC_PI_4.sin());
let code = format!("(distance (polar '(0 0) (getangle '(0 0) \"Angle: \") 10) (list {x:?} {y:?}))");
assert!(off(&mut s, &code, json!([45]), 0.0) < TOL, "10 units along 45 degrees");
}
/// Points given as inputs are points picked: two of them, or the base point and one, give the
/// angle of their line, the next call keeps its own input, and a lone first point gives nil.
#[test]
fn points_given_to_getangle_give_the_angle_of_their_line() {
let mut s = Session::new();
// Two points, without a base point.
assert!(off(&mut s, "(getangle)", json!([[1, 1], [2, 3]]), 2f64.atan2(1.0)) < TOL);
// The base point and one point.
assert!(off(&mut s, "(getangle '(1 1))", json!([[1, 2]]), FRAC_PI_2) < TOL);
// The call after it still gets its own answer.
assert_eq!(value(&mut s, "(list (equal (getangle) (/ pi 4) 1e-9) (getreal))", json!([[0, 0], [5, 5], 2.5])), "(T 2.5)");
// A first point with no second to follow: no angle.
assert_eq!(value(&mut s, "(getangle)", json!([[1, 1]])), "nil");
}
/// A null input is Enter: nil from both functions, and it answers one call only.
#[test]
fn enter_given_to_getangle_is_nil() {
let mut s = Session::new();
assert_eq!(value(&mut s, "(getangle '(0 0) \"Angle: \")", json!([null])), "nil");
assert_eq!(value(&mut s, "(getorient)", json!([null])), "nil");
// Enter answers one call only.
assert_eq!(value(&mut s, "(list (getangle) (equal (getangle) (/ pi 6) 1e-9))", json!([null, 30])), "(nil T)");
}
/// Text given as an input takes the unit forms the command line takes: radians, grads, degrees
/// and degrees with minutes.
#[test]
fn text_given_to_getangle_takes_the_unit_forms_the_command_line_takes() {
let mut s = Session::new();
for (text, want) in [("0.5r", 0.5), ("50g", FRAC_PI_4), ("45d", FRAC_PI_4), ("30d30'", 30.5f64.to_radians())] {
assert!(off(&mut s, "(getangle)", json!([text]), want) < TOL, "{text}");
}
}
/// A bare number is read in the drawing's angular units (AUNITS): radians and grads, while a
/// form that names its unit keeps it.
#[test]
fn a_number_given_to_getangle_is_read_in_aunits() {
let mut s = Session::new();
// Radians.
assert!(off(&mut s, "(progn (setvar \"AUNITS\" 3) (getangle))", json!([0.5]), 0.5) < TOL);
assert!(off(&mut s, "(getorient)", json!([0.5]), 0.5) < TOL);
// Grads.
assert!(off(&mut s, "(progn (setvar \"AUNITS\" 2) (getangle))", json!([50]), FRAC_PI_4) < TOL);
// A unit typed with the number still wins.
assert!(off(&mut s, "(getangle)", json!(["45d"]), FRAC_PI_4) < TOL);
}
/// With the zero direction turned north (ANGBASE), `getangle` measures from it and `getorient`
/// from east, for a typed angle and for a picked point.
#[test]
fn getorient_returns_radians_from_east_whatever_angbase_is() {
let mut s = Session::new();
assert!(off(&mut s, "(getorient '(0 0) \"Angle: \")", json!([45]), FRAC_PI_4) < TOL);
assert!(off(&mut s, "(getorient '(0 0))", json!([[-1, 0]]), PI) < TOL);
// ANGBASE north: 45 typed is 45 degrees from north. `getangle` returns the angle from
// ANGBASE, `getorient` the direction from east.
assert!(off(&mut s, "(setvar \"ANGBASE\" (/ pi 2))", json!([]), FRAC_PI_2) < TOL);
assert!(off(&mut s, "(getangle)", json!([45]), FRAC_PI_4) < TOL);
assert!(off(&mut s, "(getorient)", json!([45]), 3.0 * FRAC_PI_4) < TOL);
// A point west of the base: 90 degrees from north, 180 from east.
assert!(off(&mut s, "(getangle '(0 0))", json!([[-1, 0]]), FRAC_PI_2) < TOL);
assert!(off(&mut s, "(getorient '(0 0))", json!([[-1, 0]]), PI) < TOL);
}
/// An input the prompt would refuse is reported in the output and the next input is taken, as a
/// prompt asks again; `initget` bits and keywords apply.
#[test]
fn an_answer_getangle_refuses_is_reported_and_the_next_one_taken() {
let mut s = Session::new();
let r = run(&mut s, "(equal (getangle) (/ pi 6) 1e-9)", json!(["north-ish", 30]));
assert_eq!(r["value"], "T", "{r}");
let output = r["output"].as_array().unwrap();
assert!(output.iter().any(|l| l.as_str().is_some_and(|l| l.contains("angle"))), "the refusal is in the output: {r}");
// `initget` still applies: zero refused, then a keyword.
let code = "(progn (initget 2 \"Reference\") (getangle))";
assert_eq!(value(&mut s, code, json!([0, "r"])), "\"Reference\"");
}
/// Empty or blank text given as an input is Enter, as an empty line is at the prompt: nil, and
/// the next call keeps its own input. With `initget` bit 1 Enter is refused, and the next input
/// is the answer.
#[test]
fn empty_text_given_to_getangle_is_enter() {
let mut s = Session::new();
assert_eq!(value(&mut s, "(list (getangle) (getreal))", json!(["", 30])), "(nil 30)");
assert_eq!(value(&mut s, "(list (getorient '(0 0)) (getreal))", json!([" ", 30])), "(nil 30)");
// Enter is not allowed: the empty text is refused as Enter is, and 30 answers the call.
let r = run(&mut s, "(progn (initget 1) (list (equal (getangle) (/ pi 6) 1e-9) (getreal)))", json!(["", 30, 2.5]));
assert_eq!(r["value"], "(T 2.5)", "{r}");
let null = run(&mut s, "(progn (initget 1) (list (equal (getangle) (/ pi 6) 1e-9) (getreal)))", json!([null, 30, 2.5]));
assert_eq!(r["output"], null["output"], "refused with the words Enter is refused with");
}
/// Coordinates given as text are a point, as they are typed at the prompt: with the base point
/// they give the angle of the line, two of them do without one, and the next call keeps its own
/// input.
#[test]
fn coordinate_text_given_to_getangle_is_a_point() {
let mut s = Session::new();
assert_eq!(value(&mut s, "(list (equal (getangle '(0 0)) (/ pi 4) 1e-9) (getreal))", json!(["1,1", 2.5])), "(T 2.5)");
assert!(off(&mut s, "(getangle)", json!(["1,1", "2,3"]), 2f64.atan2(1.0)) < TOL);
assert!(off(&mut s, "(getorient '(1 1))", json!(["1,2"]), FRAC_PI_2) < TOL);
// The polar and relative forms are points as well (the last point is the origin here).
assert!(off(&mut s, "(getangle '(0 0))", json!(["1<45"]), FRAC_PI_4) < TOL);
assert!(off(&mut s, "(getangle '(0 0))", json!(["@1,1"]), FRAC_PI_4) < TOL);
// A keyword that also reads as a point (`@`, the last point) stays the keyword, as at the prompt.
assert_eq!(value(&mut s, "(progn (initget \"@\") (getangle '(1 1)))", json!(["@"])), "\"@\"");
}
/// The angle `text` gives when typed at the prompt of `call`, and how far the angle it gives as
/// an input is from that.
fn typed_and_given(s: &mut Session, call: &str, text: &str) -> (String, f64) {
s.cmdline(&format!("(setq typed {call})")).unwrap();
s.cmdline(text).unwrap();
let typed = value(s, "typed", json!([]));
let apart = value(s, &format!("(abs (- {call} typed))"), json!([text]));
let apart = apart.parse().unwrap_or_else(|_| panic!("{call} {text}: {apart} (typed: {typed})"));
(typed, apart)
}
/// Every form of point and angle text gives, as an input, the angle it gives typed at the
/// prompt: absolute, relative to the last point, polar, world coordinates, bare and unit-bearing
/// angles; also with the zero direction north and in a moved, turned UCS.
#[test]
fn text_given_to_getangle_is_read_as_the_same_text_typed_at_the_prompt() {
const TEXTS: [&str; 12] = ["1,1", "3,4,5", "@1,1", "@2<30", "@", "1<45", "2<<30", "#3,4", "*1,2", "*@1,2", "45", "0.5r"];
let mut s = Session::new();
s.last_point = cadcraft_geom::Vec2::new(5.0, 2.0);
for text in TEXTS {
for call in ["(getangle '(1 0))", "(getorient '(1 0))"] {
let (typed, apart) = typed_and_given(&mut s, call, text);
assert!(apart < TOL, "{call} {text}: typed {typed}, {apart} apart");
}
}
// The relative forms count from the last point, not the origin.
let (typed, _) = typed_and_given(&mut s, "(getangle '(5 2))", "@1,1");
assert_eq!(typed, value(&mut s, "(/ pi 4)", json!([])));
// North is zero, and the UCS sits at (100, 50) turned a quarter turn.
value(&mut s, "(setvar \"ANGBASE\" (/ pi 2))", json!([]));
s.execute("ucs", &json!({"option": "origin", "origin": [100, 50]})).unwrap();
s.execute("ucs", &json!({"option": "z", "angle": 90})).unwrap();
for text in TEXTS {
for call in ["(getangle '(1 0))", "(getorient '(1 0))"] {
let (typed, apart) = typed_and_given(&mut s, call, text);
assert!(apart < TOL, "ANGBASE and UCS, {call} {text}: typed {typed}, {apart} apart");
}
}
}
-81
View File
@@ -1,81 +0,0 @@
//! LISP `textbox` (#3676): the smallest box around a TEXT as drawn, relative to its insertion
//! point and unrotated.
use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{EntityCodec, set_entity_codec};
use cadcraft_engine::doc::Space;
use serde_json::json;
fn session() -> Session {
set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups });
Session::new()
}
/// The value of `code` as LISP prints it.
fn lisp(s: &mut Session, code: &str) -> String {
let r = s.execute("lisp", &json!({ "code": code })).unwrap();
r["value"].as_str().unwrap().to_string()
}
/// `(textbox …)` as [min x, min y, max x, max y]; None for nil.
fn textbox(s: &mut Session, elist: &str) -> Option<[f64; 4]> {
let v = lisp(s, &format!("(textbox {elist})"));
if v == "nil" {
return None;
}
let n: Vec<f64> = v.replace(['(', ')'], " ").split_whitespace().map(|x| x.parse().unwrap()).collect();
assert_eq!(n.len(), 6, "{v}");
Some([n[0], n[1], n[3], n[4]])
}
fn width(b: [f64; 4]) -> f64 {
b[2] - b[0]
}
#[test]
fn textbox_measures_text_as_drawn() {
let mut s = session();
let short = textbox(&mut s, "'((1 . \"AB\"))").expect("a list with only the string");
let long = textbox(&mut s, "'((1 . \"ABCDEFGH\"))").unwrap();
assert!(width(long) > width(short), "{long:?} {short:?}");
assert!(short[0] < short[2] && short[1] < short[3], "{short:?}");
// Height 40 against the default TEXTSIZE: every edge scales by their ratio.
let size: f64 = lisp(&mut s, "(getvar \"TEXTSIZE\")").parse().unwrap();
let tall = textbox(&mut s, "'((1 . \"AB\") (40 . 40.0))").unwrap();
for i in 0..4 {
assert!((tall[i] - short[i] * 40.0 / size).abs() <= 1e-6 * 40.0, "{tall:?} {short:?}");
}
let wide = textbox(&mut s, "'((1 . \"AB\") (41 . 2.0))").unwrap();
assert!((width(wide) - 2.0 * width(short)).abs() <= 1e-9 + 1e-6 * width(short), "{wide:?} {short:?}");
// The box is the drawn text's: letters that reach below the baseline lower its first corner,
// which capitals leave at about the insertion point.
let low = textbox(&mut s, "'((1 . \"gyp\"))").unwrap();
assert!(low[1] < short[1] && short[1] > -0.05 * size, "{low:?} {short:?}");
// A string that draws nothing still has its advance and height.
let blank = textbox(&mut s, "'((1 . \" \"))").expect("spaces");
assert!(blank[0] == 0.0 && blank[1] == 0.0 && blank[2] > 0.0 && blank[3] > 0.0, "{blank:?}");
// Not a text: nil.
assert_eq!(textbox(&mut s, "'((0 . \"LINE\") (10 0.0 0.0 0.0) (11 5.0 5.0 0.0) (1 . \"x\"))"), None);
assert_eq!(textbox(&mut s, "'((0 . \"TEXT\") (40 . 1.0))"), None, "no string");
assert_eq!(textbox(&mut s, "nil"), None);
// The box holds what the renderer draws for the text at the origin, control codes included.
lisp(&mut s, "(entmake '((0 . \"TEXT\") (10 0.0 0.0 0.0) (40 . 2.5) (51 . 0.3) (1 . \"%%uAgy%%d jQ\")))");
let drawn = textbox(&mut s, "(entget (entlast))").unwrap();
let list = cadcraft_engine::render::build(s.doc().unwrap(), &Space::Model, &Default::default());
let ink: Vec<_> = list.verts.iter().chain(&list.tris).collect();
assert!(!ink.is_empty());
let tol = 1e-6 * 2.5;
for p in ink {
assert!(p.x >= drawn[0] - tol && p.x <= drawn[2] + tol && p.y >= drawn[1] - tol && p.y <= drawn[3] + tol, "{p:?} outside {drawn:?}");
}
// Insertion point and rotation are not applied.
lisp(&mut s, "(entmake '((0 . \"TEXT\") (10 100.0 50.0 0.0) (40 . 2.5) (50 . 0.7) (51 . 0.3) (1 . \"%%uAgy%%d jQ\")))");
let moved = textbox(&mut s, "(entget (entlast))").unwrap();
for i in 0..4 {
assert!((moved[i] - drawn[i]).abs() <= tol, "{moved:?} {drawn:?}");
}
}
+4 -5
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;
@@ -45,7 +46,6 @@ mod dash_block;
mod dash_units;
mod data_extraction;
mod dim_baseline_spacing;
mod dim_block_text_layer_pick;
mod dim_chain;
mod dim_commands;
mod dim_explode_text;
@@ -104,11 +104,9 @@ mod layout_prompts;
mod leader_command;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod leader_text_scale;
mod lisp_answer_by_frames;
mod legacy_sysvars;
mod lisp_corpus;
mod lisp_findfile;
mod lisp_getangle_inputs;
mod lisp_textbox;
mod lisp_undo_in_routine;
mod malformed_handles;
mod matchprop;
@@ -202,6 +200,8 @@ mod temp_tracking;
mod text_commands;
mod text_generation_flags;
mod text_left_justify;
mod text_style_creation;
mod textstyle_cli;
mod tolerance;
mod transparent;
mod trim_closed_polyline;
@@ -219,7 +219,6 @@ mod viewport_frozen_selection;
mod viewport_ucs_copy;
mod vplayer_prompts;
mod vports;
mod window_rotated_text;
mod wipeout_grips;
mod xclip;
mod xdata_api;
-32
View File
@@ -136,35 +136,3 @@ fn matchprop_skips_locked_layers() {
assert_eq!(r["changed"], 0);
assert_eq!(props(&s, a).0, "L");
}
/// MATCHPROP between leaders copies the source's dimension style and its own style overrides
/// (the leader's DSTYLE data), as it does between dimensions (#3721).
#[test]
fn matchprop_copies_a_leaders_style_overrides() {
use cadcraft_engine::doc::{Common, Leader, Space};
use cadcraft_engine::geom::Vec3;
let leader = |y: f64, overrides: serde_json::Value| {
EntityKind::Leader(Leader {
vertices: vec![Vec3::new(0.0, y, 0.0), Vec3::new(10.0, y, 0.0)],
arrow: true,
spline: false,
style: "Standard".into(),
overrides: overrides.as_object().cloned().unwrap_or_default(),
})
};
let overrides_of = |s: &Session, h: Handle| match &s.doc().unwrap().entity(h).unwrap().kind {
EntityKind::Leader(l) => l.overrides.clone(),
_ => panic!("a leader"),
};
let mut s = Session::new();
let d = s.doc_mut().unwrap();
d.add(&Space::Model, Common::default(), leader(0.0, json!({ "arrowSize": 1.5, "leaderArrowBlock": "_ArchTick" }))).unwrap();
d.add(&Space::Model, Common::default(), leader(5.0, json!({}))).unwrap();
let handles: Vec<Handle> = s.doc().unwrap().model.iter().map(|e| e.handle).collect();
let (src, dst) = (handles[0], handles[1]);
assert_ne!(overrides_of(&s, dst), overrides_of(&s, src));
let r = s.execute("matchprop", &json!({ "source": src.hex(), "targets": [dst.hex()] })).unwrap();
assert_eq!(r["changed"], 1);
assert_eq!(overrides_of(&s, dst), overrides_of(&s, src));
assert!(!overrides_of(&s, dst).is_empty());
}
@@ -104,32 +104,6 @@ fn distance_uses_model_units_for_two_snaps_in_the_same_viewport() {
assert_eq!(s.state().unwrap().is_dirty(), before, "inquiry must not edit the drawing");
}
/// The `Distance` line DIST printed.
fn distance_line(s: &Session) -> Option<&String> {
s.log.iter().find(|l| l.starts_with("Distance = "))
}
/// A point an expression typed at the prompt worked out over frames (#3666) is a typed point: a
/// snapped click that comes while the frames work it out does not lend it its viewport origin.
#[test]
fn a_snapped_click_does_not_lend_its_origin_to_a_pending_expressions_point() {
let expression = super::lisp_answer_by_frames::slow("(list 95 50)");
let measure = |frames: bool| {
let (d, _) = drawing();
let mut s = session(d);
s.lisp_by_frames(frames);
s.start("dist").unwrap();
s.cmdline(&expression).unwrap();
assert_eq!(s.lisp_busy(), frames, "the expression waits for the next frame");
s.input_snapped(pick(&s, Vec2::new(100.0, 50.0), mode::INT)).unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
distance_line(&s).cloned().expect("DIST measured")
};
let at_once = measure(false);
assert!(at_once.starts_with("Distance = 5.0000,"), "paper units from the typed point: {at_once}");
assert_eq!(measure(true), at_once);
}
#[test]
fn typed_and_programmatic_points_are_measured_in_paper_units() {
let (d, _) = drawing();
+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()),
@@ -0,0 +1,207 @@
//! New text follows its style as AutoCAD's does: a fixed-height style isn't asked for a height,
//! an annotative style is asked for the paper height, TEXT takes the style's width factor and
//! obliquing angle, the Style option picks the style, and Enter at the start point continues
//! below the last TEXT.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{EntityKind, HAlign, MText, Text, VAlign};
use serde_json::json;
fn lines(s: &mut Session, input: &[&str]) {
for l in input {
s.cmdline(l).unwrap_or_else(|e| panic!("{l:?}: {e:?}"));
}
}
fn texts(s: &Session) -> Vec<Text> {
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.clone()) } else { None }).collect()
}
fn mtexts(s: &Session) -> Vec<MText> {
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::MText(t) = &e.kind { Some(t.clone()) } else { None }).collect()
}
fn close(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-9
}
#[test]
fn a_fixed_height_style_is_not_asked_for_a_height() {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Fixed", "height": 2.5 })).unwrap();
s.cmdline("TEXT").unwrap();
assert!(s.log.iter().any(|l| l.contains("\"Fixed\"") && l.contains("Text height: 2.5000")), "{:?}", s.log);
s.cmdline("0,0").unwrap();
assert!(s.prompt_text().contains("Specify rotation angle of text"), "{}", s.prompt_text());
lines(&mut s, &["0", "Hello", ""]);
assert_eq!(texts(&s)[0].height, 2.5);
// TEXTSIZE isn't changed by a fixed height; JSON text takes the fixed height by default.
assert_eq!(s.doc().unwrap().header.f64("TEXTSIZE", 0.0), 0.2);
s.execute("text", &json!({ "at": [0, 10], "text": "Json" })).unwrap();
assert_eq!(texts(&s)[1].height, 2.5);
s.execute("text", &json!({ "at": [0, 20], "text": "Own", "height": 1 })).unwrap();
assert_eq!(texts(&s)[2].height, 1.0, "an explicit height is kept");
}
#[test]
fn new_text_takes_the_styles_width_factor_and_oblique_angle() {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Narrow", "widthFactor": 0.8, "oblique": 15 })).unwrap();
lines(&mut s, &["TEXT", "0,0", "1", "0", "Typed", ""]);
s.execute("text", &json!({ "at": [0, 5], "text": "Json" })).unwrap();
s.execute("style", &json!({ "name": "Plain", "current": false })).unwrap();
s.execute("text", &json!({ "at": [0, 10], "text": "Other", "style": "plain" })).unwrap();
let t = texts(&s);
for x in &t[..2] {
assert_eq!((x.style.as_str(), x.width_factor), ("Narrow", 0.8));
assert!(close(x.oblique.to_degrees(), 15.0));
}
assert_eq!((t[2].style.as_str(), t[2].width_factor, t[2].oblique), ("Plain", 1.0, 0.0));
// Changing the style afterwards leaves existing text as it is.
s.execute("style", &json!({ "name": "Narrow", "widthFactor": 1.5 })).unwrap();
assert_eq!(texts(&s)[0].width_factor, 0.8);
assert!(s.execute("text", &json!({ "at": [0, 0], "text": "x", "style": "Nope" })).is_err());
}
#[test]
fn an_annotative_style_is_asked_for_the_paper_height() {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Notes", "annotative": true })).unwrap();
lines(&mut s, &["TEXT", "0,0"]);
assert!(s.prompt_text().contains("Specify paper text height"), "{}", s.prompt_text());
lines(&mut s, &["0.125", "0", "Note", ""]);
let d = s.doc().unwrap();
let e = d.model.iter().find(|e| matches!(e.kind, EntityKind::Text(_))).unwrap();
assert!(cadcraft_engine::doc::is_annotative(e));
assert_eq!(texts(&s)[0].height, 0.125);
}
#[test]
fn the_style_option_makes_a_style_current() {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Title", "height": 5, "current": false })).unwrap();
lines(&mut s, &["TEXT", "S"]);
assert!(s.prompt_text().contains("Enter style name or [?] <Standard>"), "{}", s.prompt_text());
// ? lists the styles, then asks for the name again.
lines(&mut s, &["?", ""]);
assert!(s.log.iter().any(|l| l.contains("Style name: \"Title\"")), "{:?}", s.log);
let _ = s.cmdline("Nope");
assert!(s.log.iter().any(|l| l.contains("Cannot find text style \"Nope\".")), "{:?}", s.log);
assert!(s.prompt_text().contains("Enter style name"), "asked again: {}", s.prompt_text());
s.cmdline("title").unwrap();
assert_eq!(s.doc().unwrap().header.str("TEXTSTYLE", ""), "Title");
assert!(s.log.iter().any(|l| l.contains("Current text style: \"Title\" Text height: 5.0000")), "{:?}", s.log);
assert!(s.prompt_text().contains("Specify start point of text"), "{}", s.prompt_text());
// Title fixes the height: the next question is the rotation.
s.cmdline("0,0").unwrap();
assert!(s.prompt_text().contains("Specify rotation angle of text"), "{}", s.prompt_text());
lines(&mut s, &["0", "Big", ""]);
assert_eq!(texts(&s)[0].style, "Title");
assert_eq!(texts(&s)[0].height, 5.0);
}
#[test]
fn a_justification_that_is_no_option_is_asked_again() {
let mut s = Session::new();
lines(&mut s, &["TEXT", "J"]);
let _ = s.cmdline("X");
assert!(s.log.iter().any(|l| l.contains("Invalid option keyword.")), "{:?}", s.log);
assert!(s.prompt_text().contains("Enter an option"), "asked again: {}", s.prompt_text());
s.cmdline("MC").unwrap();
lines(&mut s, &["0,0", "2", "0", "Centered", ""]);
assert_eq!(texts(&s)[0].halign, cadcraft_engine::doc::HAlign::Center);
// Enter leaves the question, as the start point's prompt shows.
lines(&mut s, &["TEXT", "J", ""]);
assert!(s.prompt_text().contains("Specify start point of text"), "{}", s.prompt_text());
s.cancel();
}
#[test]
fn enter_at_the_start_point_continues_below_the_last_text() {
let mut s = Session::new();
lines(&mut s, &["TEXT", "J", "MC", "10,10", "2", "90", "First", ""]);
s.execute("style", &json!({ "name": "Other" })).unwrap();
lines(&mut s, &["TEXT", ""]);
assert!(s.prompt_text().contains("Enter text"), "no height or rotation asked: {}", s.prompt_text());
lines(&mut s, &["Second", "Third", ""]);
let t = texts(&s);
assert_eq!(t.len(), 3);
for (i, x) in t.iter().enumerate().skip(1) {
assert_eq!((x.height, x.halign, x.valign), (2.0, HAlign::Center, VAlign::Middle));
assert!(close(x.rotation.to_degrees(), 90.0));
assert_eq!(x.style, "Standard", "the continued text's style, not the current one");
// Rotated 90°: lines go to +X, one line spacing (5/3 of the height) apart.
let p = x.justify_point();
assert!(close(p.x, 10.0 + 2.0 * 5.0 / 3.0 * i as f64) && close(p.y, 10.0), "line {i}: {p:?}");
}
// With no text in the drawing, Enter ends the command.
let mut empty = Session::new();
lines(&mut empty, &["TEXT", ""]);
assert!(empty.running.is_none());
assert!(texts(&empty).is_empty());
}
#[test]
fn enter_at_the_start_point_does_not_continue_with_an_unusable_height() {
let mut s = Session::new();
lines(&mut s, &["TEXT", "10,10", "2", "0", "First", ""]);
assert_eq!(texts(&s).len(), 1);
// The last text's height and TEXTSIZE are both unusable: nothing spaces the next line.
{
let d = s.doc_mut().unwrap();
d.header.set_f64("TEXTSIZE", 0.0);
let handle = d.model.iter().next().expect("the first text").handle;
d.model.modify(handle, |e| {
if let EntityKind::Text(t) = &mut e.kind {
t.height = 0.0;
}
});
}
lines(&mut s, &["TEXT", ""]);
assert!(s.running.is_none(), "Enter ends the command: {}", s.prompt_text());
assert_eq!(texts(&s).len(), 1, "no text of height 0 was made");
}
#[test]
fn mtext_starts_with_a_fixed_style_height() {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Fixed", "height": 3 })).unwrap();
lines(&mut s, &["MTEXT", "0,0", "20,-10", "Para", ""]);
s.execute("mtext", &json!({ "at": [0, 20], "text": "Json" })).unwrap();
// The Style option takes a fixed style's height too.
s.execute("style", &json!({ "name": "Free" })).unwrap();
s.execute("style", &json!({ "name": "Tall", "height": 7, "current": false })).unwrap();
lines(&mut s, &["MTEXT", "0,40", "S", "Tall", "20,30", "Tall text", ""]);
let heights: Vec<f64> = mtexts(&s).iter().map(|m| m.height).collect();
assert_eq!(heights, [3.0, 3.0, 7.0]);
}
#[test]
fn hostile_text_input_never_panics() {
// A caught panic comes back as an internal error: refused input may fail, but never so.
let not_internal = |r: &Result<_, cadcraft_engine::EngineError>, what: &str| {
assert!(!matches!(r, Err(cadcraft_engine::EngineError::Internal(..))), "{what}: {:?}", r.as_ref().err());
};
let mut s = Session::new();
s.execute("style", &json!({ "name": "Weird", "height": 1e308, "widthFactor": 1e-300 })).unwrap();
for script in [
vec!["TEXT", "S", "?", &"*".repeat(50_000)],
vec!["TEXT", "S", &"x".repeat(100_000)],
vec!["TEXT", "0,0", "0", "x", ""],
vec!["TEXT", "", "", "", ""],
] {
for l in script {
not_internal(&s.cmdline(l).map(|_| ()), l);
}
s.cancel();
}
for p in [
json!({ "at": [0, 0], "text": "x", "style": 5 }),
json!({ "at": [0, 0], "text": "x", "height": f64::MAX }),
json!({ "at": [0, 0], "text": "x", "height": -1 }),
] {
for cmd in ["text", "mtext"] {
not_internal(&s.execute(cmd, &p).map(|_| ()), cmd);
}
}
}
+233
View File
@@ -0,0 +1,233 @@
//! -STYLE at the command line (AutoCAD's prompt order, so scripts written for AutoCAD run) and
//! `style.fonts`, the fonts the Text Style dialog offers.
use cadcraft_engine::Session;
use cadcraft_engine::doc::TextStyle;
use serde_json::json;
fn style(s: &Session, name: &str) -> TextStyle {
s.doc().unwrap().text_style(name).cloned().unwrap()
}
fn current(s: &Session) -> String {
s.doc().unwrap().header.str("TEXTSTYLE", "")
}
fn lines(s: &mut Session, input: &[&str]) {
for l in input {
s.cmdline(l).unwrap_or_else(|e| panic!("{l:?}: {e:?}"));
}
}
/// A font file with only a naming table (Windows English names), built here: no font file is
/// committed.
fn font_with_names(family: &str, style: &str) -> Vec<u8> {
let mut strings = Vec::new();
let mut recs = Vec::new();
for (id, s) in [(1u16, family), (2, style)] {
let bytes: Vec<u8> = s.encode_utf16().flat_map(u16::to_be_bytes).collect();
for v in [3u16, 1, 0x0409, id, bytes.len() as u16, strings.len() as u16] {
recs.extend_from_slice(&v.to_be_bytes());
}
strings.extend(bytes);
}
let mut name = Vec::new();
for v in [0u16, 2, (6 + recs.len()) as u16] {
name.extend_from_slice(&v.to_be_bytes());
}
name.extend(recs);
name.extend(strings);
let mut out = Vec::new();
out.extend_from_slice(&0x0001_0000u32.to_be_bytes());
for v in [1u16, 16, 0, 0] {
out.extend_from_slice(&v.to_be_bytes());
}
out.extend_from_slice(b"name");
out.extend_from_slice(&0u32.to_be_bytes());
out.extend_from_slice(&28u32.to_be_bytes());
out.extend_from_slice(&(name.len() as u32).to_be_bytes());
out.extend(name);
out
}
#[test]
fn style_fonts_lists_families_and_styles() {
cadcraft_fonts::ttf::register("cadcraft-style-test-bd.ttf", font_with_names("CADCraft Style Test", "Bold"));
cadcraft_fonts::ttf::register("cadcraft-style-test.ttf", font_with_names("CADCraft Style Test", "Regular"));
let mut s = Session::new();
let r = s.execute("style.fonts", &json!({})).unwrap();
let fonts = r["fonts"].as_array().unwrap();
assert_eq!(fonts[0]["file"], cadcraft_fonts::BUILTIN_FONT, "the built-in font first");
let ours: Vec<(&str, &str)> =
fonts.iter().filter(|f| f["family"] == "CADCraft Style Test").map(|f| (f["style"].as_str().unwrap(), f["file"].as_str().unwrap())).collect();
assert_eq!(ours, [("Regular", "cadcraft-style-test.ttf"), ("Bold", "cadcraft-style-test-bd.ttf")]);
// A style naming the file uses that face.
s.execute("style", &json!({ "name": "Heavy", "font": "cadcraft-style-test-bd.ttf" })).unwrap();
assert!(cadcraft_fonts::ttf::find(&style(&s, "Heavy").font).is_some());
}
#[test]
fn dash_style_asks_in_autocads_order() {
let mut s = Session::new();
s.cmdline("-STYLE").unwrap();
assert!(s.prompt_text().contains("Enter name of text style or [?] <Standard>"), "{}", s.prompt_text());
lines(&mut s, &["Notes", "romans.shx"]);
assert!(s.prompt_text().contains("Specify height of text or [Annotative]"), "{}", s.prompt_text());
lines(&mut s, &["0.25", "0.8", "15", "Y", "N"]);
// SHX fonts are asked about vertical text.
assert!(s.prompt_text().contains("Vertical?"), "{}", s.prompt_text());
s.cmdline("N").unwrap();
assert!(s.running.is_none());
let st = style(&s, "Notes");
assert_eq!((st.font.as_str(), st.height, st.width_factor), ("romans.shx", 0.25, 0.8));
assert!((st.oblique.to_degrees() - 15.0).abs() < 1e-9);
assert!(st.backwards && !st.upside_down && !st.vertical);
assert_eq!(current(&s), "Notes");
assert!(s.log.iter().any(|l| l.contains("\"Notes\" is now the current text style.")), "{:?}", s.log);
}
#[test]
fn enter_keeps_an_existing_styles_settings() {
let mut s = Session::new();
s.execute(
"style",
&json!({ "name": "Plan", "font": "CADCraft Stroke", "height": 2.5, "widthFactor": 0.9, "oblique": 10, "upsideDown": true, "current": false }),
)
.unwrap();
s.cmdline("-STYLE").unwrap();
s.cmdline("plan").unwrap();
assert!(s.log.iter().any(|l| l == "Existing style."), "{:?}", s.log);
// Font, height, width factor, obliquing angle, backwards, upside down: all Enter. A TrueType or
// stroke font isn't asked about vertical text.
lines(&mut s, &["", "", "", "", "", ""]);
assert!(s.running.is_none(), "{}", s.prompt_text());
let st = style(&s, "Plan");
assert_eq!((st.height, st.width_factor, st.upside_down), (2.5, 0.9, true));
assert!((st.oblique.to_degrees() - 10.0).abs() < 1e-9);
assert_eq!(current(&s), "Plan");
}
#[test]
fn annotative_styles_ask_for_the_paper_height() {
let mut s = Session::new();
lines(&mut s, &["-STYLE", "Anno", "", "A", "Y"]);
assert!(s.prompt_text().contains("Match text orientation to layout?"), "{}", s.prompt_text());
s.cmdline("N").unwrap();
assert!(s.prompt_text().contains("Specify paper text height"), "{}", s.prompt_text());
lines(&mut s, &["0.125", "", "", "", ""]);
assert!(s.running.is_none(), "{}", s.prompt_text());
let st = style(&s, "Anno");
assert!(st.annotative);
assert_eq!(st.height, 0.125);
// Enter at the question says yes, as its default shows; No asks for the height again.
lines(&mut s, &["-STYLE", "Plain", "", "A"]);
assert!(s.prompt_text().contains("<Yes>"), "{}", s.prompt_text());
s.cmdline("N").unwrap();
assert!(s.prompt_text().contains("Specify height of text or [Annotative]"), "{}", s.prompt_text());
lines(&mut s, &["0.2", "", "", "", ""]);
assert!(s.running.is_none(), "{}", s.prompt_text());
assert!(!style(&s, "Plain").annotative);
}
#[test]
fn a_new_style_keeps_the_current_styles_big_font() {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Asian", "font": "txt.shx", "bigFont": "bigfont.shx" })).unwrap();
// Name, font, height, width factor, obliquing angle, backwards, upside down, vertical.
lines(&mut s, &["-STYLE", "Copy", "", "", "", "", "", "", ""]);
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(style(&s, "Copy").big_font, "bigfont.shx");
}
#[test]
fn shx_font_answers_select_the_right_fonts_and_prompt() {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Existing", "font": "old.shx", "bigFont": "old-big.shx" })).unwrap();
lines(&mut s, &["-STYLE", "Existing", "romans,new-big.shx", "", "", "", "", ""]);
assert!(s.prompt_text().contains("Vertical?"), "{}", s.prompt_text());
s.cmdline("Y").unwrap();
let st = style(&s, "Existing");
assert_eq!((st.font.as_str(), st.big_font.as_str(), st.vertical), ("romans", "new-big.shx", true));
lines(&mut s, &["-STYLE", "Existing", ",other-big.shx", "", "", "", "", "", ""]);
let st = style(&s, "Existing");
assert_eq!((st.font.as_str(), st.big_font.as_str()), ("romans", "other-big.shx"));
lines(&mut s, &["-STYLE", "Existing", "romans,", "", "", "", "", "", ""]);
assert_eq!(style(&s, "Existing").big_font, "other-big.shx");
lines(&mut s, &["-STYLE", "Existing", "romans", "", "", "", "", "", ""]);
assert!(style(&s, "Existing").big_font.is_empty());
}
#[test]
fn extensionless_installed_outline_font_does_not_ask_for_vertical_text() {
cadcraft_fonts::ttf::register("cadcraft-outline-regression.ttf", font_with_names("CADCraft Outline Regression", "Regular"));
let mut s = Session::new();
lines(&mut s, &["-STYLE", "Outline", "cadcraft-outline-regression", "", "", "", "", ""]);
assert!(s.running.is_none(), "{}", s.prompt_text());
}
#[test]
fn bad_answers_ask_again() {
let mut s = Session::new();
let still = |s: &mut Session, answer: &str, prompt: &str| {
let _ = s.cmdline(answer);
assert!(s.prompt_text().contains(prompt), "{answer:?} is refused: {}", s.prompt_text());
};
lines(&mut s, &["-STYLE", "Wide", ""]);
still(&mut s, "-1", "Specify height of text");
still(&mut s, "0", "Specify width factor");
still(&mut s, "0", "Specify width factor");
still(&mut s, "2", "Specify obliquing angle");
still(&mut s, "86", "Specify obliquing angle");
lines(&mut s, &["-20", "", ""]);
assert!(s.running.is_none());
let st = style(&s, "Wide");
assert_eq!(st.width_factor, 2.0);
assert!((st.oblique.to_degrees() + 20.0).abs() < 1e-9);
}
#[test]
fn question_mark_lists_styles() {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Title", "height": 5, "current": false })).unwrap();
lines(&mut s, &["-STYLE", "?"]);
let before = s.log.len();
s.cmdline("T*").unwrap();
let listed: Vec<&String> = s.log[before..].iter().collect();
assert!(listed.iter().any(|l| l.contains("Style name: \"Title\"") && l.contains("Height: 5.0000")), "{listed:?}");
assert!(!listed.iter().any(|l| l.contains("\"Standard\"")), "{listed:?}");
assert!(s.running.is_none(), "listing ends the command");
s.cmdline("LINE").unwrap();
assert!(s.prompt_text().contains("first point"), "the next command starts: {}", s.prompt_text());
s.cancel();
}
#[test]
fn json_form_is_the_style_command() {
let mut s = Session::new();
s.execute("-style", &json!({ "name": "Json", "widthFactor": 0.75, "current": false })).unwrap();
assert_eq!(style(&s, "Json").width_factor, 0.75);
assert_eq!(current(&s), "Standard");
assert!(s.execute("-style", &json!({})).is_err());
}
#[test]
fn hostile_input_never_panics() {
let mut s = Session::new();
let long = "x".repeat(100_000);
for script in [
vec!["-STYLE", "?", &long],
vec!["-STYLE", "a/b"],
vec!["-STYLE", "Ok", &long, "1e308", "NaN", "inf", "-0", "1e-300", "85.0000001", "-85", "maybe", "y", "y"],
vec!["-STYLE", "Shx", "x.shx", "", "", "", "", "", "Yes"],
] {
for l in script {
let _ = s.cmdline(l);
}
s.cancel();
}
for p in [json!({ "name": 5 }), json!({ "name": "n", "height": -1, "widthFactor": 1e300, "oblique": f64::MAX }), json!({ "name": long })] {
let _ = s.execute("-style", &p);
}
}
-42
View File
@@ -366,45 +366,3 @@ fn a_short_piece_far_from_the_origin_is_highlighted_and_removed_as_near_it() {
assert!((before - drawn(&s) - 0.5).abs() < 1e-3, "at {x0}: the click removes the same 0.5");
}
}
#[test]
fn a_script_extend_ignores_shift_and_extends() {
// A script's EXTEND step must ignore the live Shift key: with Shift held it still extends.
let mut s = Session::new();
line(&mut s, [4.0, -5.0], [4.0, 5.0]);
line(&mut s, [10.0, -5.0], [10.0, 5.0]);
let l = line(&mut s, [0.0, 0.0], [8.0, 0.0]);
s.zoom_extents().unwrap();
s.shift_down = true;
s.script("_.extend\n6,0\n\n").unwrap();
let EntityKind::Line(x) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!() };
assert_eq!((x.b.x, x.b.y), (10.0, 0.0), "a scripted extend ignores Shift and extends");
}
#[test]
fn a_script_trim_ignores_shift_and_trims() {
// A script's TRIM step must ignore the live Shift key: with Shift held it still trims.
let mut s = Session::new();
line(&mut s, [4.0, -5.0], [4.0, 5.0]);
line(&mut s, [10.0, -5.0], [10.0, 5.0]);
let l = line(&mut s, [0.0, 0.0], [8.0, 0.0]);
s.zoom_extents().unwrap();
s.shift_down = true;
s.script("_.trim\n6,0\n\n").unwrap();
let EntityKind::Line(x) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!() };
assert_eq!((x.b.x, x.b.y), (4.0, 0.0), "a scripted trim ignores Shift and trims");
}
#[test]
fn a_lisp_extend_ignores_shift_and_extends() {
// A LISP `(command …)` EXTEND must ignore the live Shift key: with Shift held it still extends.
let mut s = Session::new();
line(&mut s, [4.0, -5.0], [4.0, 5.0]);
line(&mut s, [10.0, -5.0], [10.0, 5.0]);
let l = line(&mut s, [0.0, 0.0], [8.0, 0.0]);
s.zoom_extents().unwrap();
s.shift_down = true;
s.cmdline("(command \"_.extend\" '(6.0 0.0) \"\")").unwrap();
let EntityKind::Line(x) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!() };
assert_eq!((x.b.x, x.b.y), (10.0, 0.0), "a LISP extend ignores Shift and extends");
}
@@ -1,400 +0,0 @@
//! A window selects a TEXT, ATTDEF or MTEXT when it holds what the text draws, turned with the
//! text or not (#3731). The document's box for text is an estimate from its number of characters
//! (and lines), which reaches past what the fonts draw on the side a justification or attachment
//! leaves open. A window that held all of a text tested that box, so it could miss the text. A
//! crossing window still selects the text by touching its box, as before.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Common, Entity, EntityKind, HAlign, MText, RawTag, Space, Text, VAlign, entity_bounds};
use cadcraft_engine::geom::{Bounds2, Vec2, Vec3};
use serde_json::{Value, json};
/// Rotations the tests turn the text by, in degrees: none, a right angle and an oblique angle.
const ROTATIONS: [f64; 3] = [0.0, 90.0, 30.0];
/// Justifications: left (baseline), centre, right and middle-centre.
const JUSTIFY: [&str; 4] = ["L", "C", "R", "MC"];
/// The points of what the renderer draws for `e` in model space (none when it draws nothing).
fn drawn_points(s: &Session, e: &Entity) -> Vec<Vec2> {
let list = cadcraft_engine::render::build(s.doc().unwrap(), &Space::Model, &Default::default());
list.prims.iter().filter(|p| p.handle == e.handle).flat_map(|p| list.points(p).to_vec()).collect()
}
/// The points of what the renderer draws for `e`, which draws something.
fn drawn(s: &Session, e: &Entity) -> Vec<Vec2> {
let pts = drawn_points(s, e);
assert!(!pts.is_empty(), "the text draws strokes");
pts
}
/// The last entity added, and the box of what it draws. The document's box for it must reach
/// past that box, or the case would not tell the two apart.
fn last_text(s: &Session) -> (Entity, Bounds2) {
let e = s.doc().unwrap().model.last().unwrap().as_ref().clone();
let ink = Bounds2::from_points(drawn(s, &e));
let estimate = entity_bounds(s.doc().unwrap(), &e, 0);
assert!(!ink.contains_box(&estimate), "the estimated box {estimate:?} reaches past the drawn text {ink:?}");
(e, ink)
}
/// A session holding one TEXT of narrow characters, which draw narrower than the estimate.
fn one_text(rotation: f64, justify: &str) -> (Session, Entity, Bounds2) {
let mut s = Session::new();
s.execute("text", &json!({"at": [3.0, 2.0], "text": "1.1", "height": 0.5, "rotation": rotation, "justify": justify})).unwrap();
let (e, ink) = last_text(&s);
(s, e, ink)
}
/// The handles the `entities` query (MCP `query_entities`) finds in window `w`.
fn query(s: &mut Session, w: Bounds2, crossing: bool) -> Vec<Value> {
let r = s.execute("entities", &json!({"window": [[w.min.x, w.min.y], [w.max.x, w.max.y]], "crossing": crossing})).unwrap();
r["entities"].as_array().unwrap().iter().map(|e| e["handle"].clone()).collect()
}
/// Whether a window dragged from `w.min` to `w.max` with no command running selects `e`.
fn dragged(s: &mut Session, w: Bounds2, e: &Entity) -> bool {
s.set_selection(Vec::new());
assert!(s.begin_window(w.min));
s.idle_click(w.max, false).unwrap();
s.state().unwrap().selection.contains(&e.handle)
}
/// Whether `input`, an ERASE ended by one more Enter, erases `e`; the erase is undone. A window
/// that finds nothing ends ERASE by itself, and that Enter then starts it again: it is cancelled.
fn erases(s: &mut Session, input: &str, e: &Entity) -> bool {
s.cmdline(input).unwrap();
s.cmdline("").unwrap();
if s.running.is_some() {
s.cancel();
}
assert!(s.running.is_none(), "{input}: the command ended");
let gone = s.doc().unwrap().entity(e.handle).is_none();
if gone {
s.undo().unwrap();
}
gone
}
/// Whether ERASE with the Window option from `w.min` to `w.max` erases `e`.
fn erased(s: &mut Session, w: Bounds2, e: &Entity) -> bool {
erases(s, &format!("ERASE W {},{} {},{}", w.min.x, w.min.y, w.max.x, w.max.y), e)
}
/// `w` with one side moved in by `by`: 0 left, 1 bottom, 2 right, 3 top.
fn nudged(w: Bounds2, side: usize, by: f64) -> Bounds2 {
let (mut min, mut max) = (w.min, w.max);
match side {
0 => min.x += by,
1 => min.y += by,
2 => max.x -= by,
_ => max.y -= by,
}
Bounds2::new(min, max)
}
#[test]
fn a_window_on_the_edges_of_a_turned_text_selects_it() {
for rotation in ROTATIONS {
for justify in JUSTIFY {
let (mut s, e, ink) = one_text(rotation, justify);
let case = format!("{rotation} degrees, {justify}");
let handle = json!(e.handle.hex());
assert_eq!(query(&mut s, ink, false), vec![handle.clone()], "query, {case}");
assert!(dragged(&mut s, ink, &e), "dragged window, {case}");
assert!(erased(&mut s, ink, &e), "ERASE W, {case}");
// A window that leaves out a sliver of the text on any side does not hold it.
for side in 0..4 {
let w = nudged(ink, side, 1e-3);
assert!(query(&mut s, w, false).is_empty(), "query, {case}, side {side}");
assert!(!dragged(&mut s, w, &e), "dragged window, {case}, side {side}");
assert!(!erased(&mut s, w, &e), "ERASE W, {case}, side {side}");
}
}
}
}
#[test]
fn a_crossing_window_still_selects_a_text_it_touches() {
for rotation in ROTATIONS {
for justify in JUSTIFY {
let (mut s, e, ink) = one_text(rotation, justify);
let handle = json!(e.handle.hex());
for w in [ink, nudged(ink, 0, 1e-3), nudged(ink, 1, 1e-3), nudged(ink, 2, 1e-3), nudged(ink, 3, 1e-3)] {
assert_eq!(query(&mut s, w, true), vec![handle.clone()], "{rotation} degrees, {justify}: {w:?}");
}
// One clear of the text's box selects nothing.
let b = entity_bounds(s.doc().unwrap(), &e, 0);
// Unturned, its box reaches right of the strokes; a crossing window there, touching
// the box and no stroke, still selects it, as before.
if rotation == 0.0 {
assert!(b.max.x > ink.max.x + 0.02, "{justify}: the box reaches right of the strokes");
let mid = (ink.min.y + ink.max.y) / 2.0;
let past = Bounds2::new(Vec2::new(ink.max.x + 0.01, mid), Vec2::new(b.max.x + 0.01, mid + 0.01));
assert_eq!(query(&mut s, past, true), vec![handle.clone()], "{justify}: crossing past the strokes");
}
let clear = Bounds2::new(Vec2::new(b.max.x + 0.1, b.min.y), Vec2::new(b.max.x + 1.0, b.max.y));
assert!(query(&mut s, clear, true).is_empty(), "{rotation} degrees, {justify}");
}
}
}
/// The reported case: three labels 0.09375 high, turned by a right angle, whose drawn text
/// starts at y = 11.277, inside the window (-1.25, 11.22)-(14.10, 21.60). Justified to their end,
/// they run up from there, and their estimated box hangs below the window's bottom edge (while
/// one down to y = 10.9 holds it).
#[test]
fn turned_labels_inside_a_window_are_selected() {
let mut s = Session::new();
let w = Bounds2::new(Vec2::new(-1.25, 11.22), Vec2::new(14.10, 21.60));
let lower = Bounds2::new(Vec2::new(-1.25, 10.9), Vec2::new(14.10, 21.60));
let mut labels = Vec::new();
for (x, value) in [(1.0, "1.1.1.1"), (5.0, "11.11.1"), (9.0, "1.11.11")] {
// Measure where the label draws, then place it so its drawn start is at y = 11.277.
let label = |s: &mut Session, y: f64| {
s.execute("text", &json!({"at": [x, y], "text": value, "height": 0.09375, "rotation": 90, "justify": "R"})).unwrap();
last_text(s)
};
let (probe, ink) = label(&mut s, 0.0);
s.execute("erase", &json!({"handles": [probe.handle.hex()]})).unwrap();
let (e, ink_at) = label(&mut s, 11.277 - ink.min.y);
let estimate = entity_bounds(s.doc().unwrap(), &e, 0);
assert!(w.contains_box(&ink_at), "{value} draws inside the window: {ink_at:?}");
assert!(!w.contains_box(&estimate) && lower.contains_box(&estimate), "{value}: the estimate {estimate:?} hangs below 11.22");
labels.push(e);
}
assert_eq!(query(&mut s, w, false).len(), 3);
s.script(&format!("ERASE W {},{} {},{}\n\n", w.min.x, w.min.y, w.max.x, w.max.y)).unwrap();
for e in &labels {
assert!(s.doc().unwrap().entity(e.handle).is_none(), "{e:?} erased");
}
}
/// The corners of the box of `pts` in the frame turned by `deg` about `o`, grown by `grow` on
/// each side but `side` (0 left, 1 bottom, 2 right, 3 top), which is pulled in by `grow` instead.
fn turned_box(pts: &[Vec2], o: Vec2, deg: f64, grow: f64, side: Option<usize>) -> [Vec2; 4] {
let r = deg.to_radians();
let local = Bounds2::from_points(pts.iter().map(|p| (*p - o).rotate(-r)));
let mut b = local.expand(grow);
if let Some(side) = side {
b = nudged(b, side, 2.0 * grow);
}
[b.min, Vec2::new(b.max.x, b.min.y), b.max, Vec2::new(b.min.x, b.max.y)].map(|c| o + c.rotate(r))
}
#[test]
fn a_window_polygon_turned_with_a_text_selects_it() {
for rotation in ROTATIONS {
for justify in JUSTIFY {
let (mut s, e, _) = one_text(rotation, justify);
let pts = drawn(&s, &e);
let o = Vec2::new(3.0, 2.0);
// The polygon ends with one Enter and the selection with the one `erases` gives.
let mut wp = |poly: [Vec2; 4]| {
let corners: Vec<String> = poly.iter().map(|p| format!("{},{}", p.x, p.y)).collect();
s.cmdline(&format!("ERASE WP {}", corners.join(" "))).unwrap();
erases(&mut s, "", &e)
};
let case = format!("{rotation} degrees, {justify}");
assert!(wp(turned_box(&pts, o, rotation, 1e-3, None)), "{case}");
for side in 0..4 {
assert!(!wp(turned_box(&pts, o, rotation, 1e-3, Some(side))), "{case}, side {side}");
}
}
}
}
#[test]
fn a_window_on_the_edges_of_an_attribute_definition_selects_it() {
for justify in ["L", "C", "R"] {
let mut s = Session::new();
s.execute("attdef", &json!({"tag": "I1", "at": [3.0, 2.0], "height": 0.5, "justify": justify})).unwrap();
let (e, ink) = last_text(&s);
assert_eq!(query(&mut s, ink, false), vec![json!(e.handle.hex())], "{justify}");
for side in 0..4 {
assert!(query(&mut s, nudged(ink, side, 1e-3), false).is_empty(), "{justify}, side {side}");
}
}
}
/// An annotative text draws at the current annotation scale, and not at all when that scale
/// hides it; a text that matches the layout's orientation draws upright whatever its rotation.
/// A window holds each as it draws.
#[test]
fn a_window_holds_annotative_and_upright_text_as_drawn() {
let held = |s: &mut Session, e: &Entity, ink: Bounds2, case: &str| {
assert_eq!(query(s, ink, false), vec![json!(e.handle.hex())], "{case}");
for side in 0..4 {
assert!(query(s, nudged(ink, side, 1e-3), false).is_empty(), "{case}, side {side}");
}
};
let mut s = Session::new();
s.execute("style", &json!({"name": "Notes", "annotative": true, "current": true})).unwrap();
s.execute("setvar", &json!({"name": "CANNOSCALE", "value": "1:50"})).unwrap();
s.execute("text", &json!({"at": [3.0, 2.0], "text": "1.1", "height": 0.5, "rotation": 30, "justify": "C"})).unwrap();
let (e, ink) = last_text(&s);
held(&mut s, &e, ink, "annotative at 1:50");
// At a scale the text doesn't support, with ANNOALLVISIBLE 0, it draws nothing.
s.execute("setvar", &json!({"name": "CANNOSCALE", "value": "1:20"})).unwrap();
s.execute("annovisible.current", &json!({})).unwrap();
let everything = Bounds2::new(Vec2::new(-1e3, -1e3), Vec2::new(1e3, 1e3));
assert!(query(&mut s, everything, false).is_empty(), "a hidden annotative text");
let mut s = Session::new();
let at = Vec3::new(3.0, 2.0, 0.0);
let text = Text {
insert: at,
align_pt: Some(at),
height: 0.5,
value: "1.1".into(),
rotation: std::f64::consts::FRAC_PI_2,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: HAlign::Center,
valign: VAlign::Baseline,
backwards: false,
upside_down: false,
};
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let common = Common { xdata: vec![tag(1001, "AcadAnnoPO"), tag(1070, "1")], ..Common::default() };
s.doc_mut().unwrap().add(&Space::Model, common.clone(), EntityKind::Text(text)).unwrap();
let (e, ink) = last_text(&s);
assert!(ink.width() > ink.height(), "drawn upright: {ink:?}");
held(&mut s, &e, ink, "upright");
let mut s = Session::new();
let note = MText {
insert: Vec3::new(3.0, 2.0, 0.0),
height: 0.5,
width: 0.0,
attach: 5,
rotation: std::f64::consts::FRAC_PI_2,
style: "Standard".into(),
contents: "1.1".into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
};
s.doc_mut().unwrap().add(&Space::Model, common, EntityKind::MText(note)).unwrap();
let (e, ink) = last_text(&s);
assert!(ink.width() > ink.height(), "MTEXT drawn upright: {ink:?}");
held(&mut s, &e, ink, "upright MTEXT");
}
/// A TEXT of narrow characters at (3, 2), justified by `halign`/`valign`, added to `s`'s model.
fn add_text(s: &mut Session, value: &str, height: f64, rotation_deg: f64, halign: HAlign, valign: VAlign, edit: impl Fn(&mut Text)) {
let at = Vec3::new(3.0, 2.0, 0.0);
let mut t = Text {
insert: at,
align_pt: Some(at),
height,
value: value.into(),
rotation: rotation_deg.to_radians(),
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign,
valign,
backwards: false,
upside_down: false,
};
edit(&mut t);
s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap();
}
/// Mirrored text (backwards, upside down) and slanted text (an obliquing angle) are held by
/// what they draw too, turned or not.
#[test]
fn a_window_holds_mirrored_and_slanted_text_as_drawn() {
let variants: [(&str, fn(&mut Text)); 3] =
[("backwards", |t| t.backwards = true), ("upside down", |t| t.upside_down = true), ("slanted", |t| t.oblique = 20f64.to_radians())];
for (name, edit) in variants {
for rotation in ROTATIONS {
for (halign, valign) in [(HAlign::Left, VAlign::Baseline), (HAlign::Center, VAlign::Baseline), (HAlign::Right, VAlign::Top)] {
let mut s = Session::new();
add_text(&mut s, "1.1", 0.5, rotation, halign, valign, edit);
let (e, ink) = last_text(&s);
let case = format!("{name}, {rotation} degrees, {halign:?} {valign:?}");
assert_eq!(query(&mut s, ink, false), vec![json!(e.handle.hex())], "{case}");
assert!(erased(&mut s, ink, &e), "ERASE W, {case}");
for side in 0..4 {
assert!(query(&mut s, nudged(ink, side, 1e-3), false).is_empty(), "{case}, side {side}");
}
}
}
}
}
/// Text that draws nothing (blank) is never held. Text with no usable height draws at a height of
/// one, as the renderer draws it, and a window that holds that takes it.
#[test]
fn a_window_holds_blank_and_zero_height_text_as_drawn() {
let everything = Bounds2::new(Vec2::new(-1e3, -1e3), Vec2::new(1e3, 1e3));
let mut s = Session::new();
add_text(&mut s, " ", 0.5, 30.0, HAlign::Center, VAlign::Baseline, |_| ());
assert!(query(&mut s, everything, false).is_empty(), "blank text");
for height in [0.0, -1.0] {
let mut s = Session::new();
add_text(&mut s, "1.1", height, 30.0, HAlign::Center, VAlign::Baseline, |_| ());
let e = s.doc().unwrap().model.last().unwrap().as_ref().clone();
let ink = Bounds2::from_points(drawn(&s, &e));
assert!(ink.width() > 0.1, "height {height}: drawn at a usable height, {ink:?}");
assert_eq!(query(&mut s, ink, false), vec![json!(e.handle.hex())], "height {height}");
}
}
/// An MTEXT of narrow characters on two lines at (3, 2), attached by `justify`.
fn one_mtext(rotation: f64, justify: &str) -> (Session, Entity, Bounds2) {
let mut s = Session::new();
s.execute("mtext", &json!({"at": [3.0, 2.0], "text": r"1.1\P11", "height": 0.5, "rotation": rotation, "justify": justify})).unwrap();
let (e, ink) = last_text(&s);
(s, e, ink)
}
#[test]
fn a_window_on_the_edges_of_a_turned_mtext_selects_it() {
for rotation in ROTATIONS {
for justify in ["TL", "MC", "BR"] {
let (mut s, e, ink) = one_mtext(rotation, justify);
let case = format!("MTEXT {rotation} degrees, {justify}");
assert_eq!(query(&mut s, ink, false), vec![json!(e.handle.hex())], "query, {case}");
assert!(erased(&mut s, ink, &e), "ERASE W, {case}");
for side in 0..4 {
let w = nudged(ink, side, 1e-3);
assert!(query(&mut s, w, false).is_empty(), "query, {case}, side {side}");
assert!(!erased(&mut s, w, &e), "ERASE W, {case}, side {side}");
}
// A window polygon turned with it.
let pts = drawn(&s, &e);
let o = Vec2::new(3.0, 2.0);
let mut wp = |poly: [Vec2; 4]| {
let corners: Vec<String> = poly.iter().map(|p| format!("{},{}", p.x, p.y)).collect();
s.cmdline(&format!("ERASE WP {}", corners.join(" "))).unwrap();
erases(&mut s, "", &e)
};
assert!(wp(turned_box(&pts, o, rotation, 1e-3, None)), "WP, {case}");
assert!(!wp(turned_box(&pts, o, rotation, 1e-3, Some(1))), "WP, {case}, bottom");
}
}
}
/// A blank MTEXT draws nothing and is still selected by its frame; an MTEXT whose contents are
/// only formatting draws nothing either and keeps the document's box.
#[test]
fn mtext_that_draws_nothing_keeps_its_box() {
let mut s = Session::new();
s.execute("mtext", &json!({"at": [3.0, 2.0], "text": " ", "height": 0.5, "width": 4.0, "rotation": 30})).unwrap();
s.execute("mtext", &json!({"at": [20.0, 2.0], "text": r"{\L}", "height": 0.5, "rotation": 30})).unwrap();
let d = s.doc().unwrap();
let texts: Vec<Entity> = d.model.iter().map(|e| e.as_ref().clone()).collect();
for e in &texts {
assert!(drawn_points(&s, e).is_empty(), "{e:?} draws nothing");
}
// The blank one is held by its frame, around (3, 2).
let blank = Bounds2::new(Vec2::new(-5.0, -5.0), Vec2::new(10.0, 10.0));
assert_eq!(query(&mut s, blank, false), vec![json!(texts[0].handle.hex())]);
let b = entity_bounds(s.doc().unwrap(), &texts[1], 0);
assert!(!b.is_empty(), "the formatting-only MTEXT has a box");
assert_eq!(query(&mut s, b, false), vec![json!(texts[1].handle.hex())]);
}
-46
View File
@@ -244,49 +244,3 @@ fn acad_xdata_of_a_dimension_is_refused_and_kept_elsewhere() {
let dm = back.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).unwrap();
assert!(matches!(&dm.kind, EntityKind::Dimension(d) if !d.overrides.is_empty()), "the DSTYLE overrides survive");
}
/// A leader's DSTYLE list is its style overrides, written from the model: `properties.set`
/// refuses `ACAD` xdata that holds one (nothing changes), with or without overrides on the
/// leader, and takes other `ACAD` data, which a save keeps beside the overrides.
#[test]
fn a_dstyle_list_in_a_leaders_acad_xdata_is_refused_and_other_acad_data_kept() {
use cadcraft_engine::doc::{Common, Leader, Space};
use cadcraft_engine::geom::Vec3;
let overrides_of = |s: &Session| {
s.doc().unwrap().model.iter().find_map(|e| match &e.kind {
EntityKind::Leader(l) => Some(l.overrides.clone()),
_ => None,
})
};
for overrides in [json!({}), json!({"arrowSize": 1.5})] {
let want = overrides.as_object().cloned().unwrap();
let mut s = Session::new();
let leader = Leader {
vertices: vec![Vec3::ZERO, Vec3::new(10.0, 0.0, 0.0)],
arrow: true,
spline: false,
style: "Standard".into(),
overrides: want.clone(),
};
let h = s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Leader(leader)).unwrap().hex();
let before = entities(&mut s, json!({"xdata": true}));
let list = json!([[1000, "DSTYLE"], [1002, "{"], [1070, 41], [1040, 9.0], [1002, "}"]]);
let later = json!([[1000, "MINE"], [1000, "dstyle"], [1002, "{"], [1070, 41], [1040, 9.0], [1002, "}"]]);
for acad in [list, later] {
let r = s.execute("properties.set", &json!({"handles": [&h], "layer": "NEWLAYER", "xdata": {"ACAD": acad}}));
let msg = r.expect_err("a DSTYLE list on a leader is refused").to_string();
assert!(msg.contains("DSTYLE"), "the refusal names the list: {msg}");
assert_eq!(entities(&mut s, json!({"xdata": true})), before, "{overrides}");
assert_eq!(overrides_of(&s), Some(want.clone()));
assert!(s.doc().unwrap().layer("NEWLAYER").is_none(), "no layer is left behind");
}
// Other ACAD data, also a string that only reads DSTYLE, is foreign data and stays.
let other = json!({"ACAD": [[1000, "DSTYLE"], [1000, "MINE"], [1070, 42]]});
s.execute("properties.set", &json!({"handles": [&h], "xdata": other})).unwrap();
let bytes = cadcraft_io::write(s.doc().unwrap(), "leader.dxf").unwrap();
let mut back = Session::empty();
back.open_drawing(cadcraft_io::read_dxf(&bytes).unwrap(), "leader", None);
assert_eq!(entities(&mut back, json!({"xdata": "ACAD"}))[0]["xdata"], other, "{overrides}");
assert_eq!(overrides_of(&back), Some(want), "the overrides after a save and reopen");
}
}
-325
View File
@@ -1,325 +0,0 @@
//! The user's plot style folder: STYLESMANAGER keeps tables there for every drawing, and a layout
//! that chooses one takes a copy into the drawing, which no longer depends on the file.
//!
//! Its own test binary, like `plotters.rs`: the folder is process-wide and must be the in-memory
//! one before any session reads the real settings folder. Each test uses its own table names.
//! The folder here treats names as macOS and Windows disks do: `a.json` and `A.json` are one file.
#[path = "support/temp_dir.rs"]
mod temp_dir;
use cadcraft_doc::PlotStyleTable;
use cadcraft_engine::Session;
use cadcraft_engine::cmd::plotstyle_folder::{PlotStyleStore, set_plot_style_store};
use serde_json::{Value, json};
use temp_dir::TempDir;
static FILES: std::sync::Mutex<Vec<(String, String)>> = std::sync::Mutex::new(Vec::new());
/// A folder in memory whose names ignore case, as on a default macOS or Windows disk: writing
/// `a.json` over an existing `A.json` replaces that file and keeps its spelling.
fn folder() -> PlotStyleStore {
fn files() -> std::sync::MutexGuard<'static, Vec<(String, String)>> {
FILES.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
PlotStyleStore {
location: || None,
list: || Ok(files().iter().map(|(n, _)| n.clone()).collect()),
read: |n| files().iter().find(|(f, _)| f.eq_ignore_ascii_case(n)).map(|(_, t)| t.clone()).ok_or_else(|| format!("{n}: no such file")),
write: |n, t| {
let mut f = files();
match f.iter_mut().find(|(x, _)| x.eq_ignore_ascii_case(n)) {
Some(x) => x.1 = t.to_string(),
None => f.push((n.to_string(), t.to_string())),
}
Ok(())
},
delete: |n| {
// A file this folder refuses to remove, as a locked or read-only file would be.
if n.starts_with("stuck") {
return Err(format!("{n}: refused"));
}
let mut f = files();
let before = f.len();
f.retain(|(x, _)| !x.eq_ignore_ascii_case(n));
if f.len() == before { Err(format!("{n}: no such file")) } else { Ok(()) }
},
}
}
fn session() -> Session {
set_plot_style_store(folder());
Session::new()
}
fn tables(s: &mut Session) -> Vec<Value> {
s.execute("stylesmanager", &json!({})).unwrap()["tables"].as_array().unwrap().clone()
}
fn source(s: &mut Session, name: &str) -> Option<String> {
tables(s).iter().find(|t| t["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(name))).map(|t| t["source"].as_str().unwrap().to_string())
}
fn style_color(s: &Session, name: &str, aci: u8) -> Option<String> {
cadcraft_doc::plot_style_table(s.doc().unwrap(), name).and_then(|t| t.by_color(aci).and_then(|st| st.color).map(|c| c.hex()))
}
#[test]
fn a_folder_table_reaches_every_drawing() {
let mut a = session();
let r = a.execute("stylesmanager", &json!({"action": "new", "name": "every", "where": "folder", "from": "monochrome.ctb"})).unwrap();
assert_eq!(r["name"], "every.ctb", "the ending follows the kind");
assert_eq!(source(&mut a, "every.ctb").as_deref(), Some("folder"));
assert!(a.doc().unwrap().plot_style_tables.is_empty(), "the drawing itself is unchanged");
// A drawing opened later sees it too.
let mut b = Session::new();
assert_eq!(source(&mut b, "every.ctb").as_deref(), Some("folder"));
// The same name again is refused.
assert!(a.execute("stylesmanager", &json!({"action": "new", "name": "every.ctb", "where": "folder"})).is_err());
// Names a file can't have are refused.
assert!(a.execute("stylesmanager", &json!({"action": "new", "name": "../up", "where": "folder"})).is_err());
}
#[test]
fn a_layout_takes_a_copy_that_no_longer_depends_on_the_file() {
let mut s = session();
s.execute("stylesmanager", &json!({"action": "new", "name": "copied.ctb", "where": "folder"})).unwrap();
s.execute("pagesetup", &json!({"layout": "Layout1", "plotStyleTable": "copied.ctb"})).unwrap();
assert_eq!(source(&mut s, "copied.ctb").as_deref(), Some("drawing"), "the layout took the table into the drawing");
// Changing the folder's file leaves the drawing's copy as it is.
s.execute("stylesmanager", &json!({"action": "set", "name": "copied.ctb", "where": "folder", "style": {"name": "Color_1", "color": "#112233"}}))
.unwrap();
assert!(style_color(&s, "copied.ctb", 1).is_none(), "the drawing still plots with its own copy");
let file = cadcraft_doc::plot_style_folder_table("copied.ctb").unwrap();
assert!(file.by_color(1).and_then(|x| x.color).is_some(), "the file has the edit");
// Without `where`, an edit goes to the drawing's copy, and undo takes it back.
s.execute("stylesmanager", &json!({"action": "set", "name": "copied.ctb", "style": {"name": "Color_2", "color": "#445566"}})).unwrap();
assert!(style_color(&s, "copied.ctb", 2).is_some());
assert!(cadcraft_doc::plot_style_folder_table("copied.ctb").unwrap().by_color(2).and_then(|x| x.color).is_none(), "the file is untouched");
s.undo().unwrap();
assert!(style_color(&s, "copied.ctb", 2).is_none());
// Choosing the table again doesn't replace the drawing's copy with the file.
s.execute("pagesetup", &json!({"layout": "Layout2", "plotStyleTable": "copied.ctb"})).unwrap();
assert!(style_color(&s, "copied.ctb", 1).is_none());
}
#[test]
fn the_drawing_wins_over_a_folder_table_of_the_same_name() {
let mut s = session();
s.execute("stylesmanager", &json!({"action": "new", "name": "both.ctb", "where": "folder", "from": "monochrome.ctb"})).unwrap();
assert_eq!(source(&mut s, "both.ctb").as_deref(), Some("folder"));
s.execute("stylesmanager", &json!({"action": "new", "name": "both.ctb"})).unwrap();
assert_eq!(source(&mut s, "both.ctb").as_deref(), Some("drawing"));
assert!(style_color(&s, "both.ctb", 1).is_none(), "the drawing's version is the one used");
}
#[test]
fn renaming_the_file_leaves_the_drawing_alone() {
let mut s = session();
s.execute("stylesmanager", &json!({"action": "new", "name": "before.stb", "where": "folder"})).unwrap();
s.execute("pagesetup", &json!({"layout": "Layout1", "plotStyleTable": "before.stb"})).unwrap();
let r = s.execute("stylesmanager", &json!({"action": "rename", "name": "before.stb", "to": "after", "where": "folder"})).unwrap();
assert_eq!(r["name"], "after.stb");
assert_eq!(source(&mut s, "after.stb").as_deref(), Some("folder"));
assert_eq!(source(&mut s, "before.stb").as_deref(), Some("drawing"), "the drawing keeps its copy under the old name");
assert_eq!(s.doc().unwrap().layout("Layout1").unwrap().page.plot_style_table, "before.stb");
// Renaming the drawing's table moves this drawing's layouts with it.
let r = s.execute("stylesmanager", &json!({"action": "rename", "name": "before.stb", "to": "mine"})).unwrap();
assert_eq!(r["layouts"], 1);
assert_eq!(s.doc().unwrap().layout("Layout1").unwrap().page.plot_style_table, "mine.stb");
// A named table can't take a colour-dependent name, and built-in tables can't be renamed.
assert!(s.execute("stylesmanager", &json!({"action": "rename", "name": "after.stb", "to": "x.ctb"})).is_err());
assert!(s.execute("stylesmanager", &json!({"action": "rename", "name": "monochrome.ctb", "to": "mine"})).is_err());
}
#[test]
fn delete_from_the_folder_leaves_the_drawings_copy() {
let mut s = session();
s.execute("stylesmanager", &json!({"action": "new", "name": "gone.ctb", "where": "folder", "from": "monochrome.ctb"})).unwrap();
s.execute("pagesetup", &json!({"layout": "Layout1", "plotStyleTable": "gone.ctb"})).unwrap();
s.execute("stylesmanager", &json!({"action": "delete", "name": "gone.ctb", "where": "folder"})).unwrap();
assert_eq!(source(&mut s, "gone.ctb").as_deref(), Some("drawing"), "the layout still plots with its copy");
assert!(style_color(&s, "gone.ctb", 1).is_some());
assert!(s.execute("stylesmanager", &json!({"action": "delete", "name": "gone.ctb", "where": "folder"})).is_err());
}
#[test]
fn reload_reads_files_added_outside_and_skips_bad_ones() {
let mut s = session();
let store = folder();
let named = PlotStyleTable::named("whatever", "", Vec::new());
(store.write)("outside.json", &named.to_file_text()).unwrap();
(store.write)("wrongkind.ctb.json", &named.to_file_text()).unwrap();
(store.write)("broken.ctb.json", "not a table").unwrap();
let r = s.execute("stylesmanager", &json!({"action": "reload"})).unwrap();
let names: Vec<&str> = r["tables"].as_array().unwrap().iter().filter_map(|t| t["name"].as_str()).collect();
assert!(names.contains(&"outside.stb"), "named after the file, with its kind's ending: {names:?}");
assert!(!names.iter().any(|n| n.starts_with("wrongkind") || n.starts_with("broken")), "{names:?}");
let warnings = r["warnings"].as_array().unwrap();
assert!(
warnings.iter().any(|w| w.as_str().unwrap().contains("wrongkind")) && warnings.iter().any(|w| w.as_str().unwrap().contains("broken")),
"{warnings:?}"
);
}
/// File hooks for the tests that save or plot (the hooks are process-wide, so both share one set).
/// The writer refuses a drawing whose layout names a table the drawing doesn't carry.
fn with_io() -> Session {
cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks {
read: |_, _| Err("no reader in this test".into()),
write: |d, _| {
let missing = d.layouts.iter().any(|l| {
let n = l.page.plot_style_table.trim();
n.eq_ignore_ascii_case("carried.ctb") && !d.plot_style_tables.iter().any(|t| t.name.eq_ignore_ascii_case(n))
});
if missing { Err("the layout's table is not in the drawing".into()) } else { Ok(b"0\nEOF\n".to_vec()) }
},
plot: Some(|_, _, _| Ok(b"%PDF-1.4".to_vec())),
});
session()
}
#[test]
fn plotting_with_a_folder_table_takes_it_into_the_drawing() {
let mut s = with_io();
s.execute("stylesmanager", &json!({"action": "new", "name": "plotted.ctb", "where": "folder"})).unwrap();
// A preview (an image with no file) takes nothing.
s.execute("plot", &json!({"layout": "Model", "output": "png", "plotStyleTable": "plotted.ctb"})).unwrap();
s.execute("plot", &json!({"layout": "Model", "output": "png", "path": null, "plotStyleTable": "plotted.ctb"})).unwrap();
assert_eq!(source(&mut s, "plotted.ctb").as_deref(), Some("folder"));
assert!(s.doc().unwrap().model_page.is_none());
// A plot from Model takes a copy, and Model remembers the table for the next plot.
s.execute("plot", &json!({"layout": "Model", "plotStyleTable": "plotted.ctb"})).unwrap();
assert_eq!(source(&mut s, "plotted.ctb").as_deref(), Some("drawing"));
assert_eq!(model_table(&s), "plotted.ctb");
assert_eq!(cadcraft_render::paper::model_page(s.doc().unwrap()).plot_style_table, "plotted.ctb", "the next Model plot starts from it");
s.undo().unwrap();
assert_eq!(model_table(&s), "");
}
fn model_table(s: &Session) -> String {
s.doc().unwrap().model_page.as_ref().map(|m| m.plot_style_table.clone()).unwrap_or_default()
}
#[test]
fn model_keeps_only_its_plot_style_table() {
let mut s = session();
s.execute("pagesetup", &json!({"layout": "model", "plotStyleTable": "monochrome.ctb"})).unwrap();
assert_eq!(model_table(&s), "monochrome.ctb");
assert!(s.execute("pagesetup", &json!({"layout": "Model", "paper": "A3"})).is_err(), "Model keeps no paper");
s.execute("pagesetup", &json!({"layout": "Model", "plotStyleTable": "None"})).unwrap();
assert_eq!(model_table(&s), "");
}
#[test]
fn saving_puts_the_folder_tables_the_layouts_use_into_the_file() {
let mut s = with_io();
s.execute("stylesmanager", &json!({"action": "new", "name": "carried.ctb", "where": "folder"})).unwrap();
s.execute("pagesetup", &json!({"layout": "Layout1", "plotStyleTable": "carried.ctb"})).unwrap();
// A drawing whose layout names the folder table without a copy (one made before copies were kept).
s.execute("stylesmanager", &json!({"action": "delete", "name": "carried.ctb", "where": "drawing"})).unwrap();
assert_eq!(source(&mut s, "carried.ctb").as_deref(), Some("folder"));
let dir = TempDir::new("carried");
s.execute("saveas", &json!({"path": dir.path_str("carried.dxf")})).unwrap();
assert_eq!(source(&mut s, "carried.ctb").as_deref(), Some("drawing"), "the save took the table into the drawing");
}
#[test]
fn renaming_a_folder_table_by_case_keeps_it() {
let mut s = session();
s.execute("stylesmanager", &json!({"action": "new", "name": "Office.ctb", "where": "folder", "from": "monochrome.ctb"})).unwrap();
s.execute("stylesmanager", &json!({"action": "rename", "name": "Office.ctb", "to": "office.ctb", "where": "folder"})).unwrap();
let names: Vec<String> = tables(&mut s).iter().filter_map(|t| t["name"].as_str().map(str::to_string)).collect();
assert!(names.iter().any(|n| n == "office.ctb"), "the table is still there, spelt the new way: {names:?}");
assert!(style_color(&s, "office.ctb", 1).is_some(), "with its styles");
}
#[test]
fn a_file_named_without_its_kind_is_edited_and_deleted_in_place() {
let mut s = session();
(folder().write)("loose.json", &PlotStyleTable::named("whatever", "", Vec::new()).to_file_text()).unwrap();
s.execute("stylesmanager", &json!({"action": "reload"})).unwrap();
s.execute("stylesmanager", &json!({"action": "set", "name": "loose.stb", "where": "folder", "description": "edited"})).unwrap();
assert_eq!(cadcraft_doc::plot_style_folder_table("loose.stb").unwrap().description, "edited", "the edit is the table the folder holds");
s.execute("stylesmanager", &json!({"action": "delete", "name": "loose.stb", "where": "folder"})).unwrap();
assert!(source(&mut s, "loose.stb").is_none(), "no file holds it any more");
}
#[test]
fn renaming_the_drawings_table_moves_model_with_it() {
let mut s = session();
s.execute("stylesmanager", &json!({"action": "new", "name": "modelold.ctb"})).unwrap();
s.execute("pagesetup", &json!({"layout": "Model", "plotStyleTable": "modelold.ctb"})).unwrap();
s.execute("stylesmanager", &json!({"action": "rename", "name": "modelold.ctb", "to": "modelnew"})).unwrap();
assert_eq!(model_table(&s), "modelnew.ctb");
}
#[test]
fn a_pdf_of_model_alone_remembers_its_table_from_a_layout_tab() {
let mut s = with_io();
s.execute("stylesmanager", &json!({"action": "new", "name": "frompaper.ctb", "where": "folder"})).unwrap();
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.execute("plot", &json!({"layouts": ["Model"], "plotStyleTable": "frompaper.ctb"})).unwrap();
assert_eq!(model_table(&s), "frompaper.ctb", "Model is the sheet plotted");
}
#[test]
fn a_refused_plot_leaves_the_drawing_as_it_was() {
let mut s = with_io();
s.execute("stylesmanager", &json!({"action": "new", "name": "refused.ctb", "where": "folder"})).unwrap();
let dir = TempDir::new("refused");
let out = std::path::PathBuf::from(dir.path_str("out"));
std::fs::create_dir(&out).unwrap();
let roots = cadcraft_engine::file_access::AutomationRoots::new(None, Some(&out)).unwrap();
let undo = s.state().unwrap().undo.len();
cadcraft_engine::file_access::confine(roots.as_ref(), || {
let outside = dir.path_str("elsewhere.pdf");
assert!(s.execute("plot", &json!({"layout": "Model", "path": outside, "plotStyleTable": "refused.ctb"})).is_err());
assert!(s.execute("plot", &json!({"layout": "Layout1", "path": outside, "plotStyleTable": "refused.ctb"})).is_err());
});
assert_eq!(model_table(&s), "", "Model still has no table");
assert_eq!(source(&mut s, "refused.ctb").as_deref(), Some("folder"), "the drawing took no copy");
assert_eq!(s.state().unwrap().undo.len(), undo, "and no undo step");
}
#[test]
fn new_copies_the_table_from_the_place_chosen() {
let mut s = session();
s.execute("stylesmanager", &json!({"action": "new", "name": "twice.ctb", "where": "folder"})).unwrap();
s.execute("stylesmanager", &json!({"action": "set", "name": "twice.ctb", "where": "folder", "style": {"name": "Color_1", "color": "#ff0000"}}))
.unwrap();
s.execute("stylesmanager", &json!({"action": "new", "name": "twice.ctb"})).unwrap();
let from = |s: &mut Session, name: &str, place: &str| {
s.execute("stylesmanager", &json!({"action": "new", "name": name, "from": "twice.ctb", "fromWhere": place})).unwrap();
style_color(s, name, 1)
};
let folder = from(&mut s, "fromfolder.ctb", "folder");
let drawing = from(&mut s, "fromdrawing.ctb", "drawing");
assert!(folder.is_some(), "the folder's table, with its red Color_1");
assert_ne!(folder, drawing, "each copy is of the table chosen");
}
#[test]
fn plotting_model_again_with_its_table_leaves_no_undo_step() {
let mut s = with_io();
s.execute("stylesmanager", &json!({"action": "new", "name": "again.ctb", "where": "folder"})).unwrap();
let undo = |s: &Session| s.state().unwrap().undo.len();
let plot = |s: &mut Session, table: &str| s.execute("plot", &json!({"layout": "Model", "plotStyleTable": table})).unwrap();
let before = undo(&s);
plot(&mut s, "None");
assert_eq!(undo(&s), before, "no table, as before: nothing to undo");
plot(&mut s, "again.ctb");
let after_first = undo(&s);
assert!(after_first > before, "the first plot keeps the table, and can be undone");
plot(&mut s, "again.ctb");
assert_eq!(undo(&s), after_first, "the same table again: nothing to undo");
}
#[test]
fn a_folder_rename_that_cant_remove_the_old_file_keeps_one_copy() {
let mut s = session();
s.execute("stylesmanager", &json!({"action": "new", "name": "stuck.ctb", "where": "folder"})).unwrap();
assert!(s.execute("stylesmanager", &json!({"action": "rename", "name": "stuck.ctb", "to": "freed", "where": "folder"})).is_err());
assert_eq!(source(&mut s, "stuck.ctb").as_deref(), Some("folder"), "the table keeps its old name");
assert!(source(&mut s, "freed.ctb").is_none(), "and isn't held twice");
}
-26
View File
@@ -23,29 +23,3 @@ fn purge_keeps_arrowhead_blocks_dimension_styles_name() {
let d = s.doc().unwrap();
assert!(d.block("_Dot").is_some() && d.block("MyArrow").is_some());
}
/// PURGE keeps the arrowhead block a leader's own override names (its DIMLDRBLK), as it keeps
/// the ones a dimension's overrides name (#3721).
#[test]
fn purge_keeps_the_arrowhead_block_a_leaders_override_names() {
use cadcraft_engine::doc::{Common, Leader, Space};
let mut s = Session::new();
let d = s.doc_mut().unwrap();
for (i, name) in ["MyArrow", "Unused"].into_iter().enumerate() {
let mut b = Block::new(name);
b.entities.push(Entity::new(Handle(0x9000 + i as u64), EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 0.5 })));
d.blocks.insert(name.into(), Arc::new(b));
}
let overrides = json!({ "leaderArrowBlock": "MyArrow" });
let leader = Leader {
vertices: vec![Vec3::ZERO, Vec3::new(10.0, 0.0, 0.0)],
arrow: true,
spline: false,
style: "Standard".into(),
overrides: overrides.as_object().cloned().unwrap_or_default(),
};
d.add(&Space::Model, Common::default(), EntityKind::Leader(leader)).unwrap();
let r = s.execute("purge", &json!({ "type": "blocks" })).unwrap();
assert_eq!(r["purged"]["blocks"], json!(["Unused"]), "{r}");
assert!(s.doc().unwrap().block("MyArrow").is_some());
}
+14
View File
@@ -36,6 +36,20 @@ pub use craft_fonts::{CRAFT_FONTS, CraftFont};
/// Name of the built-in font.
pub const BUILTIN_FONT: &str = "CADCraft Stroke";
/// Whether a style font name denotes an SHX font. An extensionless installed outline font keeps
/// its outline behavior; an unrecognized bare name is treated as an SHX name without `.shx`.
pub fn is_shx_name(name: &str) -> bool {
let name = name.trim();
if name.is_empty() || name.eq_ignore_ascii_case(BUILTIN_FONT) {
return false;
}
let file = name.rsplit(['/', '\\']).next().unwrap_or(name);
if let Some((_, extension)) = file.rsplit_once('.') {
return extension.eq_ignore_ascii_case("shx");
}
ttf::find(name).is_none()
}
/// One laid-out run of text: strokes in local coordinates (baseline at y = 0, x from 0).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Run {
+3
View File
@@ -37,6 +37,8 @@ use skrifa::{FontRef, GlyphId, MetadataProvider};
use crate::{Run, Shaped};
mod list;
pub use list::{FontEntry, installed_fonts};
#[cfg(not(target_arch = "wasm32"))]
mod dirs;
@@ -320,6 +322,7 @@ struct Fallback {
}
/// Where a font file's bytes come from.
#[derive(Clone)]
enum Source {
/// An installed font file, read on first use.
File(PathBuf),
+288
View File
@@ -0,0 +1,288 @@
//! The installed and registered fonts by family and style, as a font picker lists them. Only
//! each file's table directory and naming table are read, so listing every installed font is
//! cheap; the installed fonts are listed once per process.
use std::io::{Read, Seek, SeekFrom};
use std::sync::{Arc, OnceLock};
use skrifa::FontRef;
use skrifa::raw::tables::name::{Name, NameId};
use skrifa::raw::types::Tag;
use skrifa::raw::{FontData, FontRead};
use super::{Source, lock};
/// A font face a text style can name.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FontEntry {
/// The family ("Arial"): the typographic family when the font names one.
pub family: String,
/// The style within the family ("Regular", "Bold Italic").
pub style: String,
/// What a text style stores to use this face: its file name ("arialbd.ttf").
pub file: String,
}
/// Faces listed at most, and the longest family or style name kept.
const MAX_ENTRIES: usize = 5000;
const MAX_NAME_CHARS: usize = 128;
/// Bounds on what is read of one file: table records, and the naming table's size.
const MAX_TABLES: usize = 512;
const MAX_NAME_TABLE: usize = 1 << 20;
/// Every installed or registered font face (the first face of a collection), by family then
/// style (Regular, Italic, Bold, Bold Italic, then the rest by name). Fonts without a usable
/// naming table are left out.
pub fn installed_fonts() -> Vec<FontEntry> {
static INSTALLED: OnceLock<Vec<FontEntry>> = OnceLock::new();
// Registered fonts (web builds, tests) have no file; installed files loaded so far are
// listed from their paths.
let registered: Vec<(String, Arc<Vec<u8>>)> = {
let g = lock();
g.files.iter().filter(|(k, _)| !g.paths.contains_key(*k)).map(|(k, b)| (k.clone(), b.clone())).collect()
};
let installed = INSTALLED.get_or_init(|| {
let paths: Vec<(String, Source)> = lock().paths.iter().map(|(k, s)| (k.clone(), s.clone())).collect();
let mut out = Vec::new();
for (stem, source) in paths {
let entry = match source {
Source::File(path) => file_names(&path).map(|(family, style)| {
let file = path.file_name().map(|f| f.to_string_lossy().to_ascii_lowercase()).unwrap_or_else(|| format!("{stem}.ttf"));
FontEntry { family, style, file }
}),
Source::Static(bytes) => memory_names(bytes).map(|(family, style)| FontEntry { family, style, file: format!("{stem}.ttf") }),
};
out.extend(entry);
if out.len() >= MAX_ENTRIES {
break;
}
}
out
});
let mut all = installed.clone();
for (stem, bytes) in registered {
if let Some((family, style)) = memory_names(&bytes) {
all.push(FontEntry { family, style, file: format!("{stem}.ttf") });
}
}
sorted(all)
}
/// `entries` sorted, one per family and style (the first file listed wins).
fn sorted(mut entries: Vec<FontEntry>) -> Vec<FontEntry> {
entries.sort_by(|a, b| {
a.family.to_lowercase().cmp(&b.family.to_lowercase()).then(style_rank(&a.style).cmp(&style_rank(&b.style))).then(a.file.cmp(&b.file))
});
entries.dedup_by(|a, b| a.family.eq_ignore_ascii_case(&b.family) && a.style.eq_ignore_ascii_case(&b.style));
entries.truncate(MAX_ENTRIES);
entries
}
/// Regular, Italic, Bold and Bold Italic first, as AutoCAD's Font Style list has them.
fn style_rank(style: &str) -> (usize, String) {
let s = style.to_lowercase();
let rank = ["regular", "italic", "bold", "bold italic"].iter().position(|r| *r == s).unwrap_or(4);
(rank, s)
}
/// (family, style) of a font file's first face, reading only its table directory and naming
/// table.
fn file_names(path: &std::path::Path) -> Option<(String, String)> {
let mut f = std::fs::File::open(path).ok()?;
let mut read = |offset: u64, len: usize| -> Option<Vec<u8>> {
f.seek(SeekFrom::Start(offset)).ok()?;
let mut buf = vec![0u8; len];
f.read_exact(&mut buf).ok()?;
Some(buf)
};
names_from(&mut read)
}
/// (family, style) of the first face of font bytes held in memory.
fn memory_names(bytes: &[u8]) -> Option<(String, String)> {
let font = FontRef::from_index(bytes, 0).ok()?;
let data = font.table_data(Tag::new(b"name"))?;
family_and_style(data.as_bytes())
}
/// (family, style) of the first face of a font file read through `read(offset, len)`: the sfnt
/// or collection header, the table records, then the naming table.
pub(super) fn names_from(read: &mut dyn FnMut(u64, usize) -> Option<Vec<u8>>) -> Option<(String, String)> {
let head = read(0, 12)?;
let mut face = 0u64;
if head.get(0..4)? == b"ttcf" {
// A collection: the offset of its first face's table directory.
let first = read(12, 4)?;
face = u64::from(be32(&first, 0)?);
}
let dir = if face == 0 { head } else { read(face, 12)? };
let tables = usize::from(be16(&dir, 4)?).min(MAX_TABLES);
let records = read(face + 12, tables * 16)?;
let (offset, len) = (0..tables).find_map(|i| {
let r = records.get(i * 16..i * 16 + 16)?;
(r.get(0..4)? == b"name").then(|| Some((be32(r, 8)?, be32(r, 12)?)))?
})?;
let len = usize::try_from(len).ok().filter(|l| *l > 0 && *l <= MAX_NAME_TABLE)?;
family_and_style(&read(u64::from(offset), len)?)
}
fn be16(b: &[u8], at: usize) -> Option<u16> {
Some(u16::from_be_bytes(b.get(at..at + 2)?.try_into().ok()?))
}
fn be32(b: &[u8], at: usize) -> Option<u32> {
Some(u32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?))
}
/// The family and style a naming table gives: the typographic family and subfamily (IDs 16, 17)
/// when present, else the family and subfamily (IDs 1, 2); English names preferred.
fn family_and_style(table: &[u8]) -> Option<(String, String)> {
let name = Name::read(FontData::new(table)).ok()?;
let data = name.string_data();
// Lower is better: Windows English, other Windows, Mac English, Unicode, anything else.
let rank = |platform: u16, language: u16| match (platform, language) {
(3, 0x0409) => 0,
(3, _) => 1,
(1, 0) => 2,
(0, _) => 3,
_ => 4,
};
let best = |id: NameId| -> Option<String> {
let mut found: Option<(u8, String)> = None;
for r in name.name_record().iter().filter(|r| r.name_id() == id) {
let rk = rank(r.platform_id(), r.language_id());
if found.as_ref().is_some_and(|(k, _)| *k <= rk) {
continue;
}
let Ok(s) = r.string(data) else { continue };
let s: String = s.chars().filter(|c| !c.is_control()).take(MAX_NAME_CHARS).collect();
let s = s.trim().to_string();
if !s.is_empty() {
found = Some((rk, s));
}
}
found.map(|(_, s)| s)
};
let family = best(NameId::TYPOGRAPHIC_FAMILY_NAME).or_else(|| best(NameId::FAMILY_NAME))?;
let style = best(NameId::TYPOGRAPHIC_SUBFAMILY_NAME).or_else(|| best(NameId::SUBFAMILY_NAME)).unwrap_or_else(|| "Regular".into());
Some((family, style))
}
#[cfg(test)]
mod tests {
use super::*;
fn be16v(v: &mut Vec<u8>, x: u16) {
v.extend_from_slice(&x.to_be_bytes());
}
/// A naming table with Windows English records (platform 3, encoding 1, UTF-16BE).
pub(crate) fn name_table(records: &[(u16, &str)]) -> Vec<u8> {
let mut strings = Vec::new();
let mut recs = Vec::new();
for (id, s) in records {
let bytes: Vec<u8> = s.encode_utf16().flat_map(u16::to_be_bytes).collect();
for v in [3u16, 1, 0x0409, *id, bytes.len() as u16, strings.len() as u16] {
be16v(&mut recs, v);
}
strings.extend(bytes);
}
let mut t = Vec::new();
for v in [0u16, records.len() as u16, (6 + recs.len()) as u16] {
be16v(&mut t, v);
}
t.extend(recs);
t.extend(strings);
t
}
/// An sfnt with only a naming table, or a collection of one such face.
pub(crate) fn font_with_names(records: &[(u16, &str)], collection: bool) -> Vec<u8> {
let name = name_table(records);
let base = if collection { 16u32 } else { 0 };
let mut out = Vec::new();
if collection {
out.extend_from_slice(b"ttcf");
out.extend_from_slice(&0x0001_0000u32.to_be_bytes());
out.extend_from_slice(&1u32.to_be_bytes());
out.extend_from_slice(&base.to_be_bytes());
}
out.extend_from_slice(&0x0001_0000u32.to_be_bytes());
for v in [1u16, 16, 0, 0] {
be16v(&mut out, v);
}
out.extend_from_slice(b"name");
out.extend_from_slice(&0u32.to_be_bytes());
out.extend_from_slice(&(base + 28).to_be_bytes());
out.extend_from_slice(&(name.len() as u32).to_be_bytes());
out.extend(name);
out
}
fn read_from(bytes: &[u8]) -> impl FnMut(u64, usize) -> Option<Vec<u8>> + '_ {
|offset, len| {
let start = usize::try_from(offset).ok()?;
bytes.get(start..start.checked_add(len)?).map(<[u8]>::to_vec)
}
}
#[test]
fn families_and_styles_come_from_the_naming_table() {
let plain = font_with_names(&[(1, "Test Sans Semibold"), (2, "Regular"), (16, "Test Sans"), (17, "Semibold")], false);
assert_eq!(names_from(&mut read_from(&plain)), Some(("Test Sans".into(), "Semibold".into())), "typographic names first");
let old = font_with_names(&[(1, "Old Face"), (2, "Bold Italic")], true);
assert_eq!(names_from(&mut read_from(&old)), Some(("Old Face".into(), "Bold Italic".into())), "a collection's first face");
assert_eq!(memory_names(&font_with_names(&[(1, "In Memory")], false)), Some(("In Memory".into(), "Regular".into())));
assert_eq!(names_from(&mut read_from(&font_with_names(&[(2, "Bold")], false))), None, "no family");
}
#[test]
fn styles_sort_as_autocad_lists_them() {
let e = |family: &str, style: &str, file: &str| FontEntry { family: family.into(), style: style.into(), file: file.into() };
let got = sorted(vec![
e("b", "Bold", "bb.ttf"),
e("B", "Light", "bl.ttf"),
e("b", "Regular", "b.ttf"),
e("a", "Regular", "a.ttf"),
e("b", "Bold Italic", "bz.ttf"),
e("B", "regular", "copy.ttf"),
e("b", "Italic", "bi.ttf"),
]);
let order: Vec<&str> = got.iter().map(|e| e.file.as_str()).collect();
assert_eq!(order, ["a.ttf", "b.ttf", "bi.ttf", "bb.ttf", "bz.ttf", "bl.ttf"]);
}
#[test]
fn hostile_font_files_never_panic() {
let good = font_with_names(&[(1, "Fine")], true);
let mut cases: Vec<Vec<u8>> = vec![Vec::new(), b"ttcf".to_vec(), vec![0xFF; 12], vec![0; 40]];
for cut in [3, 12, 15, 20, 30, 40, good.len() - 1] {
cases.push(good[..cut.min(good.len())].to_vec());
}
// A huge table count, a name table past the end, an absurd length.
let mut many = good.clone();
many[20..22].copy_from_slice(&u16::MAX.to_be_bytes());
cases.push(many);
let mut far = good.clone();
far[36..40].copy_from_slice(&u32::MAX.to_be_bytes());
cases.push(far);
let mut long = good.clone();
long[40..44].copy_from_slice(&u32::MAX.to_be_bytes());
cases.push(long);
let mut seed = 0x9E37_79B9u32;
for _ in 0..200 {
let mut b = good.clone();
for _ in 0..4 {
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
let i = seed as usize % b.len();
b[i] = (seed >> 24) as u8;
}
cases.push(b);
}
for c in &cases {
let _ = names_from(&mut read_from(c));
let _ = memory_names(c);
let _ = family_and_style(c);
}
}
}
+15 -236
View File
@@ -460,101 +460,24 @@ pub(crate) fn xdata<'a>(tags: &'a [Tag], app: &str) -> &'a [Tag] {
rest.get(..end).unwrap_or(&[])
}
/// Whether xdata group `t` is the string `name` (any case): what names a list when a `1002 {`
/// follows it.
fn is_list_name(t: &Tag, name: &str) -> bool {
t.code == 1000 && t.str().trim().eq_ignore_ascii_case(name)
}
/// Whether xdata group `t` is the control string `brace` (`{` or `}`).
fn is_brace(t: &Tag, brace: &str) -> bool {
t.code == 1002 && t.str().trim() == brace
}
/// How many groups the body of a list takes at the start of `body` (the groups after its
/// `1002 {`), and whether a `1002 }` closes it there; a list left open runs to the end of the
/// run. Nested braces belong to the body.
fn xdata_list_body(body: &[Tag]) -> (usize, bool) {
/// The groups inside `1000 <name>` `1002 {` … `1002 }` of an xdata run (nested braces kept).
pub(crate) fn xdata_list<'a>(x: &'a [Tag], name: &str) -> &'a [Tag] {
let Some(at) = x.iter().position(|t| t.code == 1000 && t.str().trim().eq_ignore_ascii_case(name)) else { return &[] };
let Some(open) = x.get(at + 1).filter(|t| t.code == 1002 && t.str().trim() == "{") else { return &[] };
let _ = open;
let body = x.get(at + 2..).unwrap_or(&[]);
let mut depth = 0usize;
for (i, t) in body.iter().enumerate() {
if is_brace(t, "{") {
depth += 1;
} else if is_brace(t, "}") {
if depth == 0 {
return (i, true);
if t.code == 1002 {
match t.str().trim() {
"{" => depth += 1,
"}" if depth == 0 => return body.get(..i).unwrap_or(&[]),
"}" => depth -= 1,
_ => {}
}
depth -= 1;
}
}
(body.len(), false)
}
/// The groups inside the first list `1000 <name>` `1002 {` … `1002 }` of an xdata run (nested
/// braces kept). The name and the opening brace are looked for together: a string that only
/// reads `<name>`, with no brace after it, starts no list and does not hide a list after it.
pub(crate) fn xdata_list<'a>(x: &'a [Tag], name: &str) -> &'a [Tag] {
let Some(at) = x.windows(2).position(|w| matches!(w, [n, open] if is_list_name(n, name) && is_brace(open, "{"))) else { return &[] };
let body = x.get(at + 2..).unwrap_or(&[]);
body.get(..xdata_list_body(body).0).unwrap_or(&[])
}
/// Move the name strings held at brace depth `depth` or deeper from `held` to the end of `kept`,
/// in the order they had. `held` is in order of depth, so those are its last ones: only they are
/// looked at, and a call that releases nothing costs one comparison.
fn release_held(held: &mut Vec<(usize, Tag)>, depth: usize, kept: &mut Vec<Tag>) {
let from = held.len() - held.iter().rev().take_while(|(d, _)| *d >= depth).count();
kept.extend(held.drain(from..).map(|(_, t)| t));
}
/// Remove every list `1000 <name>` `1002 {` … `1002 }` from an xdata run, each with its name
/// group and braces: the lists [`xdata_list`] reads, so what is modelled from one is not kept
/// raw beside it. Which groups make a list is read from the run as given: a name group with the
/// opening brace right after it. Every other group stays, a string that only reads `<name>` too.
///
/// What is left holds no such list. Where a removed list stood between a name string and an
/// opening brace, the two would read as a list once written next to each other; the string then
/// goes behind that group and the groups in braces right after it, to the first place where no
/// opening brace follows it. It stays inside the braces it stood in, so every group keeps its
/// nesting, and the groups in the braces stay where they are. One pass over the run.
pub(crate) fn remove_xdata_lists(x: &mut Vec<Tag>, name: &str) {
let mut kept: Vec<Tag> = Vec::with_capacity(x.len());
// Name strings that a removal left in front of an opening brace, each with the brace depth
// it stood at, until a group that is no opening brace comes at that depth.
let mut held: Vec<(usize, Tag)> = Vec::new();
// How many braces are open around the next group.
let mut depth = 0usize;
// Whether a list was removed right after the last group kept.
let mut joined = false;
let mut rest = x.as_slice();
while let Some((t, after)) = rest.split_first() {
rest = after;
let open = is_brace(t, "{");
if open && kept.last().is_some_and(|n| is_list_name(n, name)) {
if !joined {
kept.pop();
let (len, closed) = xdata_list_body(rest);
rest = rest.get(len + usize::from(closed)..).unwrap_or(&[]);
joined = true;
continue;
}
// The names were no list's in the run as given: keep them, away from the brace.
let names = kept.iter().rev().take_while(|n| is_list_name(n, name)).count();
held.extend(kept.drain(kept.len() - names..).map(|n| (depth, n)));
}
if open {
depth += 1;
} else {
// Before the brace that closes their group, or before any other group there.
release_held(&mut held, depth, &mut kept);
if is_brace(t, "}") {
depth = depth.saturating_sub(1);
}
}
kept.push(t.clone());
joined = false;
}
release_held(&mut held, 0, &mut kept);
*x = kept;
body
}
/// Owner handle of a record: the first 330 outside `102 {…}` groups.
@@ -571,18 +494,14 @@ pub(crate) fn owner(tags: &[Tag]) -> Option<String> {
None
}
/// The name of the list in a dimension's or leader's `ACAD` xdata that holds its overrides.
pub(crate) const DSTYLE_LIST: &str = "DSTYLE";
/// Per-dimension (and per-leader) overrides from the `ACAD` "DSTYLE" xdata: `1070 <code>`
/// followed by the value.
/// Per-dimension overrides from the `ACAD` "DSTYLE" xdata: `1070 <code>` followed by the value.
pub(crate) fn read_dstyle(
tags: &[Tag],
styles: &HashMap<String, String>,
blocks: &HashMap<String, String>,
ltypes: &HashMap<String, String>,
) -> serde_json::Map<String, Value> {
read_dimvar_list(xdata_list(xdata(tags, "ACAD"), DSTYLE_LIST), styles, blocks, ltypes)
read_dimvar_list(xdata_list(xdata(tags, "ACAD"), "DSTYLE"), styles, blocks, ltypes)
}
/// A style's [`NEWER_CODES`] variables from its `CADCRAFT` "DIMVARS" xdata.
@@ -1181,144 +1100,4 @@ mod tests {
assert!(is_named_frame(&unit, Vec3::ZERO, Vec3::new(1.0, 1e-12, 0.0), Vec3::new(-1e-12, 1.0, 0.0)));
assert!(!is_named_frame(&unit, Vec3::ZERO, Vec3::new(0.0, 1.0, 0.0), Vec3::new(-1.0, 0.0, 0.0)));
}
/// An xdata run from (code, value) pairs.
fn run(list: &[(i32, &str)]) -> Vec<Tag> {
list.iter().map(|(code, value)| Tag::s(*code, *value)).collect()
}
/// `x` without its DSTYLE lists.
fn without_dstyle(mut x: Vec<Tag>) -> Vec<Tag> {
remove_xdata_lists(&mut x, DSTYLE_LIST);
x
}
/// Whether a run still holds a list [`xdata_list`] would read: a DSTYLE name group followed
/// by an opening brace.
fn has_dstyle_list(x: &[Tag]) -> bool {
x.windows(2).any(|w| matches!(w, [a, b] if a.code == 1000 && a.str() == DSTYLE_LIST && b.code == 1002 && b.str() == "{"))
}
/// A string that only has a list's name starts no list: the list after it is still read,
/// and removing the lists takes that list and leaves the string.
#[test]
fn a_loose_name_string_does_not_hide_the_list_after_it() {
let list = [(1000, "DSTYLE"), (1002, "{"), (1070, "41"), (1040, "1.5"), (1002, "}")];
for before in [vec![(1000, "DSTYLE"), (1070, "7")], vec![(1000, "DSTYLE")]] {
let mut x = run(&before);
x.extend(run(&list));
x.push(Tag::s(1000, "TAIL"));
assert_eq!(xdata_list(&x, DSTYLE_LIST), run(&[(1070, "41"), (1040, "1.5")]), "{before:?}");
let mut want = run(&before);
want.push(Tag::s(1000, "TAIL"));
assert_eq!(without_dstyle(x), want, "{before:?}");
}
// A name string with no list anywhere is no list and stays.
let loose = run(&[(1000, "DSTYLE"), (1070, "7")]);
assert!(xdata_list(&loose, DSTYLE_LIST).is_empty());
assert_eq!(without_dstyle(loose.clone()), loose);
}
/// Removing takes each list whole: its nested braces with it, and a list left open to the
/// end of the run.
#[test]
fn removing_lists_takes_nested_braces_and_an_unclosed_list() {
let nested = [(1000, "DSTYLE"), (1002, "{"), (1002, "{"), (1070, "1"), (1002, "}"), (1070, "2")];
let mut closed = run(&[(1000, "A")]);
closed.extend(run(&nested));
closed.extend(run(&[(1002, "}"), (1000, "B")]));
assert_eq!(xdata_list(&closed, DSTYLE_LIST), run(&nested[2..]));
assert_eq!(without_dstyle(closed), run(&[(1000, "A"), (1000, "B")]));
let mut open = run(&[(1000, "A")]);
open.extend(run(&nested));
assert_eq!(xdata_list(&open, DSTYLE_LIST), run(&nested[2..]));
assert_eq!(without_dstyle(open), run(&[(1000, "A")]));
}
/// The groups of `x`, each with how many braces are open around it, in a fixed order: for
/// comparing what two runs hold and how deep, whatever their order.
fn sorted(x: &[Tag]) -> Vec<(i32, String, usize)> {
let mut depth = 0usize;
let mut out = Vec::with_capacity(x.len());
for t in x {
if t.code == 1002 && t.str() == "}" {
depth = depth.saturating_sub(1);
}
out.push((t.code, t.str(), depth));
if t.code == 1002 && t.str() == "{" {
depth += 1;
}
}
out.sort();
out
}
/// Removing takes the lists of the run as given and nothing else. Where a removed list stood
/// between a name string and an opening brace, the groups in those braces are no list's and
/// stay; every group kept is as deep in braces as it was; what is left still holds no list,
/// and removing again changes nothing (a file written from it reads the same).
#[test]
fn removing_lists_keeps_the_groups_that_become_adjacent() {
let list = [(1000, "DSTYLE"), (1002, "{"), (1070, "41"), (1040, "1.5"), (1002, "}")];
let group = [(1002, "{"), (1000, "KEEP"), (1002, "}")];
let loose = (1000, "DSTYLE");
let (open, close) = ((1002, "{"), (1002, "}"));
// Each case: the run, and how many groups its lists take.
let cases: Vec<(Vec<(i32, &str)>, usize)> = vec![
// One loose name string before the list, an unnamed group after it.
([&[loose][..], &list, &group, &[(1000, "B")]].concat(), list.len()),
// Two loose strings, in lower case too (names are read in any case).
([&[(1000, "dstyle"), loose][..], &list, &group].concat(), list.len()),
// Two lists, one after the other, between the string and the group.
([&[(1000, "A"), loose][..], &list, &list, &group, &group].concat(), 2 * list.len()),
// A list after the group as well: the string must not land in front of it.
([&[loose][..], &list, &group, &list, &group].concat(), 2 * list.len()),
// The string right before a group in the run as given is that list's name.
([&[(1000, "A")][..], &[loose], &group, &list, &group].concat(), 1 + group.len() + list.len()),
// All of it inside an outer group: the string must stay inside that group.
([&[open, loose][..], &list, &group, &[close, (1000, "B")]].concat(), list.len()),
// Two deep, with a second group after the first and one more string outside.
([&[open, open, loose][..], &list, &group, &group, &[close, close, loose]].concat(), list.len()),
// Strings held at three depths at once, each released inside its own group.
([&[loose, loose, open, close, open].repeat(3)[..], &group, &[(1000, "B"), close, close, close]].concat(), 9),
// An outer group that is never closed.
([&[open, (1000, "A"), loose][..], &list, &list, &group].concat(), 2 * list.len()),
];
for (case, removed) in cases {
let x = run(&case);
let left = without_dstyle(x.clone());
assert!(!has_dstyle_list(&left) && xdata_list(&left, DSTYLE_LIST).is_empty(), "{case:?}: {left:?}");
assert_eq!(left.len(), x.len() - removed, "{case:?}: only the lists' groups went: {left:?}");
assert!(left.windows(3).any(|w| w == run(&group)), "{case:?}: the unnamed group is whole: {left:?}");
let mut before = sorted(&x);
for g in sorted(&left) {
let at = before.iter().position(|b| *b == g);
assert!(at.is_some(), "{case:?}: {g:?} is new, or not as deep in braces as it was: {left:?}");
before.remove(at.unwrap_or_default());
}
assert_eq!(without_dstyle(left.clone()), left, "{case:?}: removing again changes nothing");
}
// The first case, group by group: the loose string is behind the braces it stood before.
let left = without_dstyle(run(&[&[loose][..], &list, &group, &[(1000, "B")]].concat()));
assert_eq!(left, run(&[(1002, "{"), (1000, "KEEP"), (1002, "}"), (1000, "DSTYLE"), (1000, "B")]));
// Inside an outer group it stays inside it, before the brace that closes that group.
let left = without_dstyle(run(&[&[open, loose][..], &list, &group, &[close, (1000, "B")]].concat()));
assert_eq!(left, run(&[open, open, (1000, "KEEP"), close, loose, close, (1000, "B")]));
}
/// Many lists one after another are all removed and the groups around and between them stay
/// in order (one pass over the run: the count here is far past what one object may hold).
#[test]
fn many_consecutive_lists_are_removed() {
const LISTS: usize = 60_000;
let mut x = run(&[(1000, "HEAD")]);
for i in 0..LISTS {
x.extend(run(&[(1000, "DSTYLE"), (1002, "{"), (1070, "41"), (1002, "}")]));
if i % 20_000 == 0 {
x.push(Tag::s(1070, i.to_string()));
}
}
x.push(Tag::s(1000, "TAIL"));
assert_eq!(without_dstyle(x), run(&[(1000, "HEAD"), (1070, "0"), (1070, "20000"), (1070, "40000"), (1000, "TAIL")]));
}
}
+55 -51
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};
@@ -68,21 +70,13 @@ fn modelled_xdict_key(key: &str, of_insert: bool) -> bool {
/// Applications whose xdata CADCraft reads and writes itself
/// ([`cadcraft_doc::RESERVED_XDATA_APPS`]). `ACAD` holds dimension overrides (DSTYLE) on
/// dimensions and dimension styles; elsewhere it is kept. On a leader only its DSTYLE list is
/// CADCraft's own (the leader's overrides, see [`leader_acad_rest`]); the rest of the run is kept.
/// dimensions and dimension styles; elsewhere it is kept.
const OWN_APPS: &[&str] = cadcraft_doc::RESERVED_XDATA_APPS;
/// A LEADER's `ACAD` run (`chunk`, from its `1001` group on) without its DSTYLE lists, which
/// are read into the leader's overrides and written from them. Empty when nothing else is in
/// the run: then there is nothing to keep.
fn leader_acad_rest(chunk: &[Tag]) -> Vec<Tag> {
let mut rest = chunk.to_vec();
crate::dxf_ext::remove_xdata_lists(&mut rest, crate::dxf_ext::DSTYLE_LIST);
if rest.len() < chunk.len() && rest.len() <= 1 { Vec::new() } else { rest }
}
/// 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.
@@ -287,10 +281,7 @@ fn foreign_xdata(kind: &str, tags: &[Tag]) -> Vec<RawTag> {
i += 1 + len;
let app = first.str_ref().map(up).unwrap_or_default();
let own = OWN_APPS.contains(&app.as_str()) || (app == "ACAD" && matches!(kind, "DIMENSION" | "DIMSTYLE"));
// A leader's DSTYLE list is modelled (its overrides); the rest of its `ACAD` run is kept.
let split = (app == "ACAD" && kind == "LEADER").then(|| leader_acad_rest(chunk));
let chunk = split.as_deref().unwrap_or(chunk);
if app.is_empty() || own || chunk.is_empty() || out.len() + chunk.len() > MAX_XDATA_GROUPS {
if app.is_empty() || own || out.len() + chunk.len() > MAX_XDATA_GROUPS {
continue;
}
let mut depth = 0i32;
@@ -345,9 +336,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)
@@ -2320,14 +2359,8 @@ fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: Opti
rest.iter().position(|t| t.code == 102 && t.str().trim() == "}").map(|e| s + 1 + e)
});
let xdict_at = if h.has_reactors { reactors_end.or(handle_at) } else { handle_at };
// A leader's kept `ACAD` groups go at the end of the `ACAD` run written for its overrides.
let joined = x.filter(|_| r.kind == "LEADER" && own_apps.contains("ACAD")).map(|x| kept_acad_rest(map, x)).filter(|g| !g.is_empty());
let join_at = joined.as_ref().map(|_| acad_run_end(b));
let mut seen_owner = false;
for (i, t) in b.iter().enumerate() {
if Some(i) == join_at {
out.extend(joined.iter().flatten().cloned());
}
if i == props_at
&& let Some(x) = x
{
@@ -2377,9 +2410,6 @@ fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: Opti
map.handle_group(out, "ACAD_XDICTIONARY", 360, &[xd.hex()]);
}
}
if join_at == Some(b.len()) {
out.extend(joined.into_iter().flatten());
}
if let Some(x) = x {
if props_at == b.len() {
if let Some((want, book)) = &x.color_book
@@ -2449,32 +2479,6 @@ fn join_entries(map: &Map, b: &[Tag], kept: &ForeignObject, out: &mut Vec<Tag>)
}
}
/// The index after the last group of written record `b`'s `ACAD` xdata run (the end of the
/// record when it has none).
fn acad_run_end(b: &[Tag]) -> usize {
let Some(start) = b.iter().position(|t| t.code == 1001 && up(&t.str()) == "ACAD") else { return b.len() };
b.iter().skip(start + 1).position(|t| t.code == 1001).map_or(b.len(), |n| start + 1 + n)
}
/// The groups kept for a leader under `ACAD` (without the `1001` groups), handles remapped, for
/// the `ACAD` run the writer made from the leader's overrides: an application's data is one run
/// on a record, so [`xdata`] leaves these out there. A DSTYLE list among them is left out: the
/// run already holds the one the overrides give. (The reader keeps none, and `entmod`, `entmake`
/// and `properties.set` refuse one; this guards kept data that reached the leader another way.)
fn kept_acad_rest(map: &Map, x: &ForeignExtra) -> Vec<Tag> {
let mut out = Vec::new();
let mut inside = false;
for r in &x.xdata {
if r.code == 1001 {
inside = up(&r.value) == "ACAD";
} else if inside {
out.push(map.group(r));
}
}
crate::dxf_ext::remove_xdata_lists(&mut out, crate::dxf_ext::DSTYLE_LIST);
out
}
/// Kept xdata of applications the record doesn't already carry, handles remapped.
fn xdata(map: &Map, x: &ForeignExtra, own: &HashSet<String>, out: &mut Vec<Tag>) {
let mut skip = false;
+2 -3
View File
@@ -25,8 +25,8 @@ mod tables;
mod text;
use document::{
HandlePolicy, append, apply_sortents, count_skipped, drop_followed_attrib_layers, dropped_paper_views, out_of_memory, outside_sections,
parse_entities, place_blocks, place_entities, read_blocks, read_objects, setup_layouts,
HandlePolicy, append, apply_sortents, count_skipped, dropped_paper_views, out_of_memory, outside_sections, parse_entities, place_blocks,
place_entities, read_blocks, read_objects, setup_layouts,
};
#[cfg(test)]
use entities::acad_table;
@@ -299,7 +299,6 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize,
// are numbered above it and rebuilt on save, so following $HANDSEED would drift every save.
let own_seed = objs.xrecord_text(crate::dxf_ext::HANDSEED_KEY).and_then(|t| Handle::parse_hex(t.trim()));
let (paper_block_for, first_layout) = setup_layouts(&mut d, &mut layout_objs, &rx);
drop_followed_attrib_layers(&mut blocks, &mut entities);
place_blocks(&mut d, blocks, &mut rx, &paper_block_for, &first_layout)?;
place_entities(&mut d, entities, &rx, &paper_block_for, &first_layout)?;
draw_kept_dimensions_from_their_blocks(&mut d);
-25
View File
@@ -113,31 +113,6 @@ pub(super) fn ocs_n(n: Vec3, p: Vec3) -> Vec3 {
if (n.z - 1.0).abs() < 1e-12 && n.x.abs() < 1e-12 && n.y.abs() < 1e-12 { p } else { cadcraft_geom::Mat4::ocs(n).apply(p) }
}
/// Whether an extrusion direction leaves the Z axis — either way up — by more than noise: that is,
/// whether an entity's OCS points lie in a plane that is not parallel to the XY plane. The 1e-3 of
/// the normal's length is the tolerance the mirrored readers already allow, so an extrusion that
/// only carries noise is not a tilt.
///
/// Unlike [`tilted`], this asks about the plane rather than about how far a point moves: a text at
/// the origin barely moves under a tilt, but the direction it runs in plan does change.
pub(super) fn off_axis(n: Vec3) -> bool {
n.is_finite() && n.len() > 1e-12 && n.x.hypot(n.y) > 1e-3 * n.len()
}
/// The frame a tilted plane's points are drawn in when the entity cannot hold the plane and is
/// drawn flat, as seen from above: the matrix that takes a point in that plane to the WCS, and the
/// turn a direction at `turn` in the plane (group 50's angle) takes in plan. A direction seen
/// edge-on has no plan direction, so the file's turn is kept for it.
pub(super) fn plan_frame(n: Vec3, turn: f64) -> (cadcraft_geom::Mat4, f64) {
let m = cadcraft_geom::Mat4::ocs(n);
let ax = Vec3::new(m.m[0][0], m.m[1][0], m.m[2][0]);
let ay = Vec3::new(m.m[0][1], m.m[1][1], m.m[2][1]);
let (sin, cos) = turn.sin_cos();
let along = Vec2::new(ax.x * cos + ay.x * sin, ax.y * cos + ay.y * sin);
let angle = if along.len() > 1e-12 { along.y.atan2(along.x) } else { turn };
(m, angle)
}
/// Whether an object with OCS points `pts` (x, y and elevation) lies in a plane tilted off the
/// XY plane: drawing its points as plan coordinates (x flipped for a mirrored plane, as the
/// readers do) would put some of them off their place seen from above by more than a
+4 -46
View File
@@ -162,8 +162,9 @@ pub(super) fn parse_entities(
kindent = Some((c, k));
}
"INSERT" if t.i(66) == Some(1) => {
let ins_layer = kindent.as_ref().map(|(c, _)| c.layer.clone()).unwrap_or_default();
let left_tilted = kindent.as_ref().is_some_and(|(c, _)| reference_left_tilted(c.extrusion));
let attribs = insert_attribs(recs, &mut i, left_tilted);
let attribs = insert_attribs(recs, &mut i, &ins_layer, left_tilted);
if let Some((_, EntityKind::Insert(ins))) = kindent.as_mut() {
ins.attribs = attribs;
}
@@ -349,15 +350,6 @@ impl LayerSet {
d.layers.push(cadcraft_doc::Layer::new(name));
}
}
/// The layer `e` names, and those its block reference's attributes name for themselves.
fn ensure_entity(&mut self, d: &mut Drawing, e: &cadcraft_doc::Entity) {
self.ensure(d, &e.common.layer);
if let cadcraft_doc::EntityKind::Insert(ins) = &e.kind {
for l in ins.attribs.iter().filter_map(|a| a.props.layer.as_deref()) {
self.ensure(d, l);
}
}
}
}
/// The position of the first layout of each name, so finding the layout of each of many objects
@@ -388,7 +380,7 @@ pub(super) fn place_blocks(
if up == "*MODEL_SPACE" {
room_to_place(ents.len(), rx.entities_refused_past)?;
for (_, _, e) in ents {
layers.ensure_entity(d, &e);
layers.ensure(d, &e.common.layer);
d.model.push(e);
}
continue;
@@ -459,7 +451,7 @@ pub(super) fn place_entities(
let mut layers = LayerSet::new(d);
let layout_at = layout_positions(d);
for (owner, paper, e) in entities {
layers.ensure_entity(d, &e);
layers.ensure(d, &e.common.layer);
match paper_layout(owner, paper, rx, paper_block_for, first_layout) {
Some(lname) => {
if let Some(l) = layout_at.get(&lname).and_then(|&i| d.layouts.get_mut(i)) {
@@ -576,37 +568,3 @@ pub(super) fn apply_sortents(
}
}
}
/// An attribute on its reference's layer follows its definition's layer only where that is the
/// same layer (layer 0 being the reference's own): there it needs no layer of its own, and keeps
/// following the reference if that moves. Where the definition is on another layer, the layer the
/// attribute names stays its own. The blocks and entities are as read, before they are placed.
pub(super) fn drop_followed_attrib_layers(blocks: &mut [BlockDef], entities: &mut [(Option<String>, bool, Entity)]) {
// The first definition of each tag, by lower-cased block name. Of several BLOCK records of
// one name the last is the block that is kept ([`place_blocks`]), so it is the one that counts.
let mut defs: HashMap<String, HashMap<String, String>> = HashMap::new();
for (name, _, _, ents, _) in blocks.iter() {
let mut by_tag: HashMap<String, String> = HashMap::new();
for (_, _, e) in ents {
if let EntityKind::AttDef(a) = &e.kind {
by_tag.entry(a.tag.to_ascii_lowercase()).or_insert_with(|| e.common.layer.clone());
}
}
defs.insert(name.to_ascii_lowercase(), by_tag);
}
let drop_in = |e: &mut Entity| {
let EntityKind::Insert(ins) = &mut e.kind else { return };
let of_block = defs.get(&ins.block.to_ascii_lowercase());
for a in &mut ins.attribs {
let def = of_block.and_then(|m| m.get(&a.tag.to_ascii_lowercase())).map_or("0", String::as_str);
let follows = |l: &str| l.eq_ignore_ascii_case(&e.common.layer) && (def == "0" || def.eq_ignore_ascii_case(l));
if a.props.layer.as_deref().is_some_and(follows) {
a.props.layer = None;
}
}
};
for (_, _, _, ents, _) in blocks.iter_mut() {
ents.iter_mut().for_each(|(_, _, e)| drop_in(e));
}
entities.iter_mut().for_each(|(_, _, e)| drop_in(e));
}
+5 -36
View File
@@ -1,4 +1,4 @@
use super::common::{T, common, ocs, off_axis, plan_frame, plan_of_tilted, run_points, tilted};
use super::common::{T, common, ocs, plan_of_tilted, run_points, tilted};
use super::hatch::{CurvePoints, hatch};
use super::mtext_dxf;
use super::text::{attdef, attrib_modes, attrib_props, flatten_tilted, mtext_from, multiline_attrib, split_embedded, text_from};
@@ -304,32 +304,7 @@ pub(super) fn entity_with_table_budget(
"HELIX" => EntityKind::Helix(helix(tags)),
"RAY" => EntityKind::Ray(RayLine { base: t.p(10), dir: t.p(11) }),
"XLINE" => EntityKind::XLine(RayLine { base: t.p(10), dir: t.p(11) }),
"TEXT" => {
let mut tx = text_from(&t);
let n = c.extrusion;
// A text in a tilted plane: its insertion point, alignment point and rotation are in that
// plane's OCS, so reading them as WCS ones puts the text millions of units away in a
// drawing near UTM coordinates, and it runs the wrong way as well. Text cannot hold a
// tilted plane, so place it where the drawing has it as seen from above and turn it by
// the plane's x axis, as a tilted LWPOLYLINE is read (#1886, #2584).
//
// Only the Z-up plane is done here. A mirrored one (z < 0) is already taken apart by
// `text_from`'s `mirror_text`, which maps the anchors through the same frame and swaps
// the justification to keep the readable footprint; projecting them a second time would
// move them twice, and its swapped footprint needs the turn derived from the original
// OCS angle, which is a separate change.
if n.z >= 0.0 && off_axis(n) {
let (m, angle) = plan_frame(n, tx.rotation);
tx.insert = m.apply(tx.insert);
if let Some(a) = tx.align_pt.as_mut() {
*a = m.apply(*a);
}
tx.rotation = angle;
// Its points are plan coordinates now, so the plane it was drawn in is spent.
c.extrusion = Vec3::Z;
}
EntityKind::Text(tx)
}
"TEXT" => EntityKind::Text(text_from(&t)),
"MTEXT" => EntityKind::MText(mtext_from(tags, &c)),
"ATTDEF" => EntityKind::AttDef(attdef(tags, &mut c)),
"INSERT" => {
@@ -414,8 +389,6 @@ pub(super) fn entity_with_table_budget(
arrow: t.i(71).unwrap_or(1) != 0,
spline: t.i(72).unwrap_or(0) != 0,
style: t.s(3).unwrap_or_else(|| "Standard".into()),
// Its DSTYLE overrides need the file's handle maps: they follow in `entity_extras`.
overrides: Default::default(),
}),
// Names behind handles follow in `entity_extras` and `Objects::apply`.
"MULTILEADER" | "MLEADER" => EntityKind::MLeader(crate::dxf_mleader::read(tags)),
@@ -680,7 +653,7 @@ pub(super) fn entity_plot_style(tags: &[Tag], rx: &Rx) -> Option<String> {
by_block.then(|| "ByBlock".to_string())
}
/// Dimension and leader overrides, associativity, table references: data of an entity record that
/// Dimension overrides and associativity, table references: data of an entity record that
/// needs the file's handle maps.
pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityKind, rx: &mut Rx) {
match (kind, k) {
@@ -707,10 +680,6 @@ pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityK
dm.marks.oblique = Some(cadcraft_geom::norm_angle(base + o.to_radians()));
}
}
// A leader carries the same `ACAD` DSTYLE overrides as a dimension (#3721).
("LEADER", EntityKind::Leader(l)) => {
l.overrides = crate::dxf_ext::read_dstyle(tags, &rx.styles, &rx.brs, &rx.ltypes);
}
("ACAD_TABLE", EntityKind::Table(_)) => {
let t = T(tags);
if let Some(b) = t.s(2) {
@@ -860,7 +829,7 @@ pub(super) fn reference_left_tilted(n: Vec3) -> bool {
/// The ATTRIB records after an INSERT, advancing `i` past them and their SEQEND. Those of a
/// reference read as is in its tilted plane (`left_tilted`, [`reference_left_tilted`]) stay as
/// read with it.
pub(super) fn insert_attribs(recs: &[(String, &[Tag])], i: &mut usize, left_tilted: bool) -> Vec<Attrib> {
pub(super) fn insert_attribs(recs: &[(String, &[Tag])], i: &mut usize, ins_layer: &str, left_tilted: bool) -> Vec<Attrib> {
let mut attribs = Vec::new();
while let Some((k2, t2)) = recs.get(*i) {
if k2 == "ATTRIB" {
@@ -884,7 +853,7 @@ pub(super) fn insert_attribs(recs: &[(String, &[Tag])], i: &mut usize, left_tilt
invisible: own.i(70).unwrap_or(0) & 1 != 0,
constant: own.i(70).unwrap_or(0) & 2 != 0,
prompt: String::new(),
props: attrib_props(&tt),
props: attrib_props(&tt, ins_layer),
multiline,
modes: attrib_modes(own.0),
});
+5 -4
View File
@@ -1,12 +1,13 @@
use super::common::{T, common, ocs_n};
use super::{Attrib, AttribModes, AttribProps, Common, HAlign, MText, MultilineAttrib, Tag, Text, VAlign, Vec2, Vec3, mtext_dxf};
/// The properties an ATTRIB carries itself: those it has groups for, its layer (group 8) among
/// them even when it is its block reference's, as its definition may be on another layer.
pub(super) fn attrib_props(t: &T) -> AttribProps {
/// The properties an ATTRIB carries itself: those it has groups for. Its layer counts only when
/// it differs from its block reference's (an attribute defined on layer 0 goes on the reference's
/// layer, as it is drawn anyway).
pub(super) fn attrib_props(t: &T, insert_layer: &str) -> AttribProps {
let c = common(t);
AttribProps {
layer: t.s(8).filter(|l| !l.is_empty()),
layer: t.s(8).filter(|l| !l.is_empty() && !l.eq_ignore_ascii_case(insert_layer)),
color: (t.i(62).is_some() || t.i(420).is_some()).then_some(c.color),
linetype: t.s(6).filter(|l| !l.is_empty()),
lineweight: t.i(370).is_some().then_some(c.lineweight),
+4 -10
View File
@@ -143,9 +143,8 @@ pub(super) fn annotative_xdata(w: &mut W) {
w.s(1002, "}");
}
/// The `ACAD` DSTYLE xdata of a dimension's or a leader's style `overrides`: nothing when none
/// of them can be written.
pub(super) fn dstyle_xdata(w: &mut W, overrides: &serde_json::Map<String, serde_json::Value>, cx: &Ctx) {
/// Override (`ACAD` DSTYLE) and associativity (`CADCRAFT` ASSOC) xdata of a dimension.
pub(super) fn dim_xdata(w: &mut W, dm: &Dimension, cx: &Ctx) {
let mut ov = W {
t: Vec::new(),
next: 0,
@@ -158,7 +157,7 @@ pub(super) fn dstyle_xdata(w: &mut W, overrides: &serde_json::Map<String, serde_
xdicts: HashMap::new(),
};
let mut sah = false;
for (k, v) in overrides {
for (k, v) in &dm.overrides {
let Some(field) = DimStyle::field_name(k) else { continue };
let Some((code, kind)) = dxf_ext::dim_code(field) else { continue };
let Some(val) = dxf_ext::canonical(field, v) else { continue };
@@ -173,16 +172,11 @@ pub(super) fn dstyle_xdata(w: &mut W, overrides: &serde_json::Map<String, serde_
}
if !ov.t.is_empty() {
w.s(1001, "ACAD");
w.s(1000, dxf_ext::DSTYLE_LIST);
w.s(1000, "DSTYLE");
w.s(1002, "{");
w.xdata(ov.t);
w.s(1002, "}");
}
}
/// Override (`ACAD` DSTYLE) and associativity (`CADCRAFT` ASSOC) xdata of a dimension.
pub(super) fn dim_xdata(w: &mut W, dm: &Dimension, cx: &Ctx) {
dstyle_xdata(w, &dm.overrides, cx);
let mut ours = Vec::new();
if matches!(dm.kind, DimKind::ArcLength) {
ours.extend(dxf_ext::arclen_xdata(dm.p15));
+10 -6
View File
@@ -1,5 +1,5 @@
use super::blocks::table_size;
use super::common::{attrib_common, common, common_x, dim_xdata, dstyle_xdata, layer_and_props, multiline_tags, oblique_52, text_tags};
use super::common::{attrib_common, common, common_x, dim_xdata, layer_and_props, multiline_tags, oblique_52, text_tags};
use super::ctx::Ctx;
use super::layout::paper_view;
use super::{
@@ -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) => {
@@ -685,9 +692,6 @@ fn write_annotations_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, pap
for v in &l.vertices {
w.p(10, *v);
}
// Its overrides, as a dimension's. Other `ACAD` data kept for the leader joins this
// run when the file is finished (`dxf_raw`).
dstyle_xdata(w, &l.overrides, cx);
}
EntityKind::Image(i) => {
// Every image has its IMAGEDEF (planned in `write`); the fallback never happens.
@@ -943,7 +947,7 @@ fn mleader_fallback(w: &mut W, d: &Drawing, e: &Entity, m: &MLeader, owner: &str
for arm in m.leaders.iter().take(64) {
let mut vertices = arm.clone();
vertices.push(m.landing);
let le = part(w, EntityKind::Leader(Leader { vertices, arrow: true, spline: m.spline, style: style.clone(), overrides: Default::default() }));
let le = part(w, EntityKind::Leader(Leader { vertices, arrow: true, spline: m.spline, style: style.clone() }));
entity(w, d, &le, owner, paper, cx);
}
if let Some(t) = &m.text {
+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.
+6 -10
View File
@@ -1106,16 +1106,12 @@ fn arrow_block_definitions(
arrow_names.extend([s.arrow_block.clone(), s.arrow_block1.clone(), s.arrow_block2.clone(), s.leader_arrow_block.clone()]);
}
for e in every {
// The arrowheads a dimension's or a leader's own overrides name.
let overrides = match &e.kind {
EntityKind::Dimension(dm) => &dm.overrides,
EntityKind::Leader(l) => &l.overrides,
_ => continue,
};
for (k, v) in overrides {
let Some(f) = DimStyle::field_name(k).filter(|f| f.starts_with("arrowBlock") || *f == "leaderArrowBlock") else { continue };
if let Some(s) = dxf_ext::canonical(f, v).as_ref().and_then(|v| v.as_str()) {
arrow_names.push(s.to_string());
if let EntityKind::Dimension(dm) = &e.kind {
for (k, v) in &dm.overrides {
let Some(f) = DimStyle::field_name(k).filter(|f| f.starts_with("arrowBlock") || *f == "leaderArrowBlock") else { continue };
if let Some(s) = dxf_ext::canonical(f, v).as_ref().and_then(|v| v.as_str()) {
arrow_names.push(s.to_string());
}
}
}
}
+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.
-78
View File
@@ -3843,84 +3843,6 @@ fn mirrored_hatch_mirrors_its_pattern_lines() {
assert_eq!(dashes, vec![0.5, -0.25]);
}
/// A TEXT in a tilted Z-up plane keeps its insertion point, alignment point and rotation in that
/// plane's OCS, so read as WCS ones it lands millions of units away in a drawing near UTM
/// coordinates and runs the wrong way — the read-side counterpart of #1886, which #2584 fixed for
/// HATCH and LWPOLYLINE and left TEXT for a follow-up.
#[test]
fn tilted_text_is_placed_as_seen_from_above() {
// Extrusion (0.6,0,0.8): the OCS axes are x = (0,1,0) and y = (-0.8,0,0.6), so group 10
// (2000,-800,600) is WCS (1000,2000,0), and a text with group 50 = 0 is drawn turned 90°.
let text = "0\nSECTION\n2\nENTITIES\n0\nTEXT\n8\n0\n10\n2000\n20\n-800\n30\n600\n40\n2.5\n\
1\nSURVEY\n210\n0.6\n220\n0\n230\n0.8\n0\nENDSEC\n0\nEOF\n";
let d = read(text.as_bytes(), "t.dxf").unwrap();
let tx = first(&d, |k| if let EntityKind::Text(t) = k { Some(t.clone()) } else { None });
for (got, want) in [(tx.insert.x, 1000.0), (tx.insert.y, 2000.0), (tx.insert.z, 0.0)] {
assert!((got - want).abs() < 1e-9, "insert {:?}", tx.insert);
}
assert!((tx.rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-12, "{}", tx.rotation);
// Its points are plan coordinates now, so the plane is spent rather than kept on the entity.
assert_eq!(d.model.iter().next().unwrap().common.extrusion, Vec3::Z);
// The text takes up its place in the drawing instead of an area millions of units across.
let b = d.extents(&Space::Model);
for (got, want) in [(b.min.x, 1000.0), (b.min.y, 2000.0)] {
assert!((got - want).abs() < 10.0, "extents {b:?}");
}
// Saved flat in the WCS (no extrusion), it reads back in the same place.
let b2 = roundtrip(&d).extents(&Space::Model);
assert!((b2.min - b.min).len() < 1e-6 && (b2.max - b.max).len() < 1e-6, "{b2:?} vs {b:?}");
// A plain text and one whose extrusion only carries noise are untouched.
for ext in ["", "210\n0.0001\n220\n0\n230\n1\n"] {
let plain = format!("0\nSECTION\n2\nENTITIES\n0\nTEXT\n8\n0\n10\n5\n20\n7\n40\n2.5\n1\nOK\n{ext}0\nENDSEC\n0\nEOF\n");
let p = first(&read(plain.as_bytes(), "p.dxf").unwrap(), |k| if let EntityKind::Text(t) = k { Some(t.clone()) } else { None });
assert_eq!((p.insert.x, p.insert.y, p.insert.z), (5.0, 7.0, 0.0), "{ext:?}");
assert_eq!(p.rotation, 0.0, "{ext:?}");
}
}
/// The two operations the plain fixture cannot reach: a nonzero turn (group 50) puts weight on the
/// plane's y axis in `plan_frame`, and a justified text carries an alignment point (group 11) that
/// has to be mapped with the insertion point. Numbers worked out by hand from the arbitrary axis
/// algorithm: extrusion (0.6,0,0.8) gives x = (0,1,0) and y = (-0.8,0,0.6), so a turn of 45° runs
/// along (−0.8,1)/√2 in plan, which is (−0.624695, 0.780869) normalized.
#[test]
fn tilted_text_turns_by_the_plane_axes_and_maps_its_alignment_point() {
let text = "0\nSECTION\n2\nENTITIES\n0\nTEXT\n8\n0\n10\n2000\n20\n-800\n30\n600\n11\n2100\n21\n-800\n31\n600\n\
40\n2.5\n50\n45\n72\n2\n73\n0\n1\nRIGHT\n210\n0.6\n220\n0\n230\n0.8\n0\nENDSEC\n0\nEOF\n";
let d = read(text.as_bytes(), "r.dxf").unwrap();
let tx = first(&d, |k| if let EntityKind::Text(t) = k { Some(t.clone()) } else { None });
// Both anchors go through the same frame: (2000,-800,600) → (1000,2000,0) and
// (2100,-800,600) → (1000,2100,0).
for (got, want) in [(tx.insert.x, 1000.0), (tx.insert.y, 2000.0), (tx.insert.z, 0.0)] {
assert!((got - want).abs() < 1e-9, "insert {:?}", tx.insert);
}
let align = tx.align_pt.expect("a right-justified text keeps its alignment point");
for (got, want) in [(align.x, 1000.0), (align.y, 2100.0), (align.z, 0.0)] {
assert!((got - want).abs() < 1e-9, "align_pt {:?}", tx.align_pt);
}
// The direction is the plane's x axis turned by 45° in the plane, seen from above.
let (want_x, want_y) = (-0.624695, 0.780869);
assert!((tx.rotation.cos() - want_x).abs() < 1e-6, "cos {} (rotation {})", tx.rotation.cos(), tx.rotation);
assert!((tx.rotation.sin() - want_y).abs() < 1e-6, "sin {} (rotation {})", tx.rotation.sin(), tx.rotation);
}
/// A mirrored plane (z < 0) maps its anchors once, in `text_from`'s mirror path. The tilted branch
/// must leave those points alone: mapping them again would move the text twice. The mirrored
/// tilted plane's footprint is otherwise unchanged from main and is a separate change.
#[test]
fn mirrored_tilted_text_anchors_are_mapped_once() {
let raw = Vec3::new(2000.0, -800.0, 600.0);
let n = Vec3::new(0.6, 0.0, -0.8);
let text = "0\nSECTION\n2\nENTITIES\n0\nTEXT\n8\n0\n10\n2000\n20\n-800\n30\n600\n40\n2.5\n\
1\nMIRROR\n210\n0.6\n220\n0\n230\n-0.8\n0\nENDSEC\n0\nEOF\n";
let d = read(text.as_bytes(), "m.dxf").unwrap();
let tx = first(&d, |k| if let EntityKind::Text(t) = k { Some(t.clone()) } else { None });
let once = cadcraft_geom::Mat4::ocs(n).apply(raw);
let twice = cadcraft_geom::Mat4::ocs(n).apply(once);
assert!((tx.insert - once).len() < 1e-9, "insert {:?}: wanted {once:?} (mapped once), not {twice:?} (twice)", tx.insert);
}
/// Issue #1886: a HATCH in a tilted plane (a terrain face) is drawn as seen from above, not turned
/// about the origin. With extrusion (0, 0.5, -√3/2) the OCS axes are x = (-1,0,0) and
/// y = (0, √3/2, 1/2): the square (1,0)..(3,2) lies over (-3,0)..(-1,√3), from z 0 up to z 1.
-55
View File
@@ -206,58 +206,3 @@ fn attribute_on_layer_zero_stays_on_layer_zero() {
assert_eq!(layers_and_colors(&back), read, "{name}: attribute layers or colours changed");
}
}
/// A drawing with one INSERT on layer A in the model, whose block has an ATTDEF on layer C, and
/// an ATTRIB on `attrib_layer`; the layer table lists `table` only.
fn attrib_layer_dxf(attrib_layer: &str, table: &[&str]) -> String {
let layers: String = table.iter().map(|n| format!("0\nLAYER\n2\n{n}\n70\n0\n62\n3\n6\nCONTINUOUS\n")).collect();
format!(
"0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLAYER\n70\n{}\n{layers}0\nENDTAB\n0\nENDSEC\n\
0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n8\n0\n2\nBLK\n70\n2\n10\n0\n20\n0\n30\n0\n3\nBLK\n\
0\nATTDEF\n8\nC\n10\n0\n20\n1\n30\n0\n40\n1\n1\nx\n3\n\n2\nT1\n70\n0\n0\nENDBLK\n8\n0\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n0\nINSERT\n8\nA\n66\n1\n2\nBLK\n10\n0\n20\n0\n30\n0\n\
0\nATTRIB\n8\n{attrib_layer}\n10\n0\n20\n1\n30\n0\n40\n1\n1\nv\n2\nT1\n70\n0\n0\nSEQEND\n8\nA\n0\nENDSEC\n0\nEOF\n",
table.len()
)
}
fn attrib_layer_names(d: &Drawing) -> Vec<Option<String>> {
layers_and_colors(d).into_iter().map(|(l, _)| l).collect()
}
/// An ATTRIB on its reference's layer stays on it when its definition is on another layer.
#[test]
fn attribute_on_its_references_layer_does_not_follow_its_definition() {
let d = cadcraft_io::read(attrib_layer_dxf("A", &["0", "A", "C"]).as_bytes(), "t.dxf").expect("read");
let read = attrib_layer_names(&d);
assert_eq!(read, [Some("A".to_string())], "its own layer, not the definition's C");
let back = cadcraft_io::read(&cadcraft_io::write(&d, "t.dxf").expect("write"), "t.dxf").expect("reopen");
assert_eq!(attrib_layer_names(&back), read, "changed by a save");
}
/// A layer only an ATTRIB names is added to the layer table, and the attribute stays on it.
#[test]
fn layer_only_an_attribute_names_is_added() {
let d = cadcraft_io::read(attrib_layer_dxf("ONLYHERE", &["0", "A", "C"]).as_bytes(), "t.dxf").expect("read");
assert!(d.layer("ONLYHERE").is_some(), "layer missing from the table");
cadcraft_io::dwg_worker::allow_in_process();
for name in ["t.dxf", "t.dwg"] {
let back = cadcraft_io::read(&cadcraft_io::write(&d, name).expect("write"), name).expect("reopen");
assert!(back.layer("ONLYHERE").is_some(), "{name}: layer lost");
assert_eq!(attrib_layer_names(&back), [Some("ONLYHERE".to_string())], "{name}");
}
}
/// Of two BLOCK records of one name the last is the block the drawing keeps, so its definition
/// is the one an attribute is compared with: the first defines the tag on C, the kept one on
/// layer 0, and an ATTRIB on its reference's layer then needs no layer of its own.
#[test]
fn attribute_is_compared_with_the_block_definition_that_is_kept() {
let second = "0\nBLOCK\n8\n0\n2\nBLK\n70\n2\n10\n0\n20\n0\n30\n0\n3\nBLK\n\
0\nATTDEF\n8\n0\n10\n0\n20\n1\n30\n0\n40\n1\n1\nx\n3\n\n2\nT1\n70\n0\n0\nENDBLK\n8\n0\n";
let dxf = attrib_layer_dxf("A", &["0", "A", "C"]).replacen("0\nENDBLK\n8\n0\n", &format!("0\nENDBLK\n8\n0\n{second}"), 1);
let d = cadcraft_io::read(dxf.as_bytes(), "t.dxf").expect("read");
let kept: Vec<&str> = d.blocks.get("BLK").expect("block").entities.iter().map(|e| e.common.layer.as_str()).collect();
assert_eq!(kept, ["0"], "the last record is the block");
assert_eq!(attrib_layer_names(&d), [None], "follows its reference, as its definition is on layer 0");
}
@@ -1,341 +0,0 @@
//! A LEADER's own dimension-style overrides (its `ACAD` DSTYLE xdata, as on a DIMENSION) are
//! read into the leader, survive a save and are written once; other `ACAD` data on the leader
//! is kept beside them (#3721).
use cadcraft_color::Color;
use cadcraft_doc::{Common, DimStyle, Drawing, EntityKind, Leader, RawTag, Space};
use cadcraft_geom::Vec3;
use cadcraft_io::{SaveOptions, Version, read, read_dxf, write_dxf, write_with};
/// Shorthand for a test's fallible result.
type TestResult<T = ()> = Result<T, Box<dyn std::error::Error>>;
/// The name of the dimension style the leaders under test use: one with a large arrow.
const STYLE: &str = "BIG";
/// A leader along x with style [`STYLE`] and the given overrides.
fn leader(overrides: serde_json::Value) -> EntityKind {
EntityKind::Leader(Leader {
vertices: vec![Vec3::ZERO, Vec3::new(4.0, 0.0, 0.0), Vec3::new(10.0, 0.0, 0.0)],
arrow: true,
spline: false,
style: STYLE.into(),
overrides: overrides.as_object().cloned().unwrap_or_default(),
})
}
/// A drawing with style [`STYLE`] (a large arrow), a second style that names the `_ArchTick`
/// arrowhead (so a saved file has that block record) and one leader with `overrides`.
fn drawing(overrides: serde_json::Value) -> TestResult<Drawing> {
let mut d = Drawing::new_metric();
d.dim_styles.push(DimStyle { name: STYLE.into(), arrow_size: 120.0, ..DimStyle::default() });
d.dim_styles.push(DimStyle { name: "Ticks".into(), leader_arrow_block: "_ArchTick".into(), ..DimStyle::default() });
d.add(&Space::Model, Common::default(), leader(overrides))?;
Ok(d)
}
/// The groups of a DXF text as (code, value) pairs, both trimmed.
fn groups(text: &str) -> Vec<(String, String)> {
let lines: Vec<&str> = text.lines().collect();
lines.as_chunks::<2>().0.iter().map(|[code, value]| (code.trim().to_string(), value.trim().to_string())).collect()
}
/// DXF text of (code, value) pairs.
fn text_of(groups: &[(String, String)]) -> String {
groups.iter().map(|(code, value)| format!("{code}\n{value}\n")).collect()
}
/// Where the first LEADER record's groups lie in `groups`: from its `0` group up to the next one.
fn leader_record(groups: &[(String, String)]) -> TestResult<std::ops::Range<usize>> {
let start = groups.iter().position(|(code, value)| code == "0" && value == "LEADER").ok_or("no LEADER record")?;
let len = groups[start + 1..].iter().position(|(code, _)| code == "0").ok_or("LEADER record is not closed")?;
Ok(start..start + 1 + len)
}
/// The handle of the BLOCK_RECORD named `name` (any case) in a DXF's groups.
fn block_record_handle(groups: &[(String, String)], name: &str) -> TestResult<String> {
let mut handle = None;
let mut inside = false;
for (code, value) in groups {
match code.as_str() {
"0" => {
inside = value == "BLOCK_RECORD";
handle = None;
}
"5" if inside => handle = Some(value.clone()),
"2" if inside && value.eq_ignore_ascii_case(name) => return handle.ok_or_else(|| "BLOCK_RECORD without a handle".into()),
_ => {}
}
}
Err(format!("no BLOCK_RECORD {name}").into())
}
/// (code, value) pairs from string literals.
fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> {
list.iter().map(|(code, value)| (code.to_string(), value.to_string())).collect()
}
/// A DSTYLE list as another program writes it on a leader: DIMASZ (41) 1.5, DIMCLRD (176) red
/// and DIMLDRBLK (341) as the handle `tick` of a BLOCK_RECORD.
fn dstyle(tick: &str) -> Vec<(String, String)> {
pairs(&[
("1000", "DSTYLE"),
("1002", "{"),
("1070", "41"),
("1040", "1.5"),
("1070", "176"),
("1070", "1"),
("1070", "341"),
("1005", tick),
("1002", "}"),
])
}
/// A saved drawing whose leader (no overrides of ours) got the `ACAD` xdata `acad` builds from
/// the `_ArchTick` block record's handle, appended to its record as another program writes it.
fn dxf_with_leader_xdata(acad: impl Fn(&str) -> Vec<(String, String)>) -> TestResult<String> {
let mut g = groups(&write_dxf(&drawing(serde_json::json!({}))?));
let tick = block_record_handle(&g, "_ArchTick")?;
let at = leader_record(&g)?.end;
let mut run = pairs(&[("1001", "ACAD")]);
run.extend(acad(&tick));
g.splice(at..at, run);
Ok(text_of(&g))
}
/// The drawing's one leader and its entity.
fn the_leader(d: &Drawing) -> TestResult<(&cadcraft_doc::Entity, &Leader)> {
d.model
.iter()
.find_map(|e| match &e.kind {
EntityKind::Leader(l) => Some((e.as_ref(), l)),
_ => None,
})
.ok_or_else(|| "no leader".into())
}
/// The style a leader of `d` draws with: its dimension style with its overrides applied.
fn drawn_style(d: &Drawing) -> TestResult<DimStyle> {
let (_, l) = the_leader(d)?;
Ok(d.dim_style(&l.style).ok_or("the leader's style is missing")?.with_overrides(&l.overrides))
}
/// How many groups of the first LEADER record of DXF `text` are the pair (`code`, `value`).
fn count_in_leader(text: &str, code: &str, value: &str) -> TestResult<usize> {
let g = groups(text);
let rec = leader_record(&g)?;
Ok(g[rec].iter().filter(|(c, v)| c == code && v == value).count())
}
/// Whether kept xdata holds a string group with `value`.
fn has_string(xdata: &[RawTag], value: &str) -> bool {
xdata.iter().any(|t| t.code == 1000 && t.value.trim() == value)
}
/// A LEADER's DSTYLE list under `ACAD` is read into the leader's overrides and is not kept as
/// raw xdata beside them.
#[test]
fn a_leaders_dstyle_overrides_are_read() -> TestResult {
let d = read_dxf(dxf_with_leader_xdata(dstyle)?.as_bytes())?;
let (e, l) = the_leader(&d)?;
assert!(!l.overrides.is_empty(), "the leader's DSTYLE list is read into its overrides");
let style = d.dim_style(STYLE).ok_or("style missing")?;
let drawn = drawn_style(&d)?;
assert!(drawn.arrow_size < style.arrow_size, "DIMASZ override: {} < {}", drawn.arrow_size, style.arrow_size);
assert!((drawn.arrow_size - 1.5).abs() < 1e-12, "the arrow size the file gives: {}", drawn.arrow_size);
assert_eq!(drawn.dim_line_color, Color::Index(1), "DIMCLRD override");
assert_ne!(drawn.dim_line_color, style.dim_line_color);
assert!(drawn.leader_arrow_block.eq_ignore_ascii_case("_ArchTick"), "DIMLDRBLK by handle: {:?}", drawn.leader_arrow_block);
// Modelled, so not also kept as the leader's raw xdata.
assert!(!has_string(&e.common.xdata, "DSTYLE"), "{:?}", e.common.xdata);
Ok(())
}
/// A save writes the leader's overrides as one DSTYLE list in one `ACAD` run, and a reopen
/// reads the same overrides.
#[test]
fn a_leaders_overrides_survive_a_save_and_are_written_once() -> TestResult {
let first = read_dxf(dxf_with_leader_xdata(dstyle)?.as_bytes())?;
let saved = write_dxf(&first);
assert_eq!(count_in_leader(&saved, "1000", "DSTYLE")?, 1, "one DSTYLE list on the saved leader");
assert_eq!(count_in_leader(&saved, "1001", "ACAD")?, 1, "in one ACAD run");
let second = read_dxf(saved.as_bytes())?;
assert_eq!(drawn_style(&second)?, drawn_style(&first)?, "the leader draws the same after a save and reopen");
assert_ne!(drawn_style(&second)?, *second.dim_style(STYLE).ok_or("style missing")?, "and not as its bare style");
// A second save writes the same record: nothing piles up.
let again = write_dxf(&second);
assert_eq!(count_in_leader(&again, "1000", "DSTYLE")?, 1);
assert_eq!(count_in_leader(&again, "1001", "ACAD")?, 1);
Ok(())
}
/// Overrides set on a leader in the model are written and read back in every DXF version,
/// ASCII and binary.
#[test]
fn overrides_set_in_the_model_are_written_and_read_back() -> TestResult {
let overrides = serde_json::json!({
"arrowSize": 1.5,
"scale": 2.0,
"dimLineColor": serde_json::to_value(Color::Index(3))?,
"leaderArrowBlock": "_DotSmall",
});
// No dimension style names this arrowhead: the file gets its block record for the leader.
let d = drawing(overrides)?;
let want = drawn_style(&d)?;
let saved = write_dxf(&d);
assert_eq!(count_in_leader(&saved, "1000", "DSTYLE")?, 1);
assert_eq!(drawn_style(&read_dxf(saved.as_bytes())?)?, want);
// Every DXF version and both encodings carry them.
for version in Version::ALL {
for binary in [false, true] {
let bytes = write_with(&d, "leader.dxf", &SaveOptions { version: Some(version), binary })?;
assert_eq!(drawn_style(&read(&bytes, "leader.dxf")?)?, want, "{version:?} binary={binary}");
}
}
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
/// Overrides set on a leader in the model come back from every DWG version.
#[test]
fn overrides_set_in_the_model_survive_dwg() -> TestResult {
cadcraft_io::dwg_worker::allow_in_process();
let overrides = serde_json::json!({
"arrowSize": 1.5,
"scale": 2.0,
"dimLineColor": serde_json::to_value(Color::Index(3))?,
"leaderArrowBlock": "_DotSmall",
});
let d = drawing(overrides)?;
// The values the leader draws with: the ones its overrides set, not its whole style (other
// variables of a style have their own DWG limits).
let drawn = |d: &Drawing| -> TestResult<(f64, f64, Color, String)> {
let st = drawn_style(d)?;
Ok((st.arrow_size, st.scale, st.dim_line_color, st.leader_arrow_block.to_ascii_uppercase()))
};
let want = drawn(&d)?;
for version in Version::ALL {
let bytes = write_with(&d, "leader.dwg", &SaveOptions { version: Some(version), binary: false })?;
let back = read(&bytes, "leader.dwg")?;
assert_eq!(drawn(&back)?, want, "{version:?}");
let bare = back.dim_style(STYLE).ok_or("style missing")?;
assert!(drawn(&back)?.0 < bare.arrow_size, "{version:?}: the override, not the style's arrow size");
}
Ok(())
}
/// Other `ACAD` xdata on a leader is kept beside its overrides, and a leader whose `ACAD` run
/// has no DSTYLE list keeps the whole run.
#[test]
fn other_acad_xdata_on_a_leader_round_trips_beside_its_overrides() -> TestResult {
// Another list before the DSTYLE list and a loose string after it, in the same ACAD run.
let mixed = |tick: &str| {
let mut run = pairs(&[("1000", "REVISION"), ("1002", "{"), ("1070", "7"), ("1002", "}")]);
run.extend(dstyle(tick));
run.extend(pairs(&[("1000", "CHECKED")]));
run
};
let first = read_dxf(dxf_with_leader_xdata(mixed)?.as_bytes())?;
let (e, _) = the_leader(&first)?;
let kept = e.common.xdata.clone();
assert!(has_string(&kept, "REVISION") && has_string(&kept, "CHECKED"), "the other ACAD data is kept: {kept:?}");
assert!(!has_string(&kept, "DSTYLE"), "the DSTYLE list is modelled, not kept: {kept:?}");
let saved = write_dxf(&first);
for (value, what) in [("DSTYLE", "the overrides"), ("REVISION", "the other list"), ("CHECKED", "the loose string")] {
assert_eq!(count_in_leader(&saved, "1000", value)?, 1, "{what} once");
}
assert_eq!(count_in_leader(&saved, "1001", "ACAD")?, 1, "all in one ACAD run");
let second = read_dxf(saved.as_bytes())?;
let (e, _) = the_leader(&second)?;
assert_eq!(e.common.xdata, kept, "the kept ACAD data is unchanged by a save and reopen");
assert_eq!(drawn_style(&second)?, drawn_style(&first)?);
// A leader whose ACAD run has no DSTYLE list keeps the whole run, and gets no overrides.
let plain = |_: &str| pairs(&[("1000", "REVISION"), ("1002", "{"), ("1070", "7"), ("1002", "}")]);
let first = read_dxf(dxf_with_leader_xdata(plain)?.as_bytes())?;
let (e, l) = the_leader(&first)?;
assert!(l.overrides.is_empty());
let kept = e.common.xdata.clone();
assert!(has_string(&kept, "REVISION"));
let saved = write_dxf(&first);
assert_eq!(count_in_leader(&saved, "1000", "DSTYLE")?, 0);
assert_eq!(count_in_leader(&saved, "1001", "ACAD")?, 1);
let second = read_dxf(saved.as_bytes())?;
assert_eq!(the_leader(&second)?.0.common.xdata, kept);
Ok(())
}
/// A string that only reads "DSTYLE" before the leader's real DSTYLE list does not hide the
/// list: the overrides are read, the list is not kept raw beside them, and a save writes one
/// list (not a second one from the kept data) with the loose string still there.
#[test]
fn a_loose_dstyle_string_before_the_list_does_not_hide_it() -> TestResult {
let loose_first = |tick: &str| {
let mut run = pairs(&[("1000", "DSTYLE"), ("1070", "7")]);
run.extend(dstyle(tick));
run
};
let first = read_dxf(dxf_with_leader_xdata(loose_first)?.as_bytes())?;
let (e, l) = the_leader(&first)?;
assert!(!l.overrides.is_empty(), "the list after the loose string is read into the overrides");
assert!((drawn_style(&first)?.arrow_size - 1.5).abs() < 1e-12);
let kept = e.common.xdata.clone();
assert!(has_string(&kept, "DSTYLE"), "the loose string is kept: {kept:?}");
assert!(!kept.iter().any(|t| t.code == 1002), "the list is modelled, not kept: {kept:?}");
let saved = write_dxf(&first);
assert_eq!(count_in_leader(&saved, "1002", "{")?, 1, "one list on the saved leader");
assert_eq!(count_in_leader(&saved, "1000", "DSTYLE")?, 2, "its name and the loose string");
assert_eq!(count_in_leader(&saved, "1001", "ACAD")?, 1);
let second = read_dxf(saved.as_bytes())?;
assert_eq!(the_leader(&second)?.0.common.xdata, kept, "the kept data is unchanged by a save and reopen");
assert_eq!(drawn_style(&second)?, drawn_style(&first)?);
Ok(())
}
/// The kept `ACAD` groups of `xdata` after the `1001` group, each with how many braces are open
/// around it.
fn acad_depths(xdata: &[RawTag]) -> Vec<(i32, String, usize)> {
let mut depth = 0usize;
let mut out = Vec::new();
for t in xdata.iter().filter(|t| t.code != 1001) {
let value = t.value.trim().to_string();
if t.code == 1002 && value == "}" {
depth = depth.saturating_sub(1);
}
out.push((t.code, value.clone(), depth));
if t.code == 1002 && value == "{" {
depth += 1;
}
}
out
}
/// Other `ACAD` data in an outer group around the leader's DSTYLE list keeps its nesting: a
/// loose "DSTYLE" string before the list and a group after it both stay inside the outer group,
/// through a save and a reopen.
#[test]
fn other_acad_xdata_around_the_list_keeps_its_nesting() -> TestResult {
let nested = |tick: &str| {
let mut run = pairs(&[("1002", "{"), ("1000", "DSTYLE")]);
run.extend(dstyle(tick));
run.extend(pairs(&[("1002", "{"), ("1000", "KEEP"), ("1002", "}"), ("1002", "}"), ("1000", "AFTER")]));
run
};
let first = read_dxf(dxf_with_leader_xdata(nested)?.as_bytes())?;
let (e, l) = the_leader(&first)?;
assert!(!l.overrides.is_empty(), "the list inside the outer group is read into the overrides");
let kept = e.common.xdata.clone();
let depths = acad_depths(&kept);
let depth_of = |value: &str| depths.iter().find(|(code, v, _)| *code == 1000 && v == value).map(|(_, _, d)| *d);
assert_eq!(depth_of("DSTYLE"), Some(1), "the loose string is still inside the outer group: {kept:?}");
assert_eq!(depth_of("KEEP"), Some(2), "the inner group is still inside the outer group: {kept:?}");
assert_eq!(depth_of("AFTER"), Some(0), "what stood after the outer group is still after it: {kept:?}");
assert_eq!(depths.iter().filter(|(code, _, _)| *code == 1002).count(), 4, "only the list's braces went: {kept:?}");
let saved = write_dxf(&first);
assert_eq!(count_in_leader(&saved, "1000", "DSTYLE")?, 2, "the written list's name and the loose string");
assert_eq!(count_in_leader(&saved, "1001", "ACAD")?, 1);
let second = read_dxf(saved.as_bytes())?;
assert_eq!(the_leader(&second)?.0.common.xdata, kept, "the kept data is unchanged by a save and reopen");
assert_eq!(drawn_style(&second)?, drawn_style(&first)?);
Ok(())
}
@@ -18,7 +18,7 @@ fn drawing() -> TestResult<Drawing> {
] {
for arrow in [false, true] {
for spline in [false, true] {
let leader = Leader { vertices: vertices.clone(), arrow, spline, style: "Elevation".into(), overrides: Default::default() };
let leader = Leader { vertices: vertices.clone(), arrow, spline, style: "Elevation".into() };
d.add(&Space::Model, common.clone(), EntityKind::Leader(leader))?;
}
}
+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 -1
View File
@@ -54,13 +54,14 @@ mod layout_plot_flags;
#[cfg(not(target_arch = "wasm32"))]
mod layout_plot_settings;
mod layout_plot_window;
mod leader_dstyle_overrides;
mod leader_vertex_elevation;
#[cfg(not(target_arch = "wasm32"))]
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;
@@ -211,7 +211,6 @@ pub(crate) fn leaders(elevated: bool) -> Vec<Case> {
arrow,
spline,
style: "ISO-25".into(),
overrides: Default::default(),
}),
)
})
-2
View File
@@ -45,8 +45,6 @@ pub(crate) fn sub_ctx<'a>(ctx: &Ctx<'a>, e: &Entity, m: Mat3) -> Ctx<'a> {
// Proxy graphics are drawn as part of the block they are in; a block reference or a
// dimension sets its own block instead.
block: ctx.block,
// A block inside a dimension's block (an arrowhead) is an ordinary block.
dim_block: false,
}
}
+1 -15
View File
@@ -2,7 +2,7 @@ use super::display::Kind;
use super::draw::stroke_with;
use super::props::default_lineweight;
use super::text_entity::{layout_mtext_entity, place_text_entity, style_font, text_style};
use super::{Builder, Color, Ctx, DimGeometry, DimText, Drawing, Entity, EntityKind, Ink, LineRole, Lineweight, Vec2, dim, ink};
use super::{Builder, Color, Ctx, DimGeometry, DimText, Drawing, Entity, EntityKind, LineRole, Lineweight, Vec2, dim, ink};
/// The font settings of a dimension style's text style.
pub fn dim_text(d: &Drawing, st: &cadcraft_doc::DimStyle) -> DimText {
@@ -17,20 +17,6 @@ pub fn dimension_in(d: &Drawing, dm: &cadcraft_doc::Dimension) -> DimGeometry {
dim::dimension_geometry_with(dm, &style, d.header.f64("DIMSCALE", 1.0), &dim_text(d, &st))
}
/// The colour a dimension style colour variable (`color`: DIMCLRD, DIMCLRE, DIMCLRT) gives a part
/// of `e`: ByBlock is the object's own colour and ByLayer its layer's, as [`dimension`] resolves
/// them.
pub(crate) fn style_ink(ctx: &Ctx, e: &Entity, color: Color) -> Ink {
let layer_name = if e.common.layer == "0" { ctx.block_layer.as_deref().unwrap_or("0") } else { e.common.layer.as_str() };
let layer_color = ctx.layer_color(layer_name).unwrap_or(Color::Index(7));
let own = match e.common.color {
Color::ByLayer => layer_color,
Color::ByBlock => ctx.block_color,
c => c,
};
ink(color, layer_color, own)
}
/// `lw` / `lt` are the dimension's own lineweight and linetype (ByBlock in DIMLWD, DIMLWE,
/// DIMLTYPE, DIMLTEX1 and DIMLTEX2).
pub(crate) fn dimension(
+20 -39
View File
@@ -1,7 +1,5 @@
use super::blocks::{insert, proxy, sub_ctx};
use super::dim_draw::{
MAX_FILL_SOLIDS, MAX_FILL_TEXTS, block_text_box, dim_text_fill, dimension, dimension_in, solid_covers, starts_text_marks, style_ink,
};
use super::dim_draw::{MAX_FILL_SOLIDS, MAX_FILL_TEXTS, block_text_box, dim_text_fill, dimension, dimension_in, solid_covers, starts_text_marks};
use super::display::{Kind, NO_LAYER, VIEWPORT_CONTENT};
use super::linetype::Layout;
use super::props::{resolve, transparency};
@@ -103,8 +101,8 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
};
let tol = b.opts.tolerance / ctx.xf.scale_factor().max(1e-12);
let lw = if b.opts.lineweights { lw } else { 0.0 };
// Stroke a run with the entity's linetype in colour `col`, laid out as `how` says.
let stroke_in = |b: &mut Builder, col: Ink, pts: &[Vec2], how: Layout| match lt.as_ref().filter(|_| b.opts.linetypes) {
// Stroke a run with the entity's linetype, laid out as `how` says.
let stroke_as = |b: &mut Builder, pts: &[Vec2], how: Layout| match lt.as_ref().filter(|_| b.opts.linetypes) {
Some(lt) => {
let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12);
let dashes = linetype::apply_as(pts, lt, ltscale, min, how, b);
@@ -112,24 +110,22 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
for dash in dashes.unwrap_or_else(|| vec![pts.to_vec()]) {
if dash.len() == 1 {
if let Some(p) = dash.first() {
b.point(ctx, col, *p);
b.point(ctx, rgb, *p);
}
} else {
b.polyline(ctx, col, lw, &dash);
b.polyline(ctx, rgb, lw, &dash);
}
}
// Text and shapes embedded in the linetype (shapes when their SHX file is found), on
// a run whose dashes were laid out.
if b.opts.text && laid {
for sh in linetype_text::texts(ctx.d, pts, lt, ltscale, min, how) {
b.shaped(ctx, col, lw, &sh);
b.shaped(ctx, rgb, lw, &sh);
}
}
}
None => b.polyline(ctx, col, lw, pts),
None => b.polyline(ctx, rgb, lw, pts),
};
// The same in the entity's own colour.
let stroke_as = |b: &mut Builder, pts: &[Vec2], how: Layout| stroke_in(b, rgb, pts, how);
let stroke = |b: &mut Builder, pts: &[Vec2]| stroke_as(b, pts, Layout::Open);
// A polyline's centre line: with PLINEGEN the pattern runs along the whole of it (stretched
// around a closed one from its second vertex, as AutoCAD lays it); otherwise it restarts at
@@ -237,14 +233,15 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
EntityKind::Tolerance(t) => tolerance::draw(b, ctx, e, t, lw, tol),
EntityKind::Leader(l) => {
let pts: Vec<Vec2> = l.vertices.iter().map(|v| v.xy()).collect();
// The leader's own DIMCLRD (an override in its DSTYLE xdata) colours its line and
// arrowhead, as a dimension's dimension line; without one it has its own colour.
let rgb = leader_color_override(ctx, e, l).unwrap_or(rgb);
stroke_in(b, rgb, &pts, Layout::Open);
stroke(b, &pts);
if l.arrow
&& let (Some(a), Some(n)) = (pts.first(), pts.get(1))
{
let (kind, size) = leader_arrow(ctx.d, l);
let st = ctx.d.dim_style(&l.style);
// DIMASZ × DIMSCALE of the leader's style (the drawing's DIMSCALE when it is 0).
let size = st.map(|s| s.arrow_size).unwrap_or(0.18) * leader_scale(ctx.d, st);
// DIMLDRBLK ("" = closed filled).
let kind = dim::Arrowhead::parse(st.map(|s| s.leader_arrow_block.as_str()).unwrap_or(""));
let g = dim::arrowhead(kind, *a, (*a - *n).normalized(), size);
for l in &g.lines {
b.polyline(ctx, rgb, lw, l);
@@ -257,9 +254,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
// Relative sizes follow the view: undo the block / viewport scale.
let view = b.opts.view_height / ctx.xf.scale_factor().max(1e-12);
let size = point::size(ctx.d.header.f64("PDSIZE", 0.0), view);
// A dimension's definition points are not point objects: always dots.
let mode = if ctx.dim_block { 0 } else { ctx.d.header.i64("PDMODE", 0) };
let fig = point::figure(mode, size, p.p.xy(), p.angle, tol);
let fig = point::figure(ctx.d.header.i64("PDMODE", 0), size, p.p.xy(), p.angle, tol);
if fig.dot {
b.point(ctx, rgb, p.p.xy());
}
@@ -398,7 +393,7 @@ fn draw_dimension(
// DXF group 12: a moved dimension keeps its `*D` block where it was and the offset in
// the insertion point, so the block draws translated by it (#2634).
let off = dm.insertion_point.xy();
let sub = Ctx { block: Some(blk), block_pstyle: b.named, block_transparency: own, dim_block: true, ..sub_ctx(ctx, e, Mat3::translate(off)) };
let sub = Ctx { block: Some(blk), block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, Mat3::translate(off)) };
// DIMTFILL: the block's MTEXT carries no background mask here, so a background
// around each of the block's texts is drawn before the block's first text or first
// line of the text's marks, except for a text that a SOLID of the block covers.
@@ -462,23 +457,9 @@ fn table(b: &mut Builder, ctx: &Ctx, t: &cadcraft_doc::Table, rgb: Ink, lw: f32)
table::draw(b, ctx, t, rgb, lw);
}
/// The arrowhead a leader draws at its first vertex and its size, from the leader's dimension
/// style with the leader's own overrides applied (as a dimension applies its overrides):
/// DIMLDRBLK ("" = closed filled), and DIMASZ × DIMSCALE (the drawing's DIMSCALE when the
/// style's is 0). A leader whose style is missing draws with the default style's values.
fn leader_arrow(d: &Drawing, l: &cadcraft_doc::Leader) -> (dim::Arrowhead, f64) {
let st = d.dim_style(&l.style).cloned().unwrap_or_default().with_overrides(&l.overrides);
let size = st.arrow_size * st.effective_scale(d.header.f64("DIMSCALE", 1.0));
(dim::Arrowhead::parse(&st.leader_arrow_block), size)
}
/// The colour a leader's own DIMCLRD override gives its line and arrowhead (ByBlock = the
/// leader's own colour, as on a dimension); `None` when the leader does not override DIMCLRD,
/// and it draws in its own colour.
fn leader_color_override(ctx: &Ctx, e: &Entity, l: &cadcraft_doc::Leader) -> Option<Ink> {
if !l.overrides.keys().any(|k| cadcraft_doc::DimStyle::field_name(k) == Some("dimLineColor")) {
return None;
}
let st = ctx.d.dim_style(&l.style).cloned().unwrap_or_default().with_overrides(&l.overrides);
Some(style_ink(ctx, e, st.dim_line_color))
/// The overall scale of a leader drawn with dimension style `st`: its DIMSCALE, else the
/// drawing's.
fn leader_scale(d: &Drawing, st: Option<&cadcraft_doc::DimStyle>) -> f64 {
let dimscale = d.header.f64("DIMSCALE", 1.0);
st.map(|s| s.effective_scale(dimscale)).unwrap_or_else(|| cadcraft_doc::DimStyle::default().effective_scale(dimscale))
}
-3
View File
@@ -109,9 +109,6 @@ struct Ctx<'a> {
/// The block whose contents are being drawn (`None` at the top level): a dimension in it whose
/// own block leads back to it is drawn from its definition points (see [`loops`]).
block: Option<&'a cadcraft_doc::Block>,
/// The entities drawn are a dimension's block: its POINT objects are the dimension's
/// definition points, drawn as dots whatever the point style (`PDMODE`).
dim_block: bool,
}
impl Ctx<'_> {
+3 -5
View File
@@ -146,12 +146,10 @@ pub fn model_unit_mm(page: &PageSetup) -> f64 {
}
/// The page a model-space plot starts from: ISO A4 in a drawing whose length unit is metric,
/// ANSI A otherwise, with the plot style table Model remembers. Model space keeps no other page
/// settings, so the plot takes its sheet (and its units) from here unless the caller picks
/// another paper.
/// ANSI A otherwise. Model space has no stored page setup, so the plot takes its sheet (and its
/// units) from here unless the caller picks another paper.
pub fn model_page(d: &Drawing) -> PageSetup {
let mut page =
PageSetup { plot_style_table: d.model_page.as_ref().map(|m| m.plot_style_table.clone()).unwrap_or_default(), ..PageSetup::default() };
let mut page = PageSetup::default();
if let Some(p) = paper_size(if metric_length_unit(d) { "A4" } else { "ANSI A" }) {
page.paper = p.name.into();
page.width_mm = p.width_mm;
-1
View File
@@ -102,7 +102,6 @@ pub(crate) fn top_ctx<'a>(d: &'a Drawing, xf: Mat3, top: Handle, frozen: &'a [St
block_pstyle: None,
block_transparency: 0,
block: None,
dim_block: false,
}
}
+1 -7
View File
@@ -2,8 +2,7 @@
//!
//! Plots (PDF) and layouts shown with "Display plot styles" (screen, PNG and SVG) draw each
//! object with the plot style that applies to it. In a colour-dependent table that is the style
//! of the object's index colour; a true colour uses the style of its nearest index colour,
//! except that the style's colour does not replace it. In a
//! of the object's index colour; a true colour uses the style of its nearest index colour. In a
//! named table it is the object's PlotStyle property: a style name, `ByLayer` (the layer's
//! style; layer 0 inside a block takes the reference's layer) or `ByBlock` (the block
//! reference's); names the table lacks print as `Normal`. The
@@ -94,11 +93,6 @@ impl Styler {
if s.keeps_color() {
return (ink, lw);
}
// A true colour is not replaced by the colour of a colour-dependent table's style: those
// colours are answers for index colours.
if ink.aci == 0 && !self.is_named() {
return (Ink { rgb: s.shade(ink.rgb), ..ink }, lw);
}
// Colour 7 is black on the paper the style prints on.
let base = if ink.aci7 { Rgb(0, 0, 0) } else { ink.rgb };
(Ink { rgb: s.apply_color(base), aci7: false, ..ink }, lw)
-279
View File
@@ -377,37 +377,6 @@ fn text_that_draws_nothing_has_no_extents() {
}
}
/// An underline is drawn below the baseline and an overline above the top of the line: the
/// extents hold them, however the text is justified, for plain text and for Aligned text, plain
/// or mirrored. A toggle that is off again before any character draws nothing and changes nothing.
#[test]
fn text_extents_hold_underlines_and_overlines() {
use cadcraft_doc::HAlign::{Aligned, Left};
use cadcraft_doc::VAlign::{Baseline, Bottom, Middle, Top};
for halign in [Left, Aligned] {
for valign in [Baseline, Bottom, Middle, Top] {
for flags in [(false, false), (false, true)] {
let of = |value: &str| drawn_and_extents_at(halign, valign, value, 1.0, 1.0, 20.0, flags);
let (plain_drawn, plain_extents) = of("AB");
// The last underlines only its second letter.
for value in ["%%uAB", "%%oAB", "%%u%%oAB", "A%%uB"] {
let (drawn, extents) = of(value);
assert!(
drawn.height() > plain_drawn.height(),
"{halign:?} {valign:?} {flags:?} {value:?}: the line is drawn outside the letters"
);
assert!(
extents.min.y <= drawn.min.y + 1e-6 && extents.max.y >= drawn.max.y - 1e-6,
"{halign:?} {valign:?} {flags:?} {value:?}: drawn {drawn:?} outside extents {extents:?}"
);
}
let (_, off) = of("%%u%%uAB");
assert_eq!((off.min.y, off.max.y), (plain_extents.min.y, plain_extents.max.y), "{halign:?} {valign:?} {flags:?}: no line, same box");
}
}
}
}
#[test]
fn hatch_pattern_and_solid() {
let mut d = Drawing::new_imperial();
@@ -2042,54 +2011,6 @@ fn mtext_background_mask_stays_paper_mask_under_monochrome_ctb() {
assert!(mask_idx < text_idx, "Kind::Mask must precede text under monochrome.ctb");
}
/// Through a colour-dependent plot style table that prints every index colour black, a line and
/// a solid hatch with a true colour keep that colour, white too and when the true colour is the
/// layer's, while the same objects in index colours print black.
#[test]
fn a_true_colour_keeps_its_colour_through_a_colour_dependent_table() {
let (white, orange) = (Rgb(255, 255, 255), Rgb(200, 100, 50));
let mut d = Drawing::new_metric();
d.layers.push(cadcraft_doc::Layer { name: "Orange".into(), color: Color::True(orange), ..Default::default() });
// One line and one solid hatch per row: true white, true orange, orange by the layer's true
// colour, index 7, index 1.
let rows = [
Common { color: Color::True(white), ..Default::default() },
Common { color: Color::True(orange), ..Default::default() },
Common { layer: "Orange".into(), ..Default::default() },
Common { color: Color::Index(7), ..Default::default() },
Common { color: Color::Index(1), ..Default::default() },
];
for (row, common) in rows.into_iter().enumerate() {
let y = row as f64;
let line = cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) };
d.add(&Space::Model, common.clone(), EntityKind::Line(line)).unwrap();
let fill = Hatch { solid: true, pattern: "SOLID".into(), ..pattern_hatch("SOLID", 1.0, (20.0, y - 0.2, 30.0, y + 0.2)) };
d.add(&Space::Model, common, EntityKind::Hatch(fill)).unwrap();
}
// The one colour of each row: its line and its hatch are drawn in the same colour.
let colours = |l: &DisplayList| -> Vec<Rgb> {
let row_of = |p: &DPrim| l.points(p).first().map(|q| q.y.round());
(0..5)
.map(|row| {
let mut seen: Vec<Rgb> = l.prims.iter().filter(|p| row_of(p) == Some(f64::from(row))).map(|p| p.color).collect();
assert!(seen.len() >= 2, "row {row}: a line and a fill");
seen.dedup();
assert_eq!(seen.len(), 1, "row {row}: {seen:?}");
seen[0]
})
.collect()
};
let black = Rgb(0, 0, 0);
let monochrome = Options {
plot_style_table: Some(std::sync::Arc::new(cadcraft_doc::PlotStyleTable::builtin("monochrome.ctb").unwrap())),
..Default::default()
};
assert_eq!(colours(&build_plot(&d, &Space::Model, &monochrome)), vec![white, orange, orange, black, black]);
// Without a table the true colours are the same, and index colour 1 is still red.
let plain = colours(&build_plot(&d, &Space::Model, &Options::default()));
assert_eq!((&plain[..3], plain[4]), (&[white, orange, orange][..], Rgb(255, 0, 0)));
}
#[test]
fn mtext_background_mask_resolves_bylayer_byblock_and_nonfinite_rotation() {
let mut d = Drawing::new_metric();
@@ -2249,125 +2170,6 @@ fn mtext_background_mask_resolves_bylayer_byblock_and_nonfinite_rotation() {
assert!(max_x - min_x > 8.0, "overflowing word background quad width ({}) must cover actual glyph strokes", max_x - min_x);
}
/// The background mask's triangle corners, and whether `p` lies in one of its triangles.
fn mask_tris(list: &DisplayList) -> Vec<cadcraft_geom::Vec2> {
let p = list.prims.iter().find(|p| p.kind == Kind::Mask).expect("background mask");
list.tris[p.start as usize..(p.start + p.len) as usize].to_vec()
}
fn masked(tris: &[cadcraft_geom::Vec2], p: cadcraft_geom::Vec2) -> bool {
tris.chunks(3).any(|t| {
let side = |a: cadcraft_geom::Vec2, b: cadcraft_geom::Vec2| (b - a).cross(p - a);
let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])];
s.iter().all(|v| *v >= 0.0) || s.iter().all(|v| *v <= 0.0)
})
}
fn masked_mtext(contents: &str, width: f64, rotation: f64, columns: Option<cadcraft_doc::MTextColumns>) -> cadcraft_doc::MText {
cadcraft_doc::MText {
insert: Vec3::new(3.0, 4.0, 0.0),
height: 1.0,
width,
attach: 1,
rotation,
style: "Standard".into(),
contents: contents.into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns,
background: Some(cadcraft_doc::MTextBackground { mask: 3, color: None, scale: 1.5 }),
}
}
#[test]
fn mtext_background_mask_leaves_the_gutter_between_columns_bare() {
let columns = cadcraft_doc::MTextColumns { count: 2, gutter: 4.0, height: 6.0, ..Default::default() };
for rotation in [0.0, 0.6] {
let t = masked_mtext(&"word ".repeat(12), 10.0, rotation, Some(columns.clone()));
let mut d = Drawing::new_metric();
d.add(&Space::Model, Common::default(), EntityKind::MText(t.clone())).unwrap();
let tris = mask_tris(&build(&d, &Space::Model, &Options::default()));
let at = t.insert.xy();
let world = |x: f64, y: f64| at + cadcraft_geom::Vec2::new(x, y).rotate(rotation);
// Columns 0..10 and 14..24, from the insertion point down to -6.
assert!(masked(&tris, world(5.0, -3.0)) && masked(&tris, world(19.0, -1.0)), "{rotation}: each column is masked");
assert!(!masked(&tris, world(12.0, -3.0)), "{rotation}: the gutter is not");
let l = layout_mtext_entity(&d, &t);
assert!(l.strokes.iter().flatten().all(|p| masked(&tris, *p)), "{rotation}: every stroke is behind the mask");
}
}
/// Text too wide for its column is drawn across the gutter: a stroke that starts in one column
/// and ends in the next is behind the mask along its whole length, not only at its two ends.
#[test]
fn mtext_background_mask_holds_a_stroke_that_runs_across_the_gutter() {
let columns = cadcraft_doc::MTextColumns { count: 2, gutter: 4.0, height: 6.0, ..Default::default() };
for rotation in [0.0, 0.6] {
// One underscore forty times its width: a single stroke far longer than the column.
let t = masked_mtext("{\\W40;_}", 10.0, rotation, Some(columns.clone()));
let mut d = Drawing::new_metric();
d.add(&Space::Model, Common::default(), EntityKind::MText(t.clone())).unwrap();
let tris = mask_tris(&build(&d, &Space::Model, &Options::default()));
let l = layout_mtext_entity(&d, &t);
let segments: Vec<[cadcraft_geom::Vec2; 2]> = l.strokes.iter().flat_map(|s| s.windows(2).map(|w| [w[0], w[1]])).collect();
// Columns 0..10 and 14..24 from the insertion point, before the rotation.
let across = |p: cadcraft_geom::Vec2| (p - t.insert.xy()).rotate(-rotation).x;
assert!(segments.iter().any(|[a, b]| across(*a) < 10.0 && across(*b) > 14.0), "{rotation}: a stroke crosses the gutter: {segments:?}");
for [a, b] in segments {
for i in 0..=16 {
let p = a + (b - a) * (f64::from(i) / 16.0);
assert!(masked(&tris, p), "{rotation}: {p:?} of the stroke {a:?} to {b:?} is not behind the mask");
}
}
}
}
#[test]
fn mtext_background_mask_quads_of_columns_turn_with_the_text() {
let columns = cadcraft_doc::MTextColumns { count: 2, gutter: 4.0, height: 6.0, ..Default::default() };
let tris_of = |rotation: f64| {
let t = masked_mtext(&"word ".repeat(12), 10.0, rotation, Some(columns.clone()));
let mut d = Drawing::new_metric();
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
mask_tris(&build(&d, &Space::Model, &Options::default()))
};
let (flat, turned) = (tris_of(0.0), tris_of(0.9));
assert!(flat.len() >= 12, "one quad per column");
assert_eq!(flat.len(), turned.len());
let at = cadcraft_geom::Vec2::new(3.0, 4.0);
for (a, b) in flat.iter().zip(&turned) {
let want = at + (*a - at).rotate(0.9);
assert!((want - *b).len() < 1e-6, "{a:?} turned about the insertion point is {want:?}, not {b:?}");
}
}
#[test]
fn mtext_background_mask_of_one_column_is_one_quad_as_before() {
// The quad the mask had before columns got their own: the layout's box, grown by the text
// drawn past it and by the border offset, turned by the rotation about the insertion point.
let one_quad = |d: &Drawing, t: &cadcraft_doc::MText| {
let u = layout_mtext_entity(d, &cadcraft_doc::MText { rotation: 0.0, ..t.clone() });
let mut bounds = u.bounds;
u.strokes.iter().flatten().for_each(|q| bounds.add(*q));
let gap = 0.5 * t.height;
let (lo, hi) = (bounds.min - cadcraft_geom::Vec2::new(gap, gap), bounds.max + cadcraft_geom::Vec2::new(gap, gap));
let (at, x) = (t.insert.xy(), cadcraft_geom::Vec2::from_angle(t.rotation));
let turn = |p: cadcraft_geom::Vec2| at + x * (p.x - at.x) + x.perp() * (p.y - at.y);
let [p0, p1, p2, p3] = [lo, cadcraft_geom::Vec2::new(hi.x, lo.y), hi, cadcraft_geom::Vec2::new(lo.x, hi.y)].map(turn);
vec![p0, p1, p2, p0, p2, p3]
};
let one_column = cadcraft_doc::MTextColumns { count: 1, gutter: 4.0, height: 3.0, ..Default::default() };
for t in [
masked_mtext("Typography, quickly jumping", 0.0, 0.0, None),
masked_mtext("Typography wraps, quickly jumping\\Pover lazy dogs", 6.0, 0.4, None),
masked_mtext(&"jumpy word ".repeat(9), 8.0, -0.3, Some(one_column.clone())),
] {
let mut d = Drawing::new_metric();
d.add(&Space::Model, Common::default(), EntityKind::MText(t.clone())).unwrap();
assert_eq!(mask_tris(&build(&d, &Space::Model, &Options::default())), one_quad(&d, &t), "{}", t.contents);
}
}
// ---------- point and primitive budgets (#1922, #1603) ----------
fn circle() -> EntityKind {
@@ -3022,84 +2824,3 @@ fn fills_cut_to_a_clip_region_past_the_fill_cap_are_left_out_and_mark_the_list()
let cut = built(&clipped_square(251, near_top));
assert!(cut.truncated && fill_area(&cut) == 0.0, "{}", fill_area(&cut));
}
// ---------- a leader's own dimension style overrides (#3721) ----------
/// A drawing with dimension style `BIG` (a large arrow) and one leader along x that uses it,
/// with the given overrides (DimStyle fields or DIM* names, as its DSTYLE xdata is read).
fn leader_drawing(overrides: serde_json::Value) -> Drawing {
let mut d = Drawing::new_imperial();
d.dim_styles.push(cadcraft_doc::DimStyle { name: "BIG".into(), arrow_size: 4.0, ..Default::default() });
let leader = cadcraft_doc::Leader {
vertices: vec![Vec3::ZERO, Vec3::new(20.0, 0.0, 0.0)],
arrow: true,
spline: false,
style: "BIG".into(),
overrides: overrides.as_object().cloned().unwrap_or_default(),
};
d.add(&Space::Model, Common::default(), EntityKind::Leader(leader)).unwrap();
d
}
/// The filled triangles a drawing's leader arrowhead draws.
fn leader_fill(d: &Drawing) -> Vec<Vec2> {
let l = build(d, &Space::Model, &Options::default());
l.prims.iter().filter(|p| p.kind == Kind::Tris).flat_map(|p| l.points(p).to_vec()).collect()
}
/// How far a drawing's filled leader arrowhead reaches along the leader.
fn leader_arrow_length(d: &Drawing) -> f64 {
cadcraft_geom::Bounds2::from_points(leader_fill(d)).width()
}
/// A leader's own DIMASZ and DIMSCALE overrides size its arrowhead, over its style's values.
#[test]
fn leader_arrow_size_and_scale_overrides_shrink_the_arrowhead() {
let plain = leader_arrow_length(&leader_drawing(serde_json::json!({})));
assert!(plain > 0.0);
let small = leader_arrow_length(&leader_drawing(serde_json::json!({ "arrowSize": 1.0 })));
assert!(small > 0.0 && small < plain, "DIMASZ override: {small} < {plain}");
// The file's spelling (a DIM* name) is the same override.
assert_eq!(leader_arrow_length(&leader_drawing(serde_json::json!({ "DIMASZ": 1.0 }))), small);
let scaled = leader_arrow_length(&leader_drawing(serde_json::json!({ "scale": 0.5 })));
assert!(scaled > 0.0 && scaled < plain, "DIMSCALE override: {scaled} < {plain}");
let both = leader_arrow_length(&leader_drawing(serde_json::json!({ "arrowSize": 1.0, "scale": 0.5 })));
assert!(both < small && both < scaled, "both overrides: {both} < {small}, {scaled}");
}
/// A leader's own DIMLDRBLK override picks its arrowhead, over its style's.
#[test]
fn leader_arrowhead_block_override_changes_the_arrowhead() {
let plain = leader_drawing(serde_json::json!({}));
let tick = leader_drawing(serde_json::json!({ "leaderArrowBlock": "_ArchTick" }));
assert!(!leader_fill(&plain).is_empty(), "the style's closed filled arrowhead");
assert_ne!(leader_fill(&tick), leader_fill(&plain), "another arrowhead is drawn");
// The closed arrowhead lies along the leader from its tip (x = 0); the tick crosses the tip.
let reach = |d: &Drawing| cadcraft_geom::Bounds2::from_points(leader_fill(d));
assert!(reach(&plain).min.x > -1e-9, "{:?}", reach(&plain));
assert!(reach(&tick).min.x < -1e-9 && reach(&tick).max.x > 1e-9, "{:?}", reach(&tick));
// The same arrowhead named by the style draws the same: the override stands in for it.
let mut styled = leader_drawing(serde_json::json!({}));
styled.dim_styles.iter_mut().filter(|s| s.name == "BIG").for_each(|s| s.leader_arrow_block = "_ArchTick".into());
assert_eq!(leader_fill(&tick), leader_fill(&styled));
}
/// A leader's own DIMCLRD override colours its line and arrowhead; ByBlock is its own colour.
#[test]
fn leader_line_colour_override_colours_the_line_and_arrowhead() {
let colours = |d: &Drawing| {
let l = build(d, &Space::Model, &Options::default());
let mut c: Vec<Rgb> = l.prims.iter().map(|p| p.color).collect();
c.dedup();
(c, l.prims.len())
};
let (plain, n) = colours(&leader_drawing(serde_json::json!({})));
assert!(n >= 2 && plain.len() == 1, "the line and the arrowhead in the leader's one colour: {plain:?}");
let red = serde_json::to_value(Color::Index(1)).unwrap();
let (over, m) = colours(&leader_drawing(serde_json::json!({ "dimLineColor": red })));
assert_eq!(m, n, "the same parts are drawn");
assert_eq!(over.len(), 1, "line and arrowhead share the override's colour: {over:?}");
assert_ne!(over, plain, "DIMCLRD override changes the colour");
let by_block = serde_json::to_value(Color::ByBlock).unwrap();
assert_eq!(colours(&leader_drawing(serde_json::json!({ "dimLineColor": by_block }))).0, plain, "ByBlock: the leader's own colour");
}
+12 -51
View File
@@ -88,8 +88,7 @@ pub(crate) fn mtext(b: &mut Builder, ctx: &Ctx, layer: &str, t: &cadcraft_doc::M
if b.opts.fill
&& let Some(bg) = &t.background
&& (bg.mask & 0x03) != 0
&& let tris = mtext_bg_tris(ctx.d, t, &l, bg.scale)
&& !tris.is_empty()
&& let Some([p0, p1, p2, p3]) = mtext_bg_quad(ctx.d, t, &l, bg.scale)
{
let n = b.list.prims.len();
let use_mask = (bg.mask & 2) != 0 || bg.color.is_none();
@@ -97,7 +96,7 @@ pub(crate) fn mtext(b: &mut Builder, ctx: &Ctx, layer: &str, t: &cadcraft_doc::M
Some(c) if !use_mask => ink(c, layer_color, ctx.block_color),
_ => Ink { rgb: Rgb(255, 255, 255), aci7: false, aci: 0 },
};
b.tris(ctx, fill_ink, &tris);
b.tris(ctx, fill_ink, &[p0, p1, p2, p0, p2, p3]);
if use_mask && let Some(p) = b.list.prims.get_mut(n) {
p.kind = super::Kind::Mask;
}
@@ -107,9 +106,7 @@ pub(crate) fn mtext(b: &mut Builder, ctx: &Ctx, layer: &str, t: &cadcraft_doc::M
}
}
/// The background's triangles: two per column, each column's box grown by its own text and the
/// border offset, so the gutters between columns stay unmasked.
fn mtext_bg_tris(d: &Drawing, t: &cadcraft_doc::MText, l: &cadcraft_fonts::MTextLayout, scale: f64) -> Vec<cadcraft_geom::Vec2> {
fn mtext_bg_quad(d: &Drawing, t: &cadcraft_doc::MText, l: &cadcraft_fonts::MTextLayout, scale: f64) -> Option<[cadcraft_geom::Vec2; 4]> {
let rot = if t.rotation.is_finite() { t.rotation } else { 0.0 };
let u_owned;
let u = if rot == 0.0 {
@@ -118,57 +115,21 @@ fn mtext_bg_tris(d: &Drawing, t: &cadcraft_doc::MText, l: &cadcraft_fonts::MText
u_owned = layout_mtext_entity(d, &cadcraft_doc::MText { rotation: 0.0, background: None, ..t.clone() });
&u_owned
};
let mut boxes = u.column_bounds.clone();
// Each point grows the column nearest to it across: the last one starting at or left of it,
// or the next one when that is closer.
let mut starts: Vec<(f64, usize)> = boxes.iter().map(|c| c.min.x).zip(0..).collect();
starts.sort_by(|a, b| a.0.total_cmp(&b.0));
for stroke in &u.strokes {
// The column of the stroke's point before this one. A stroke that goes on into another
// column (text too wide for its own) crosses the gutter: the column it comes from grows
// to its far end too, so the whole of it is behind that column's quad.
let mut from: Option<usize> = None;
for q in stroke {
if !q.is_finite() {
from = None;
continue;
}
let k = starts.partition_point(|(x, _)| *x <= q.x);
let next = starts.get(k).map(|&(x, i)| (x - q.x, i));
let prev = k.checked_sub(1).and_then(|k| starts.get(k)).map(|&(_, i)| (boxes.get(i).map_or(0.0, |c| q.x - c.max.x), i));
let nearest = match (prev, next) {
(Some((past, i)), Some((short, j))) => {
if short < past {
j
} else {
i
}
}
(Some((_, i)), None) | (None, Some((_, i))) => i,
(None, None) => break,
};
for column in [Some(nearest), from.filter(|i| *i != nearest)].into_iter().flatten() {
if let Some(c) = boxes.get_mut(column) {
c.add(*q);
}
}
from = Some(nearest);
let mut bounds = u.bounds;
for q in u.strokes.iter().flatten() {
if q.is_finite() {
bounds.add(*q);
}
}
if !(bounds.width().is_finite() && bounds.height().is_finite()) || bounds.width() <= 0.0 || bounds.height() <= 0.0 {
return None;
}
let gap = (scale - 1.0).clamp(0.0, 4.0) * t.height.max(0.0);
let (lo, hi) = (bounds.min - cadcraft_geom::Vec2::new(gap, gap), bounds.max + cadcraft_geom::Vec2::new(gap, gap));
let at = t.insert.xy();
let (x, y) = (cadcraft_geom::Vec2::from_angle(rot), cadcraft_geom::Vec2::from_angle(rot).perp());
let turn = |p: cadcraft_geom::Vec2| at + x * (p.x - at.x) + y * (p.y - at.y);
let mut tris = Vec::with_capacity(boxes.len() * 6);
for bounds in boxes {
if !(bounds.width().is_finite() && bounds.height().is_finite()) || bounds.width() <= 0.0 || bounds.height() <= 0.0 {
continue;
}
let (lo, hi) = (bounds.min - cadcraft_geom::Vec2::new(gap, gap), bounds.max + cadcraft_geom::Vec2::new(gap, gap));
let [p0, p1, p2, p3] = [lo, cadcraft_geom::Vec2::new(hi.x, lo.y), hi, cadcraft_geom::Vec2::new(lo.x, hi.y)].map(turn);
tris.extend([p0, p1, p2, p0, p2, p3]);
}
tris
Some([turn(lo), turn(cadcraft_geom::Vec2::new(hi.x, lo.y)), turn(hi), turn(cadcraft_geom::Vec2::new(lo.x, hi.y))])
}
/// A TEXT's justification as the fonts' alignment (used where text is placed outside a build).
+2 -4
View File
@@ -35,13 +35,11 @@ fn colours(l: &DisplayList) -> Vec<Rgb> {
}
#[test]
fn monochrome_prints_every_index_colour_black() {
fn monochrome_prints_every_colour_black() {
let d = drawing(&Space::Model);
let l = build_plot(&d, &Space::Model, &with_table(PlotStyleTable::builtin("monochrome.ctb").unwrap()));
assert_eq!(l.prims.len(), 4);
assert!(l.prims[..3].iter().all(|p| p.color == BLACK && !p.aci7), "{:?}", l.prims);
// The table's black is for index colours: the true orange keeps its colour.
assert_eq!(l.prims[3].color, Rgb(255, 128, 0));
assert!(l.prims.iter().all(|p| p.color == BLACK && !p.aci7), "{:?}", l.prims);
// Without a table the colours are the objects'.
let plain = build_plot(&d, &Space::Model, &Options::default());
assert_eq!(colours(&plain), [Rgb(255, 0, 0), Rgb(0, 255, 0), BLACK, Rgb(255, 128, 0)]);
+2 -47
View File
@@ -1,7 +1,7 @@
//! POINT display: point style (PDMODE) and size (PDSIZE) (issue #261).
use cadcraft_doc::{Block, Common, DimKind, Dimension, Drawing, Entity, EntityKind, Handle, Line, Point, Space};
use cadcraft_geom::{Bounds2, Vec2, Vec3};
use cadcraft_doc::{Common, Drawing, EntityKind, Line, Point, Space};
use cadcraft_geom::{Bounds2, Vec3};
use cadcraft_render::{DisplayList, Kind, Options, build};
/// A point at (5,5) and a vertical line 100 units long (the extents are 100 high).
@@ -67,48 +67,3 @@ fn hostile_point_settings_do_not_panic() {
}
}
}
/// A dimension read from a file draws with its block, which holds the definition points as POINT
/// objects. They mark where the dimension is attached and are not point objects of the drawing:
/// the point style must not turn them into figures.
#[test]
fn a_dimension_blocks_definition_points_stay_dots_under_a_point_style() {
let mut d = Drawing::new_imperial();
d.header.set_i64("PDMODE", 3);
d.header.set_f64("PDSIZE", 2.0);
let mut blk = Block::new("*D1");
blk.entities.push(Entity::new(Handle(1), EntityKind::Line(Line { a: Vec3::new(0.0, 5.0, 0.0), b: Vec3::new(10.0, 5.0, 0.0) })));
let def = Common { layer: "Defpoints".into(), ..Common::default() };
let mut point = Entity::new(Handle(2), EntityKind::Point(Point { p: Vec3::new(10.0, 0.0, 0.0), angle: 0.0 }));
point.common = def;
blk.entities.push(point);
d.blocks.insert("*D1".into(), std::sync::Arc::new(blk));
let dim = Dimension {
kind: DimKind::Linear { rotation: 0.0 },
defpt: Vec3::new(0.0, 5.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("*D1".into()),
overrides: Default::default(),
assoc: Vec::new(),
marks: Default::default(),
insertion_point: Vec3::ZERO,
};
d.add(&Space::Model, Common::default(), EntityKind::Dimension(dim)).unwrap();
// A point object of the drawing, which does follow the point style.
d.add(&Space::Model, Common::default(), EntityKind::Point(Point { p: Vec3::new(30.0, 30.0, 0.0), angle: 0.0 })).unwrap();
let l = build(&d, &Space::Model, &Options::default());
let near = |at: Vec2, kind: Kind| l.prims.iter().filter(|p| p.kind == kind && l.points(p).iter().any(|q| q.dist(at) < 1.5)).count();
let (def, own) = (Vec2::new(10.0, 0.0), Vec2::new(30.0, 30.0));
assert_eq!(near(def, Kind::Polyline), 0, "no figure at the definition point");
assert_eq!(near(def, Kind::Point), 1, "the definition point is a dot");
assert_eq!(near(own, Kind::Polyline), 2, "the drawing's own point keeps its cross");
}

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