Compare 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
FredApps 9d2d4085d3 docs: include acadrust's MPL-2.0 text and the ACadSharp notice (#3759) (#3760) 2026-12-02 19:35:43 +01:00
DievartisandFredApps 8e329e42b9 Hatch dialog: create custom patterns and capture a repeating tile from a drawing (#3631)
* Hatch dialog: author custom PAT families and capture a repeating tile

* Handle Escape through CADCraft's window cancel intent in the hatch dialog

* Keep custom hatches in the pattern gallery and fix repeating tile capture

* Exercise keyboard input in the hatch gallery filter

* Use the active drawing’s hatch geometry and finish tile picks only after two corners

Resolve embedded pattern lines for the gallery, HATCH, HATCHEDIT and Properties. Retry an empty compact swatch at full-period scale. Add coverage for two reopened drawings with the same pattern name, incomplete picks and aligned sparse marks.

The earlier shallow-slope fix skips empty scanlines before clipping. Its regression counts 10,000 full-length marks in a 100 by 100 tile area.

* Expose hatch tile capture as a headless engine command and reuse it in the dialog

* Respect drawing visibility and localize hatch capture errors in the dialog

* Use the public UI state constructor in workspace tests and route hatch capture through CadApp::run

* Classify in-memory hatch tile capture as requiring no files

* Check the saved hatch by handle independently of entity iteration order

* Reserve the native user-defined hatch name across custom pattern entry points

* Add the Chinese command label for Capture hatch tile

chinese_menus_and_commands_are_fully_translated requires every command
label in the Simplified Chinese catalog. The Ubuntu gate failed with this
one key still in English.

---------

Co-authored-by: FredApps <[email protected]>
2026-12-02 16:18:48 +01:00
FredApps 46ebd11c11 fix(ci): give each plotter test its own device name (#3758)
The in-memory plotter store is shared by the whole test process. On
FreeBSD the tests run as threads of one process (cargo test), so the
three tests that each create a "Banner Printer" collide and the later
one fails with "plotter `Banner Printer` already exists". Each test now
creates a device with its own name.
2026-12-02 11:54:15 +01: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 e064c97a3d io: take the test-only acadrust from the storytold/acadrust fork (#3761)
* io: take the test-only acadrust from the storytold/acadrust fork at storytold/v0.6.6

* io: say the test-only acadrust matches craft-dwg's crates.io 0.6.6 until the craft-libs repin
2026-12-02 10:49:50 +01:00
ALDREY, ALEJO EZEQUIEL 5ef8b342de Web: optional external file providers, disabled by default (#2593)
Adds an optional file-provider bridge for a trusted same-origin CADCraft web host. It is off until the host calls registerProvider. Provider Save and Open transfer single DXF files in memory and refuse drawings with external images or xrefs. Contributed by @alejocapo04.
2026-12-02 09:20:05 +01: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
75 changed files with 9044 additions and 205 deletions
+6
View File
@@ -22,11 +22,17 @@ Generated-in-code assets are original and have no file to list:
- the sample drawings (`crates/engine/src/sample.rs`);
- the synthetic two-hexagon hatch logo (`crates/io/tests/it/hatch_loop_flags.rs`, `logo`):
original contributor geometry, generated in code from invented points, under MIT OR Apache-2.0.
- the self-contained line drawings/DXF bytes generated by provider regressions in
`crates/ui-egui/src/file_provider_app/tests.rs` and
`apps/cadcraft-web/src/file_providers/browser_tests.rs` (CADCraft contributors, original test
code/data, MIT OR Apache-2.0; no vendor drawing, external image, font or other asset is added).
| Asset | Author | Source | Licence | Notes |
|---|---|---|---|---|
| `crates/ui-egui/src/i18n/zh_shared.tsv` | @V1dalTheAbidal | [craft-i18n #444](https://github.com/storytold/craft-i18n/pull/444), [pinned Simplified Chinese CADCraft catalog](https://github.com/storytold/craft-i18n/blob/9fa32aecf2759cd61bb216a958df68da619798f3/locales/zh-hans/cadcraft.tsv#L201) | MIT OR Apache-2.0 | Exact generated one-row projection for offline builds; AI-assisted, not native-speaker reviewed. |
| `licenses/jpeg-encoder-0.6.1/` | jpeg-encoder contributors and Independent JPEG Group | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1) | (MIT OR Apache-2.0) AND IJG | Dependency license and SIMD notices; source hashes in SOURCE.json. |
| `licenses/dwg/acadrust-MPL-2.0.txt` | acadrust contributors | [acadrust 0.6.6](https://crates.io/crates/acadrust/0.6.6), [hakanaktt/acadrust](https://github.com/hakanaktt/acadrust), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MPL-2.0 | DWG read/write dependency, used unmodified through craft-dwg. Full licence text is also in NOTICE. |
| `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | Albert Domenech (ACadSharp) and acadrust contributors | [ACadSharp](https://github.com/DomCR/ACadSharp), via [acadrust 0.6.6 third-party notices](https://github.com/hakanaktt/acadrust/blob/v0.6.6/THIRD_PARTY_NOTICES.md), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MIT (ACadSharp, via acadrust) | Upstream notice for MIT code ported into acadrust's DWG reader and writer. Full text is also in NOTICE. |
| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 173cc737](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full monochrome fallback. Registered by the production default font definitions; dependency assets unmodified here, no font file copied into this repository. |
| `krilla 0.8.2 / icc/sGrey-v2-magic.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v2-magic.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v2-magic.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `4110169287e5f1b5149ca9f1da1814d32943905bba8030e849d1a3b729a19481`. |
| `krilla 0.8.2 / icc/sGrey-v4.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v4.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v4.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `00c0f94e09127520a17dc0e1d9264b5702081d96dbdb1549ee88e3631ce42a9d`. |
Generated
+96 -2
View File
@@ -26,6 +26,29 @@ dependencies = [
"web-time",
]
[[package]]
name = "acadrust"
version = "0.6.6"
source = "git+https://github.com/storytold/acadrust.git?rev=5d5c482b3fcb3dc77e8281474461760f32959436#5d5c482b3fcb3dc77e8281474461760f32959436"
dependencies = [
"anyhow",
"bitflags 2.13.2",
"byteorder",
"encoding_rs",
"flate2",
"foldhash 0.2.0",
"indexmap",
"itoa",
"memmap2",
"nom 7.1.3",
"oem_cp",
"once_cell",
"rayon",
"ryu",
"thiserror 2.0.21",
"web-time",
]
[[package]]
name = "accesskit"
version = "0.25.2"
@@ -855,7 +878,7 @@ dependencies = [
name = "cadcraft-io"
version = "0.21.0"
dependencies = [
"acadrust",
"acadrust 0.6.6 (git+https://github.com/storytold/acadrust.git?rev=5d5c482b3fcb3dc77e8281474461760f32959436)",
"cadcraft-color",
"cadcraft-doc",
"cadcraft-fonts",
@@ -959,6 +982,7 @@ dependencies = [
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-bindgen-test",
"web-sys",
]
@@ -1022,6 +1046,12 @@ dependencies = [
"wayland-client",
]
[[package]]
name = "cast"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
[[package]]
name = "cc"
version = "1.10.0"
@@ -1427,7 +1457,7 @@ name = "craft-dwg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"acadrust",
"acadrust 0.6.6 (registry+https://github.com/rust-lang/crates.io-index)",
"log",
]
@@ -4064,6 +4094,16 @@ dependencies = [
"autocfg",
]
[[package]]
name = "minicov"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4869b6a491569605d66d3952bcdf03df789e5b536e5f0cf7758a7f08a55ae24d"
dependencies = [
"cc",
"walkdir",
]
[[package]]
name = "minimal-lexical"
version = "0.2.1"
@@ -4263,6 +4303,15 @@ dependencies = [
"memchr",
]
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "num-conv"
version = "0.2.2"
@@ -4798,6 +4847,12 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "oorandom"
version = "11.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
[[package]]
name = "open"
version = "5.4.5"
@@ -6824,6 +6879,45 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "wasm-bindgen-test"
version = "0.3.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae7499dfd45780a0a91d7ee6bb9ac51970a4479a41a89da443fdda5a39547d42"
dependencies = [
"async-trait",
"cast",
"js-sys",
"libm",
"minicov",
"nu-ansi-term",
"num-traits",
"oorandom",
"serde",
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-bindgen-test-macro",
"wasm-bindgen-test-shared",
]
[[package]]
name = "wasm-bindgen-test-macro"
version = "0.3.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b84b5ac638bfb168196a1a461fcc8f46a294a18b1b6be52133b4e0db122cc9f"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "wasm-bindgen-test-shared"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f692aa943ccd88363733b77063f32cfed5bc6cbea8e6e8b251b302f881606fe"
[[package]]
name = "wayland-backend"
version = "0.3.17"
+1
View File
@@ -85,6 +85,7 @@ egui = { version = "0.37", default-features = false, features = ["default_fonts"
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
egui_kittest = "0.37"
wasm-bindgen-test = "0.3.79"
eframe = { version = "0.37", default-features = false }
egui-wgpu = "0.37"
# Monotonic time on native and web (performance.now on wasm).
+428 -2
View File
@@ -10,9 +10,435 @@ docs/brand/LICENSE-brand.txt.
Third-party material
Software dependencies are listed in Cargo.lock. One is under a weak-copyleft licence: the acadrust
crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) is licensed under the
crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) 0.6.6 is licensed under the
Mozilla Public License 2.0 and is used unmodified as a separate library via craft-dwg. Its source
is available from crates.io and the repository above.
is available from crates.io and the repository above. The licence text and upstream third-party
notices are retained in licenses/dwg/, copied verbatim from craft-libs at
8fa4db64a9bb943520259ea95331a303ba788f21, the revision this repository pins.
acadrust's DWG reader and writer include code ported and adapted from ACadSharp
(https://github.com/DomCR/ACadSharp), Copyright (c) 2021 Albert Domenech, under the MIT License.
The Mozilla Public License 2.0 text and the upstream third-party notices follow.
The following text is reproduced verbatim from licenses/dwg/acadrust-MPL-2.0.txt:
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under the name "LEGAL", and included in all Covered Software
distributed in Source Code Form. Except to the extent prohibited by
statute or regulation, such description must be sufficiently detailed
for a recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
The following text is reproduced verbatim from licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md:
# Third-Party Notices
## ACadSharp
The DWG reader and writer include code ported and adapted from ACadSharp. The repository
history's initial DWG support commit identifies the source classes explicitly, including
`DwgStreamReaderBase`, `DwgLZ77AC21Decompressor`, `DwgFileHeaderWriterAC18`, and
`DwgObjectWriter`. Their current Rust implementations are in `src/io/dwg`.
Copyright (c) 2021 Albert Domenech
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## DWG Format References
DWG field layouts and version behavior are based on the Open Design Alliance (ODA) DWG
specification and reverse engineering, including comparison with drawings produced by CAD
applications. LibreDWG is used as a secondary cross-check for selected field names and
layouts. The Reed-Solomon tests cite numeric reference values from LibreDWG's
`src/reedsolomon.c` to validate the Rust implementation; those values are test data, not
translated routines. The repository history and source review found no LibreDWG routines
ported into the implementation. The source comments identify the specific cross-checks.
CADCraft's icons, drafting font, hatch patterns and linetypes are drawn or defined in code.
+3
View File
@@ -37,3 +37,6 @@ wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Location", "Navigator", "Blob", "BlobPropertyBag", "Url", "MessageEvent", "UrlSearchParams", "MediaQueryList", "Event", "EventTarget", "CustomEvent", "CustomEventInit"] }
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
wasm-bindgen-test = { workspace = true }
+232
View File
@@ -0,0 +1,232 @@
//! Same-origin file-provider bridge. Persistence belongs to the registered provider, not WASM.
//!
//! Callbacks enqueue commands for a later egui frame. Exporting bytes never acknowledges them.
use cadcraft_ui_egui::file_providers::{Host, Resource};
use js_sys::{Array, Function, Object, Reflect, Uint8Array};
use wasm_bindgen::{JsCast, JsValue, closure::Closure, prelude::wasm_bindgen};
thread_local! {
static CURRENT_CONTEXT: std::cell::RefCell<Option<egui::Context>> = const { std::cell::RefCell::new(None) };
}
const API: &str = "cadcraftFileProviders";
const EVENT: &str = "cadcraft-file-provider";
const MAX_BYTES: u32 = 80 * 1024 * 1024;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(catch, js_namespace = Uint8Array, js_name = from)]
fn copy_event_bytes(bytes: &[u8]) -> Result<Uint8Array, JsValue>;
}
fn error(message: impl ToString) -> JsValue {
JsValue::from_str(&message.to_string())
}
fn object(value: &serde_json::Value) -> Result<JsValue, JsValue> {
js_sys::JSON::parse(&value.to_string())
}
fn set(target: &JsValue, key: &str, value: &JsValue) -> Result<(), JsValue> {
if Reflect::set(target, &key.into(), value)? { Ok(()) } else { Err(error("file-provider API is not writable")) }
}
// Inspect UTF-16 length before copying a host string into WASM memory.
fn bounded_string(value: JsValue, max_units: u32) -> Result<String, JsValue> {
let text = value.dyn_into::<js_sys::JsString>().map_err(|_| error("resource fields must be strings"))?;
if text.length() > max_units {
return Err(error("resource field is too large"));
}
text.as_string().ok_or_else(|| error("invalid resource field"))
}
fn resource(value: JsValue) -> Result<Resource, JsValue> {
if value.is_null() || !value.is_object() || Array::is_array(&value) {
return Err(error("resource entries must be objects"));
}
let entry = value.dyn_into::<Object>()?;
let id = bounded_string(Reflect::get(&entry, &"id".into())?, 160)?;
let name = bounded_string(Reflect::get(&entry, &"name".into())?, 255)?;
let updated = Reflect::get(&entry, &"updatedAt".into())?;
let updated_at = if updated.is_undefined() { String::new() } else { bounded_string(updated, 100)? };
Ok(Resource { id, name, updated_at })
}
fn wake_later(ctx: &egui::Context) {
let fallback = ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
CURRENT_CONTEXT.with(|current| current.borrow().as_ref().unwrap_or(&fallback).request_repaint());
});
}
/// Makes the capability discoverable without enabling it or changing the browser's writer.
pub fn install(host: Host, ctx: egui::Context) -> Result<(), JsValue> {
let window = web_sys::window().ok_or_else(|| error("no window"))?;
CURRENT_CONTEXT.with(|current| *current.borrow_mut() = Some(ctx.clone()));
if Reflect::has(&window, &API.into())? {
// A graphics restart keeps the page capability and pending requests, and renews its wake target.
return Ok(());
}
// A delayed result from an earlier page must never address a new document's request.
let crypto = Reflect::get(&window, &"crypto".into())?;
let random = Reflect::get(&crypto, &"getRandomValues".into())?.dyn_into::<Function>()?;
let nonce = Uint8Array::new_with_length(16);
random.call1(&crypto, &nonce)?;
host.set_session(nonce.to_vec().iter().map(|byte| format!("{byte:02x}")).collect()).map_err(error)?;
let api = Object::new();
set(&api, "protocolVersion", &1.into())?;
set(&api, "app", &"cadcraft".into())?;
set(&api, "capabilities", &object(&serde_json::json!(["revisionAck", "externalRecents", "saveDestination", "openBytes"]))?)?;
let h = host.clone();
let wake = ctx.clone();
let register = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<String, JsValue>>::new(move |id, label, namespace| {
let id = bounded_string(id, 160)?;
let label = bounded_string(label, 100)?;
let namespace = bounded_string(namespace, 160)?;
let connection = h.connect(id, label, namespace).map_err(error)?;
wake_later(&wake);
Ok(connection)
});
set(&api, "registerProvider", register.as_ref())?;
register.forget();
let h = host.clone();
let wake = ctx.clone();
let unregister = Closure::<dyn FnMut() -> Result<bool, JsValue>>::new(move || {
h.disconnect().map_err(error)?;
wake_later(&wake);
Ok(true)
});
set(&api, "unregisterProvider", unregister.as_ref())?;
unregister.forget();
let h = host.clone();
let wake = ctx.clone();
let enabled = Closure::<dyn FnMut(JsValue) -> Result<bool, JsValue>>::new(move |value: JsValue| {
let value = value.as_bool().ok_or_else(|| error("enabled must be a boolean"))?;
h.set_enabled(value).map_err(error)?;
wake_later(&wake);
Ok(true)
});
set(&api, "setEnabled", enabled.as_ref())?;
enabled.forget();
let h = host.clone();
let wake = ctx.clone();
let resources = Closure::<dyn FnMut(JsValue, JsValue) -> Result<(), JsValue>>::new(move |connection, value: JsValue| {
let connection = bounded_string(connection, 160)?;
if !Array::is_array(&value) {
return Err(error("resources must be an array of at most 100 entries"));
}
let entries = value.dyn_into::<Array>()?;
if entries.length() > 100 {
return Err(error("resources must be an array of at most 100 entries"));
}
// Read only bounded metadata; do not copy or serialize arbitrary host properties.
let resources = entries.iter().map(resource).collect::<Result<Vec<_>, _>>()?;
h.set_resources(&connection, resources).map_err(error)?;
wake_later(&wake);
Ok(())
});
set(&api, "setResources", resources.as_ref())?;
resources.forget();
let h = host.clone();
let wake = ctx.clone();
let request_open = Closure::<dyn FnMut(JsValue) -> Result<String, JsValue>>::new(move |resource| {
let resource = bounded_string(resource, 160)?;
let request = h.request_open(&resource).map_err(error)?;
wake_later(&wake);
Ok(request)
});
set(&api, "requestOpen", request_open.as_ref())?;
request_open.forget();
let h = host.clone();
let wake = ctx.clone();
let open = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, name, value: JsValue| {
let request = bounded_string(request, 160)?;
let name = bounded_string(name, 255)?;
let bytes = value.dyn_into::<Uint8Array>().map_err(|_| error("bytes must be a Uint8Array"))?;
if bytes.length() > MAX_BYTES {
return Err(error("file exceeds the provider limit"));
}
h.open(request, name, bytes.to_vec()).map_err(error)?;
wake_later(&wake);
Ok(())
});
set(&api, "openResource", open.as_ref())?;
open.forget();
let h = host.clone();
let wake = ctx.clone();
let cancel_open = Closure::<dyn FnMut(JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, message| {
let request = bounded_string(request, 160)?;
let message = bounded_string(message, 1024)?;
h.cancel_open(request, message).map_err(error)?;
wake_later(&wake);
Ok(())
});
set(&api, "cancelOpen", cancel_open.as_ref())?;
cancel_open.forget();
let h = host.clone();
let wake = ctx.clone();
let result = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, status, resource| {
let request = bounded_string(request, 160)?;
let status = bounded_string(status, 8)?;
let resource = bounded_string(resource, 160)?;
h.result(request, status, resource).map_err(error)?;
wake_later(&wake);
Ok(())
});
set(&api, "saveResult", result.as_ref())?;
result.forget();
let h = host.clone();
let wake = ctx.clone();
let dialog = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, destination, name| {
let request = bounded_string(request, 160)?;
let destination = bounded_string(destination, 8)?;
let name = bounded_string(name, 255)?;
h.resolve_dialog(&request, &destination, &name).map_err(error)?;
wake_later(&wake);
Ok(())
});
set(&api, "resolveSaveDialog", dialog.as_ref())?;
dialog.forget();
let h = host.clone();
let snapshot = Closure::<dyn FnMut() -> Result<JsValue, JsValue>>::new(move || object(&h.snapshot()));
set(&api, "snapshot", snapshot.as_ref())?;
snapshot.forget();
set(&window, API, &Object::freeze(&api))?;
dispatch(&serde_json::json!({"type": "ready", "protocolVersion": 1}), None)
}
fn dispatch(metadata: &serde_json::Value, bytes: Option<Vec<u8>>) -> Result<(), JsValue> {
let detail = object(metadata)?;
if let Some(bytes) = bytes {
set(&detail, "bytes", &copy_event_bytes(&bytes)?.into())?;
}
let init = web_sys::CustomEventInit::new();
init.set_detail(&detail);
let event = web_sys::CustomEvent::new_with_event_init_dict(EVENT, &init)?;
web_sys::window().ok_or_else(|| error("no window"))?.dispatch_event(&event)?;
Ok(())
}
pub fn publish(host: &Host) {
if host.publish_events_with(dispatch, |error| log::error!("file-provider event delivery failed: {error:?}")) {
CURRENT_CONTEXT.with(|current| {
if let Some(ctx) = current.borrow().as_ref() {
ctx.request_repaint();
}
});
}
}
#[cfg(test)]
mod browser_tests;
@@ -0,0 +1,271 @@
//! Original, self-contained DXF fixture. Rust closures create genuine JS exceptions; no JS source.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
use cadcraft_engine::{Session, cmd::file};
use cadcraft_ui_egui::{CadApp, Services};
use js_sys::{Array, Function, Object, Reflect, Uint8Array};
use serde_json::json;
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
fn error(message: impl ToString) -> JsValue {
JsValue::from_str(&message.to_string())
}
fn field(object: &JsValue, name: &str) -> Result<JsValue, JsValue> {
Reflect::get(object, &name.into())
}
fn text(object: &JsValue, name: &str) -> Result<String, JsValue> {
field(object, name)?.as_string().ok_or_else(|| error(format!("missing string field {name}")))
}
fn call(object: &JsValue, name: &str, arguments: &[JsValue]) -> Result<JsValue, JsValue> {
let function = field(object, name)?.dyn_into::<Function>()?;
let array = Array::new();
for argument in arguments {
array.push(argument);
}
function.apply(object, &array)
}
struct Page {
window: web_sys::Window,
api: JsValue,
host: cadcraft_ui_egui::file_providers::Host,
ctx: egui::Context,
events: Rc<RefCell<Vec<JsValue>>>,
listener: Closure<dyn FnMut(web_sys::Event)>,
}
impl Page {
fn install(app: &CadApp) -> Result<Self, JsValue> {
let window = web_sys::window().ok_or_else(|| error("no browser window"))?;
if Reflect::has(&window, &super::API.into())? {
return Err(error("fixture requires a fresh owned page"));
}
let host = app.file_providers.clone();
let ctx = egui::Context::default();
let events = Rc::new(RefCell::new(Vec::new()));
let seen = events.clone();
let listener = Closure::<dyn FnMut(web_sys::Event)>::new(move |event: web_sys::Event| {
if let Ok(event) = event.dyn_into::<web_sys::CustomEvent>() {
seen.borrow_mut().push(event.detail());
}
});
window.add_event_listener_with_callback(super::EVENT, listener.as_ref().unchecked_ref())?;
let mut page = Self { window, api: JsValue::UNDEFINED, host, ctx, events, listener };
super::install(page.host.clone(), page.ctx.clone())?;
page.api = field(&page.window, super::API)?;
Ok(page)
}
fn api(&self, method: &str, arguments: &[JsValue]) -> Result<JsValue, JsValue> {
call(&self.api, method, arguments)
}
fn latest(&self, kind: &str) -> Result<JsValue, JsValue> {
self.events
.borrow()
.iter()
.rev()
.find(|event| text(event, "type").is_ok_and(|name| name == kind))
.cloned()
.ok_or_else(|| error(format!("missing real window event {kind}")))
}
fn tick(&self, app: &mut CadApp) {
self.ctx.run_ui(Default::default(), |ui| app.logic(ui.ctx())).drop_without_applying_deltas();
}
fn choose(&self, app: &mut CadApp) -> Result<String, JsValue> {
let value = app.run("qsave", serde_json::Value::Null).map_err(error)?;
value
.get("requestId")
.and_then(serde_json::Value::as_str)
.map(str::to_string)
.ok_or_else(|| error("qsave did not create a real provider choice"))
}
fn captured_save(&self, app: &mut CadApp) -> Result<String, JsValue> {
let request = self.choose(app)?;
super::publish(&self.host);
assert_eq!(text(&self.latest("saveDialog")?, "requestId")?, request);
self.api("resolveSaveDialog", &[request.clone().into(), "provider".into(), "Fixture.dxf".into()])?;
Ok(request)
}
// Both the injected callback and production publisher are entered through catch-enabled
// Function::call0. Restore the exact own descriptor (or remove our inherited-method shadow)
// BEFORE assertions, even when an uncaught production exception returns Err from call0.
fn with_replacement(&self, target: &JsValue, key: &str, replacement: &JsValue) -> Result<Result<JsValue, JsValue>, JsValue> {
let object = field(&js_sys::global(), "Object")?;
let descriptor = call(&object, "getOwnPropertyDescriptor", &[target.clone(), key.into()])?;
let original = field(target, key)?;
let host = self.host.clone();
let operation = Closure::<dyn FnMut()>::new(move || super::publish(&host));
let outcome = match Reflect::set(target, &key.into(), replacement) {
Ok(true) => operation.as_ref().unchecked_ref::<Function>().call0(&JsValue::UNDEFINED),
Ok(false) => Err(error("injected method is not writable")),
Err(error) => Err(error),
};
if descriptor.is_undefined() {
if !Reflect::delete_property(target.unchecked_ref::<Object>(), &key.into())? {
return Err(error("could not remove injected method"));
}
} else {
call(&object, "defineProperty", &[target.clone(), key.into(), descriptor.clone()])?;
}
let restored = call(&object, "getOwnPropertyDescriptor", &[target.clone(), key.into()])?;
if field(target, key)? != original || restored.is_undefined() != descriptor.is_undefined() {
return Err(error("injected property was not restored exactly"));
}
if !descriptor.is_undefined() {
for attribute in ["value", "get", "set", "writable", "enumerable", "configurable"] {
if field(&restored, attribute)? != field(&descriptor, attribute)? {
return Err(error("injected property descriptor changed"));
}
}
}
Ok(outcome)
}
fn fail_copy(&self) -> Result<u32, JsValue> {
let calls = Rc::new(Cell::new(0));
let seen = calls.clone();
let fault = Closure::<dyn FnMut(JsValue) -> Result<JsValue, JsValue>>::new(move |_| {
seen.set(seen.get() + 1);
Err(js_sys::RangeError::new("synthetic CAD byte-copy failure").into())
});
let array = field(&js_sys::global(), "Uint8Array")?;
self.with_replacement(&array, "from", fault.as_ref())??;
Ok(calls.get())
}
fn fail_dispatch(&self, kind: &str) -> Result<u32, JsValue> {
let original = field(&self.window, "dispatchEvent")?.dyn_into::<Function>()?;
let window: JsValue = self.window.clone().into();
let wanted = kind.to_string();
let calls = Rc::new(Cell::new(0));
let seen = calls.clone();
let fault = Closure::<dyn FnMut(JsValue) -> Result<JsValue, JsValue>>::new(move |event: JsValue| {
if text(&field(&event, "detail")?, "type")? == wanted {
seen.set(seen.get() + 1);
Err(js_sys::RangeError::new("synthetic CAD metadata dispatch failure").into())
} else {
original.call1(&window, &event)
}
});
self.with_replacement(&self.window, "dispatchEvent", fault.as_ref())??;
Ok(calls.get())
}
}
impl Drop for Page {
fn drop(&mut self) {
let _ = self.window.remove_event_listener_with_callback(super::EVENT, self.listener.as_ref().unchecked_ref());
let _ = Reflect::delete_property(self.window.unchecked_ref::<Object>(), &super::API.into());
}
}
#[wasm_bindgen_test]
fn real_window_delivery_recovery_preserves_dxf_and_consumes_actual_cad_actions() -> Result<(), JsValue> {
// Production codec hooks, on this fixture's fresh browser page only. Native app fixtures
// use cadcraft_io directly and never replace their process-global test hooks.
file::set_io(file::IoHooks {
read: |bytes, name| cadcraft_io::read(bytes, name).map_err(|error| error.to_string()),
write: |drawing, name| cadcraft_io::write(drawing, name).map_err(|error| error.to_string()),
plot: None,
});
file::set_write_as(|drawing, name, options| {
cadcraft_io::write_with(drawing, name, &cadcraft_io::SaveOptions { version: options.version, binary: options.binary })
.map_err(|error| error.to_string())
});
let mut app = CadApp::new(Session::new(), Services { no_file_system: true, ..Default::default() });
app.run("line", json!({"points":[[0,0],[10,10]]})).map_err(error)?;
let page = Page::install(&app)?;
let connection = page.api("registerProvider", &["fixture".into(), "Fixture storage".into(), "account-one".into()])?;
let resources = Array::new();
for id in ["file-1", "file-2"] {
let resource = Object::new();
Reflect::set(&resource, &"id".into(), &id.into())?;
Reflect::set(&resource, &"name".into(), &"Fixture.dxf".into())?;
Reflect::set(&resource, &"updatedAt".into(), &"".into())?;
resources.push(&resource);
}
page.api("setResources", &[connection.clone(), resources.into()])?;
let uid = app.session.state().map_err(error)?.uid;
let checkpoint = app.session.state().map_err(error)?.saved.clone();
let chooser = page.choose(&mut app)?;
assert_eq!(page.fail_dispatch("saveDialog")?, 1);
page.tick(&mut app);
super::publish(&page.host);
assert_eq!(text(&page.latest("saveFailed")?, "requestId")?, chooser);
assert!(page.api("resolveSaveDialog", &[chooser.into(), "provider".into(), "Late.dxf".into()]).is_err());
assert!(!page.host.busy());
assert!(Arc::ptr_eq(&app.session.state().map_err(error)?.saved, &checkpoint));
let read = page.api("requestOpen", &["file-2".into()])?;
assert_eq!(page.fail_dispatch("openRequested")?, 1);
let failed_read = page.latest("openFailed")?;
assert_eq!(field(&failed_read, "requestId")?, read);
assert_eq!(text(&failed_read, "resourceId")?, "file-2");
assert_eq!(field(&failed_read, "connectionId")?, connection);
assert!(!page.host.busy());
let failed = page.captured_save(&mut app)?;
let later_read = page.api("requestOpen", &["file-2".into()])?;
app.set_status("Awaiting the synthetic byte-copy failure");
assert_eq!(page.fail_copy()?, 1, "actual catch-enabled production copy must throw exactly once");
assert!(!page.events.borrow().iter().any(|event| text(event, "type").is_ok_and(|kind| kind == "save")));
assert_eq!(field(&page.latest("openRequested")?, "requestId")?, later_read);
assert!(page.api("saveResult", &[failed.clone().into(), "saved".into(), "file-1".into()]).is_err());
page.api("cancelOpen", &[later_read, "".into()])?;
page.tick(&mut app);
super::publish(&page.host);
assert_eq!(text(&page.latest("saveFailed")?, "requestId")?, failed);
let state = app.session.state().map_err(error)?;
assert_eq!(state.uid, uid);
assert!(state.is_dirty() && Arc::ptr_eq(&state.saved, &checkpoint));
assert!(!page.host.busy() && page.host.bound_document("file-1").is_none());
assert!(app.status.as_ref().is_some_and(|(message, _)| message.contains("File provider save failed")));
let retry = page.captured_save(&mut app)?;
assert_ne!(retry, failed);
super::publish(&page.host);
let saved = page.latest("save")?;
assert_eq!(text(&saved, "requestId")?, retry);
assert_eq!(text(&saved, "filename")?, "Fixture.dxf");
assert_eq!(text(&saved, "documentId")?, uid.to_string());
assert_eq!(field(&saved, "connectionId")?, connection);
let bytes = field(&saved, "bytes")?.dyn_into::<Uint8Array>()?;
assert!(bytes.length() > 0);
let drawing = cadcraft_io::read(&bytes.to_vec(), "Fixture.dxf").map_err(error)?;
assert_eq!(drawing.model.len(), app.session.state().map_err(error)?.doc.model.len());
assert!(!drawing.model.is_empty());
assert!(page.host.pending_for(uid) && app.session.state().map_err(error)?.is_dirty());
let captured = app.session.state().map_err(error)?.doc.clone();
let captured_revision = app.session.state().map_err(error)?.revision;
app.run("line", json!({"points":[[20,20],[30,30]]})).map_err(error)?;
page.api("saveResult", &[retry.clone().into(), "saved".into(), "file-1".into()])?;
page.tick(&mut app);
super::publish(&page.host);
let terminal = page.latest("saved")?;
assert_eq!(text(&terminal, "requestId")?, retry);
assert_eq!(text(&terminal, "resourceId")?, "file-1");
assert_eq!(text(&terminal, "revision")?, captured_revision.to_string());
let state = app.session.state().map_err(error)?;
assert!(state.is_dirty() && Arc::ptr_eq(&state.saved, &captured), "ACK owns its snapshot, never later edits");
assert_eq!(page.host.bound_document("file-1"), Some(uid));
assert!(!page.host.busy());
let open = page.api("requestOpen", &["file-2".into()])?;
super::publish(&page.host);
page.api("openResource", &[open.clone(), "Fixture.dxf".into(), bytes.into()])?;
page.tick(&mut app);
super::publish(&page.host);
let opened = page.latest("opened")?;
assert_eq!(field(&opened, "requestId")?, open);
assert_eq!(text(&opened, "resourceId")?, "file-2");
assert_eq!(field(&opened, "connectionId")?, connection);
assert_eq!(text(&opened, "namespace")?, "account-one");
let imported = app.session.state().map_err(error)?;
assert_ne!(imported.uid, uid);
assert_eq!(imported.doc.model.len(), drawing.model.len());
let original = app.session.docs.iter().find(|doc| doc.uid == uid).ok_or_else(|| error("original drawing was lost on provider open"))?;
assert!(original.is_dirty() && Arc::ptr_eq(&original.saved, &captured));
assert!(!page.host.busy());
page.api("unregisterProvider", &[])?;
Ok(())
}
+11
View File
@@ -15,6 +15,8 @@ mod api;
#[cfg(target_arch = "wasm32")]
pub mod download;
#[cfg(target_arch = "wasm32")]
mod file_providers;
#[cfg(target_arch = "wasm32")]
mod host;
#[cfg(any(target_arch = "wasm32", test))]
@@ -47,6 +49,7 @@ mod web {
self.1.drain(&mut self.0);
self.0.system_animations = self.3.as_ref().map(|reduced| !reduced.matches());
self.0.logic(ctx);
crate::file_providers::publish(&self.0.file_providers);
let drawing = self.0.session.state().ok();
crate::push_title(&mut self.4, drawing.map(|d| d.title.as_str()), drawing.is_some_and(|d| d.is_dirty()), set_page_title);
// The crate suppresses duplicates, so reporting after every logic callback
@@ -82,6 +85,7 @@ mod web {
self.1.take_dropped(ui.ctx());
}
self.0.ui(ui);
crate::file_providers::publish(&self.0.file_providers);
}
}
@@ -181,6 +185,13 @@ mod web {
let session = if app_bridge.is_some() { Session::empty() } else { Session::new() };
let control = crate::api::install(cc.egui_ctx.clone());
let mut app = CadApp::new(session, services()).with_control(control);
// The provider capability is independent of the parent and same-document host modes.
// Avoid two hosts competing for the same Save command.
if app_bridge.is_none() {
if let Err(error) = crate::file_providers::install(app.file_providers.clone(), cc.egui_ctx.clone()) {
log::error!("file provider capability could not be installed: {error:?}");
}
}
app.system_languages =
web_sys::window().map(|w| w.navigator().languages().iter().filter_map(|v| v.as_string()).collect()).unwrap_or_default();
if let Some(profile) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::options::PROFILE_KEY)) {
+17 -14
View File
@@ -213,16 +213,14 @@ mod tests {
let path = directory.join("workspace.json");
let (mut first, restored, error) = Workspace::at(Some(path.clone()));
assert!(restored.is_none() && error.is_none());
let ui = UiState {
show_palettes: false,
show_command_line: false,
toolset_tab: "Modeling".into(),
collapsed_groups: vec!["Solid".into()],
history_lines: 5,
dialog: Some("layers".into()),
start_tab: true,
..Default::default()
};
let mut ui = UiState::default();
ui.show_palettes = false;
ui.show_command_line = false;
ui.toolset_tab = "Modeling".into();
ui.collapsed_groups = vec!["Solid".into()];
ui.history_lines = 5;
ui.dialog = Some("layers".into());
ui.start_tab = true;
first.save_if_changed(&ui, Instant::now()).unwrap();
let bytes = fs::read(&path).unwrap();
let value: Value = serde_json::from_slice(&bytes).unwrap();
@@ -313,7 +311,9 @@ mod tests {
let (mut store, ui, error) = Workspace::at(Some(path.clone()));
assert!(ui.is_none());
assert!(error.as_deref().is_some_and(|error| error.contains("left unchanged")));
store.save_if_changed(&UiState { show_palettes: false, ..Default::default() }, Instant::now()).unwrap();
let mut ui = UiState::default();
ui.show_palettes = false;
store.save_if_changed(&ui, Instant::now()).unwrap();
assert_eq!(fs::read(&path).unwrap(), bytes);
}
fs::remove_dir_all(directory).unwrap();
@@ -351,7 +351,8 @@ mod tests {
let path = directory.join("workspace.json");
let (mut store, _, _) = Workspace::at(Some(path.clone()));
let start = Instant::now();
let mut ui = UiState { history_lines: 1, ..Default::default() };
let mut ui = UiState::default();
ui.history_lines = 1;
assert_eq!(store.save_if_changed(&ui, start).unwrap(), None);
// A drag: a new state every frame, none of them written until the interval ends.
for (frame, lines) in (2..=5).enumerate() {
@@ -375,7 +376,8 @@ mod tests {
let directory = temp_dir();
let path = directory.join("workspace.json");
let (mut store, _, _) = Workspace::at(Some(path.clone()));
let mut ui = UiState { show_palettes: false, ..Default::default() };
let mut ui = UiState::default();
ui.show_palettes = false;
store.save_if_changed(&ui, Instant::now()).unwrap();
let good = fs::read(&path).unwrap();
ui.collapsed_groups = vec!["x".repeat(257)];
@@ -391,7 +393,8 @@ mod tests {
let (mut store, _, _) = Workspace::at(Some(path.clone()));
// Simulate a destination becoming unavailable after startup.
fs::create_dir(&path).unwrap();
let ui = UiState { show_palettes: false, ..Default::default() };
let mut ui = UiState::default();
ui.show_palettes = false;
let first_error = store.save_if_changed(&ui, Instant::now()).unwrap_err();
fs::remove_dir(&path).unwrap();
assert_eq!(store.save_if_changed(&ui, Instant::now()).unwrap_err(), first_error);
+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
}
+5
View File
@@ -261,6 +261,11 @@ pub fn is_user_pattern(name: &str) -> bool {
name.eq_ignore_ascii_case(USER_PATTERN)
}
/// Names owned by the standard library or the native user-defined hatch form.
pub fn is_reserved_pattern_name(name: &str) -> bool {
is_user_pattern(name) || pattern(name).is_some()
}
/// Hatch pattern scales must be greater than this limit. For a user-defined hatch, the scale is its line spacing.
pub const MIN_HATCH_PATTERN_SCALE: f64 = 1e-9;
+3 -1
View File
@@ -40,14 +40,15 @@ 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;
@@ -196,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());
+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 {
+26 -10
View File
@@ -1,10 +1,11 @@
//! HATCH, GRADIENT, BOUNDARY, REGION: boundaries from pick points or selected closed objects.
//! HATCHGENERATEBOUNDARY: polylines around existing hatches.
mod capture;
mod patfile;
pub(super) use edit::{set_pattern, takes_pattern};
pub(super) use patfile::run_patterns;
pub use patfile::{PatternChoice, pattern_choices};
pub use patfile::{PatternChoice, pattern_choices, pattern_choices_in, register_drawing_patterns};
pub(super) use patfile::{drawing_lines, run_patterns};
use cadcraft_color::Color;
use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_scale};
@@ -56,6 +57,10 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("hatchgenerateboundary", "Generate Boundary", edit::run_hatchgenerateboundary)
.params("{handles?} (a closed polyline around each boundary loop of the hatches, which stay as they are) → handles")
.interactive(|_| Ok(Box::new(SelectRun::new("hatchgenerateboundary", "HATCHGENERATEBOUNDARY")))),
CommandSpec::new("hatch.capture", "Capture hatch tile", capture::run)
.params("{first:[x,y], second:[x,y], name?:string} → {pattern, patternText}; capture line segments inside the tile in the active space")
.enabled(has_doc)
.noundo(),
CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick)
.params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing")
.enabled(has_doc)
@@ -340,6 +345,7 @@ pub(crate) fn gradient_name(t: &str) -> Option<&'static str> {
#[derive(Clone)]
struct HatchSettings {
lines: Vec<cadcraft_doc::library::PatternLine>,
pattern: String,
scale: f64,
/// HPSPACE for user-defined patterns. The entity stores it as its scale.
@@ -372,8 +378,10 @@ impl HatchSettings {
angle: f64_or(p, "angle", 0.0).to_radians(),
centered: bool_or(p, "centered", true),
});
let lines = s.doc().ok().and_then(|d| drawing_lines(d, &pattern)).unwrap_or_else(|| patfile::lines_for(&pattern));
let scale = f64_or(p, "scale", hdr.1).max(1e-9);
HatchSettings {
lines,
pattern,
scale,
user_spacing: scale,
@@ -417,12 +425,12 @@ impl HatchSettings {
background: None,
// A user-defined hatch's families come from its angle, spacing and double flag, not
// from a pattern definition; any other hatch takes the loaded pattern's, if any.
pattern_lines: if user_defined { cadcraft_doc::library::user_defined_lines(self.double) } else { patfile::lines_for(&self.pattern) },
pattern_lines: if user_defined { cadcraft_doc::library::user_defined_lines(self.double) } else { self.lines.clone() },
})
}
}
fn make(s: &mut Session, p: &Value, gradient: bool) -> Result<Value> {
fn make(s: &mut Session, p: &Value, gradient: bool, loaded: &[String]) -> Result<Value> {
// A zero or negative pattern scale would be clamped to a near-zero spacing.
size_param(if gradient { "gradient" } else { "hatch" }, p, "scale", false)?;
let cmd = if gradient { "gradient" } else { "hatch" };
@@ -435,7 +443,10 @@ fn make(s: &mut Session, p: &Value, gradient: bool) -> Result<Value> {
if gradient && str_param(p, "name").is_some_and(|t| gradient_name(t).is_none()) {
return Err(bad(cmd, format!("unknown gradient `name`; use one of {}", GRADIENT_NAMES.join(", "))));
}
let st = HatchSettings::from(s, p, gradient);
let mut st = HatchSettings::from(s, p, gradient);
if loaded.iter().any(|n| n.eq_ignore_ascii_case(&st.pattern)) {
st.lines = patfile::lines_for(&st.pattern);
}
// Loops by picked point or selected object: one hatch each when separate.
let mut groups: Vec<Vec<HatchLoop>> = Vec::new();
// Internal points and boundary objects can come together (the dialog's Pick points and
@@ -534,18 +545,19 @@ fn add_hatches(s: &mut Session, st: &HatchSettings, groups: Vec<Vec<HatchLoop>>)
}
fn run_hatch(s: &mut Session, p: &Value) -> Result<Value> {
patfile::load_param(p)?;
let loaded = patfile::load_param(p)?;
// Like the prompt: a name without a definition would be drawn as ANSI31.
if let Some(up) = str_param(p, "pattern").map(str::to_ascii_uppercase)
&& cadcraft_doc::library::pattern(&up).is_none()
&& patfile::user_pattern(&up).is_none()
&& drawing_lines(s.doc()?, &up).is_none()
{
return Err(bad("hatch", format!("unknown pattern {up}: not built in; load it with patternFile or patternText (a .pat file)")));
}
make(s, p, false)
make(s, p, false, &loaded)
}
fn run_gradient(s: &mut Session, p: &Value) -> Result<Value> {
make(s, p, true)
make(s, p, true, &[])
}
fn boundary_at(s: &mut Session, q: Vec2) -> Result<Vec<Handle>> {
@@ -706,13 +718,17 @@ impl HatchM {
self.settings.double = s.last_used.hatch_double;
return Ok(true);
}
let up = match patfile::typed_file(s, t) {
let file = patfile::typed_file(s, t);
let explicit = file.is_some();
let up = match file {
// Nothing loaded from it: the pattern is asked again.
Some(n) if n.is_empty() => return Ok(false),
Some(n) => n,
None => t.to_ascii_uppercase(),
};
if pattern_exists(&up) {
let local = if explicit { None } else { drawing_lines(s.doc()?, &up) };
if local.is_some() || pattern_exists(&up) {
self.settings.lines = local.unwrap_or_else(|| patfile::lines_for(&up));
self.settings.pattern = up.clone();
// A named pattern, SOLID included, is not the user-defined one.
self.settings.double = false;
+205
View File
@@ -0,0 +1,205 @@
//! Capture a rectangular tile from the active drawing space as reusable PAT text.
use cadcraft_doc::{Drawing, EntityKind, Space, library::PatternLine};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
use crate::cmd::{bad, point_param};
use crate::{Result, Session};
const COMMAND: &str = "hatch.capture";
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
let corner = |key| point_param(p, key).filter(|q| q.is_finite()).ok_or_else(|| bad(COMMAND, format!("give a finite {key} point [x,y]")));
let a = corner("first")?;
let b = corner("second")?;
let name = match p.get("name") {
None => "CAPTURED_TILE",
Some(v) => v.as_str().ok_or_else(|| bad(COMMAND, "name must be a string"))?,
}
.trim()
.to_ascii_uppercase();
if name.is_empty()
|| name.len() > 31
|| !name.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_')
|| cadcraft_doc::library::is_reserved_pattern_name(&name)
{
return Err(bad(COMMAND, "use a custom pattern name of 1 to 31 letters, digits or underscores"));
}
let lines = capture_lines(s.doc()?, &s.space(), a, b).map_err(|e| bad(COMMAND, e))?;
let mut text = format!("*{name}, Custom pattern\n");
for line in lines {
text.push_str(&format!("{},{},{},{},{}", line.angle, line.origin.0, line.origin.1, line.delta.0, line.delta.1));
for dash in line.dashes {
text.push_str(&format!(",{dash}"));
}
text.push('\n');
}
Ok(json!({"pattern": name, "patternText": text}))
}
/// A PAT family repeats along an integer combination of the two tile edges.
/// The perpendicular neighbour is a second combination with determinant one.
fn captured_family(start: Vec2, end: Vec2, u: Vec2, v: Vec2, m: i32, n: i32) -> PatternLine {
let along = u * f64::from(m) + v * f64::from(n);
let period = along.len();
let dir = along / period;
// Extended Euclid: a*m + b*n = 1, so the neighbour is -b*u + a*v.
let (mut r, mut t) = (m, n);
let (mut a, mut b, mut c, mut d) = (1, 0, 0, 1);
while t != 0 {
let k = r / t;
(r, t) = (t, r % t);
(a, c) = (c, a - k * c);
(b, d) = (d, b - k * d);
}
let neighbour = (v * f64::from(a) - u * f64::from(b)) / f64::from(r);
let len = start.dist(end);
PatternLine {
origin: (start.x, start.y),
angle: dir.y.atan2(dir.x).to_degrees(),
delta: (neighbour.dot(dir), u.cross(v) / period),
dashes: if len >= period { Vec::new() } else { vec![len, len - period] },
}
}
fn capture_lines(d: &Drawing, space: &Space, a: Vec2, b: Vec2) -> std::result::Result<Vec<PatternLine>, &'static str> {
let low = Vec2::new(a.x.min(b.x), a.y.min(b.y));
let w = (a.x - b.x).abs();
let h = (a.y - b.y).abs();
if !w.is_finite() || !h.is_finite() || w < 1e-9 || h < 1e-9 {
return Err("Pick two opposite corners for the tile");
}
let entities = || d.space(space).into_iter().flat_map(|store| store.iter()).filter(|entity| d.is_visible(entity));
let (mut origin, mut u, mut v) = (low, Vec2::new(w, 0.), Vec2::new(0., h));
let mut guides = Vec::new();
for entity in entities() {
let EntityKind::LwPolyline(p) = &entity.kind else { continue };
if !p.closed || p.vertices.len() != 4 || p.vertices.iter().any(|q| q.bulge != 0.) {
continue;
}
let mut corners = [None; 4];
let mut order = [0usize; 4];
for (index, vertex) in p.vertices.iter().enumerate() {
let q = vertex.p;
let right = q.x > low.x + w / 2.;
let top = q.y > low.y + h / 2.;
let target = low + Vec2::new(if right { w } else { 0. }, if top { h } else { 0. });
if (q.x - target.x).abs() <= w * 0.002 && (q.y - target.y).abs() <= h * 0.002 {
order[index] = usize::from(right) + 2 * usize::from(top);
corners[order[index]] = Some(q);
}
}
if let [Some(bl), Some(br), Some(tl), Some(tr)] = corners
&& order.iter().zip(order.iter().cycle().skip(1)).all(|(a, b)| (a ^ b).count_ones() == 1)
&& (bl + (br - bl) + (tl - bl)).dist(tr) < w.min(h) * 1e-8
{
(origin, u, v) = (bl, br - bl, tl - bl);
guides.push(entity.handle);
}
}
let area = u.cross(v);
let coords = |p: Vec2| Vec2::new(p.cross(v) / area, u.cross(p) / area);
let world = |p: Vec2| u * p.x + v * p.y;
let mut families = Vec::new();
let mut add = |a: Vec2, b: Vec2, grid: bool| -> std::result::Result<(), &'static str> {
let (mut start, mut end) = (a - origin, b - origin);
let (s, e) = (coords(start), coords(end));
let inside = |q: Vec2| (-1e-8..=1.00000001).contains(&q.x) && (-1e-8..=1.00000001).contains(&q.y);
if !inside(s) || !inside(e) || start == end {
return Ok(());
}
let delta = e - s;
// Simple LINE geometry retains its original coordinates and short dash period.
let simple = if delta.x.abs() < 1e-14 {
Some((0, delta.y.signum() as i32))
} else {
(1..=128).find_map(|m| {
let m = m * delta.x.signum() as i32;
let n = f64::from(m) * delta.y / delta.x;
(n.abs() <= 128. && (n - n.round()).abs() < 1e-10).then_some((m, n.round() as i32))
})
};
let (mut m, mut n) = if let Some(dir) = simple.filter(|_| !grid) {
dir
} else {
// Shared vertices round identically, including on neighbouring tiles.
let snap = |p: Vec2| Vec2::new((p.x * 2048.).round(), (p.y * 2048.).round());
let (s, e) = (snap(s), snap(e));
if s == e {
return Err("A segment is too small for the tile capture precision.");
}
start = world(s / 2048.);
end = world(e / 2048.);
((e.x - s.x) as i32, (e.y - s.y) as i32)
};
if m < 0 || (m == 0 && n < 0) {
std::mem::swap(&mut start, &mut end);
(m, n) = (-m, -n);
}
let (mut gcd, mut k) = (m.abs(), n.abs());
while k != 0 {
(gcd, k) = (k, gcd % k);
}
if gcd != 0 {
families.push(captured_family(start, end, u, v, m / gcd, n / gcd));
}
Ok(())
};
for entity in entities() {
match &entity.kind {
EntityKind::Line(l) => add(l.a.xy(), l.b.xy(), false)?,
EntityKind::LwPolyline(p) if !guides.contains(&entity.handle) => {
for (i, vertex) in p.vertices.iter().enumerate() {
let next = p.vertices.get(i + 1).or_else(|| if p.closed { p.vertices.first() } else { None });
if let Some(next) = next
&& vertex.bulge == 0.
{
add(vertex.p, next.p, true)?;
}
}
}
_ => {}
}
}
if families.is_empty() {
return Err("No complete line segments in the selected tile.");
}
Ok(families)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn capture_l_from_drawing_without_a_dialog() {
let mut s = Session::new();
s.execute("rectang", &json!({"p1":[30,40], "p2":[40,50]})).unwrap();
for (a, b) in [([32, 42], [35, 42]), ([32, 42], [32, 46]), ([50, 60], [57, 60])] {
s.execute("line", &json!({"points":[a,b]})).unwrap();
}
// An almost coincident hidden guide would shift the origin if it were used.
let guide = s.execute("rectang", &json!({"p1":[30.01,40.01],"p2":[40.01,50.01]})).unwrap();
s.execute("hideobjects", &json!({"handles":[guide["handle"]]})).unwrap();
s.execute("layer.new", &json!({"name":"Hidden detail","current":true})).unwrap();
s.execute("line", &json!({"points":[[33,43],[36,43]]})).unwrap();
let detail = s.doc().unwrap().model.iter().last().unwrap().handle.hex();
s.execute("layer.current", &json!({"name":"0"})).unwrap();
s.execute("layoff", &json!({"handles":[detail]})).unwrap();
let result = s.execute(COMMAND, &json!({"first":[40,50],"second":[30,40],"name":"HEADLESS_L"})).unwrap();
let dest = s.execute("rectang", &json!({"p1":[0,0],"p2":[30,20]})).unwrap();
let mut apply = result;
apply["handles"] = json!([dest["handle"]]);
s.execute("hatch", &apply).unwrap();
let drawing = s.doc().unwrap();
let hatch = drawing.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h) } else { None }).unwrap();
assert_eq!(hatch.pattern, "HEADLESS_L");
assert_eq!(hatch.pattern_lines.len(), 2, "frame and exterior segment excluded");
for (angle, ink) in [(0., 3.), (90., 4.)] {
let line = hatch.pattern_lines.iter().find(|l| (l.angle - angle).abs() < 1e-8).unwrap();
assert_eq!(line.origin, (2., 2.));
assert_eq!(line.dashes, vec![ink, ink - 10.]);
assert!((line.delta.1 - 10.).abs() < 1e-8);
}
}
}
+16 -6
View File
@@ -195,9 +195,9 @@ fn separate(s: &mut Session, handle: Handle) -> Result<Vec<Handle>> {
}
/// Pattern, scale and angle (degrees) from the parameters.
fn properties(h: &mut Hatch, p: &Value) {
fn properties(h: &mut Hatch, p: &Value, local: Option<&[cadcraft_doc::library::PatternLine]>) {
if let Some(v) = str_param(p, "pattern") {
set_pattern(h, v);
set_pattern(h, v, local);
}
if let Some(x) = p.get("scale").and_then(Value::as_f64).filter(|x| x.is_finite() && *x > 0.0) {
h.scale = x;
@@ -222,11 +222,12 @@ pub(crate) fn takes_pattern(h: &Hatch, name: &str) -> bool {
/// Give `h` the pattern called `name` (HATCHEDIT's and Properties' pattern edit); false, and
/// nothing changes, for a blank name or one the hatch can't take ([`takes_pattern`]).
pub(crate) fn set_pattern(h: &mut Hatch, name: &str) -> bool {
pub(crate) fn set_pattern(h: &mut Hatch, name: &str, local: Option<&[cadcraft_doc::library::PatternLine]>) -> bool {
let name = name.trim();
if name.is_empty() || !takes_pattern(h, name) {
if name.is_empty() || (local.is_none() && !takes_pattern(h, name)) {
return false;
}
let keep_lines = h.pattern.eq_ignore_ascii_case(name) && !h.pattern_lines.is_empty();
h.pattern = name.to_ascii_uppercase();
h.solid = h.pattern == "SOLID";
// A named pattern, SOLID included, replaces the gradient fill; the renderer draws the
@@ -237,6 +238,10 @@ pub(crate) fn set_pattern(h: &mut Hatch, name: &str) -> bool {
// any other name is the hatch's own and keeps its definition.
if cadcraft_doc::library::pattern(&h.pattern).is_some() {
h.pattern_lines.clear();
} else if keep_lines {
return true;
} else if let Some(lines) = local {
h.pattern_lines = lines.to_vec();
} else if let Some(user) = super::patfile::user_pattern(&h.pattern) {
h.pattern_lines = user.lines;
}
@@ -479,7 +484,9 @@ pub(super) fn run_hatchedit(s: &mut Session, p: &Value) -> Result<Value> {
}
// Like the prompt: a pattern must be one CADCraft defines, SOLID, or the hatches' own (a
// pattern read from a file keeps its definition).
let local = str_param(p, "pattern").and_then(|n| super::drawing_lines(s.doc().ok()?, n.trim()));
if let Some(up) = str_param(p, "pattern").map(|v| v.trim().to_ascii_uppercase()).filter(|v| !v.is_empty())
&& local.is_none()
&& !defined_pattern(&up)
{
let d = s.doc()?;
@@ -507,7 +514,7 @@ pub(super) fn run_hatchedit(s: &mut Session, p: &Value) -> Result<Value> {
notes.push(format!("Hatch {}: {missing} new boundary loop(s) could not be linked; it is now non-associative.", handle.hex()));
}
}
properties(&mut h, p);
properties(&mut h, p, local.as_deref());
if let Some(g) = &grad {
g.apply(&mut h);
}
@@ -720,7 +727,10 @@ impl Interactive for HatchEditM {
(Ask::Pattern, _) => {
if let Some(t) = text.filter(|t| !t.is_empty()) {
let up = t.to_ascii_uppercase();
if cadcraft_doc::library::pattern(&up).is_none() && super::patfile::user_pattern(&up).is_none() {
if cadcraft_doc::library::pattern(&up).is_none()
&& super::patfile::user_pattern(&up).is_none()
&& super::drawing_lines(s.doc()?, &up).is_none()
{
s.echo(format!("Unknown pattern {up}."));
return Ok(Step::Continue);
}
+54 -5
View File
@@ -9,7 +9,7 @@
use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
use cadcraft_doc::library::files::{UserPattern, parse_pat};
use cadcraft_doc::library::{PatternLine, pattern, standard_patterns};
use cadcraft_doc::library::{PatternLine, is_reserved_pattern_name, standard_patterns};
use serde_json::{Value, json};
use super::super::helpers::support_text;
@@ -38,7 +38,7 @@ pub(crate) fn user_pattern_name(name: &str) -> Option<String> {
/// The line families a new hatch of pattern `name` carries: a user pattern's, else none (the
/// library's patterns are drawn and saved from the library).
pub(crate) fn lines_for(name: &str) -> Vec<PatternLine> {
if pattern(name).is_some() {
if is_reserved_pattern_name(name) {
return Vec::new();
}
user_pattern(name).map(|p| p.lines).unwrap_or_default()
@@ -70,6 +70,54 @@ pub fn pattern_choices() -> Vec<PatternChoice> {
v
}
fn embedded(d: &cadcraft_doc::Drawing) -> impl Iterator<Item = &cadcraft_doc::Hatch> {
let stores = std::iter::once(&d.model)
.chain(d.layouts.iter().map(|l| &l.entities))
.chain(d.blocks.values().filter(|b| b.xref_path.is_none()).map(|b| &b.entities));
stores.flat_map(|s| s.iter()).filter_map(|e| match &e.kind {
cadcraft_doc::EntityKind::Hatch(h) if !h.pattern_lines.is_empty() => Some(h),
_ => None,
})
}
pub(crate) fn drawing_lines(d: &cadcraft_doc::Drawing, name: &str) -> Option<Vec<PatternLine>> {
if is_reserved_pattern_name(name) {
return None;
}
embedded(d).find(|h| h.pattern.eq_ignore_ascii_case(name)).map(|h| h.pattern_lines.clone())
}
/// An embedded definition takes precedence over the session library in its own drawing.
pub fn pattern_choices_in(d: &cadcraft_doc::Drawing) -> Vec<PatternChoice> {
let mut choices = pattern_choices();
let mut seen = std::collections::HashSet::new();
for h in embedded(d) {
if !seen.insert(h.pattern.to_ascii_uppercase()) || is_reserved_pattern_name(&h.pattern) {
continue;
}
if let Some(c) = choices.iter_mut().find(|c| c.name.eq_ignore_ascii_case(&h.pattern)) {
c.lines.clone_from(&h.pattern_lines);
} else {
choices.push(PatternChoice { name: h.pattern.clone(), description: String::new(), lines: h.pattern_lines.clone() });
}
}
choices
}
/// Make embedded custom definitions available when opening the hatch manager in an older drawing.
pub fn register_drawing_patterns(d: &cadcraft_doc::Drawing) {
let mut user = store();
let mut known: std::collections::HashSet<_> = user.iter().map(|p| p.name.to_ascii_uppercase()).collect();
for h in embedded(d) {
if user.len() >= MAX_USER_PATTERNS {
break;
}
if !h.pattern_lines.is_empty() && known.insert(h.pattern.to_ascii_uppercase()) && !is_reserved_pattern_name(&h.pattern) {
user.push(UserPattern { name: h.pattern.clone(), description: String::new(), lines: h.pattern_lines.clone() });
}
}
}
/// Add the patterns of a `.pat` file's text (a pattern loaded before under the same name is
/// replaced). Returns the names added and the file's problems.
pub(crate) fn load(text: &str) -> (Vec<String>, Vec<String>) {
@@ -78,7 +126,7 @@ pub(crate) fn load(text: &str) -> (Vec<String>, Vec<String>) {
let mut added = Vec::new();
let mut user = store();
for p in parsed.items {
if pattern(&p.name).is_some() {
if is_reserved_pattern_name(&p.name) {
warnings.push(format!("{} is a built-in pattern; the built-in definition is kept", p.name));
continue;
}
@@ -97,14 +145,15 @@ pub(crate) fn load(text: &str) -> (Vec<String>, Vec<String>) {
}
/// Load the pattern file a HATCH call names (`patternFile` path or `patternText` contents).
pub(super) fn load_param(p: &Value) -> Result<()> {
pub(super) fn load_param(p: &Value) -> Result<Vec<String>> {
if let Some((text, source)) = support_text("hatch", p, "patternFile", "patternText")? {
let (added, warnings) = load(&text);
if added.is_empty() {
return Err(bad("hatch", format!("no hatch pattern could be read from {source}: {}", warnings.join("; "))));
}
return Ok(added);
}
Ok(())
Ok(Vec::new())
}
/// A `.pat` file typed at HATCH's pattern prompt: load it and return the pattern to use (the
+21 -2
View File
@@ -14,7 +14,7 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
pub(crate) const MAX_PICKS: usize = 1000;
/// The first prompt's keywords: what to pick.
const MODES: [&str; 4] = ["Points", "Objects", "oRigin", "Hatch"];
const MODES: [&str; 5] = ["Points", "Objects", "oRigin", "Hatch", "TileRect"];
/// What HATCHPICK picks.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -22,6 +22,8 @@ pub enum PickMode {
/// Internal points, each inside a closed boundary.
#[default]
Points,
/// Two opposite corners of a rectangular custom-pattern tile.
TileRect,
/// Closed boundary objects.
Objects,
/// One point: the pattern origin.
@@ -44,6 +46,7 @@ pub struct HatchPicks {
fn mode_named(t: &str) -> Option<PickMode> {
Some(match t.trim().to_ascii_lowercase().as_str() {
"points" | "p" => PickMode::Points,
"tilerect" | "tile" => PickMode::TileRect,
"objects" | "o" => PickMode::Objects,
"origin" | "r" => PickMode::Origin,
"hatch" | "h" => PickMode::Hatch,
@@ -134,6 +137,10 @@ impl Interactive for HatchPickM {
match self.mode {
None => Prompt::new("Enter what to pick", Accept::TEXT).kw(&MODES),
Some(PickMode::Points) => Prompt::new("Pick internal point", Accept::POINT).kw(&["Undo"]),
Some(PickMode::TileRect) => {
Prompt::new(if self.picks.is_empty() { "Pick first corner of tile" } else { "Pick opposite corner of tile" }, Accept::POINT)
.kw(&["Undo"])
}
Some(PickMode::Objects) => Prompt::new("Select objects", Accept::SELECT).kw(&["Undo"]),
Some(PickMode::Origin) => Prompt::new("Specify the pattern origin", Accept::POINT),
Some(PickMode::Hatch) => Prompt::new("Select hatch object", Accept::SELECT),
@@ -150,12 +157,13 @@ impl Interactive for HatchPickM {
};
match (mode, i) {
(_, Input::Cancel) => Ok(Step::Cancel),
(PickMode::Points | PickMode::Objects, Input::Keyword(k)) if k == "Undo" => {
(PickMode::Points | PickMode::TileRect | PickMode::Objects, Input::Keyword(k)) if k == "Undo" => {
if self.picks.pop().is_none() {
s.echo("Nothing to undo.");
}
Ok(Step::Continue)
}
(PickMode::TileRect, Input::Enter) => Ok(Step::Continue),
(PickMode::Points | PickMode::Objects, Input::Enter) => {
self.keep(s, mode);
Ok(Step::Done)
@@ -174,6 +182,17 @@ impl Interactive for HatchPickM {
}
Ok(Step::Continue)
}
(PickMode::TileRect, Input::Point(q)) => {
if self.count() < 2 {
self.picks.push(Pick::Point(q, Vec::new()));
}
if self.count() >= 2 {
self.keep(s, mode);
Ok(Step::Done)
} else {
Ok(Step::Continue)
}
}
(PickMode::Objects, Input::Pick(hs)) => {
let room = MAX_PICKS.saturating_sub(self.count());
let closed: Vec<Handle> = {
+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)) => {
+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())));
+5 -2
View File
@@ -204,6 +204,7 @@ fn set_override(dm: &mut cadcraft_doc::Dimension, field: &'static str, v: Value)
/// A `properties.set` call, checked before any object changes: the values every object takes,
/// and what the edits need to know beforehand.
struct Call<'a> {
hatch_lines: Option<Vec<cadcraft_doc::library::PatternLine>>,
p: &'a Value,
color: Option<Color>,
transparency: Option<Transparency>,
@@ -351,8 +352,10 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
let hatch_lines = str_param(p, "pattern").and_then(|n| crate::cmd::hatch::drawing_lines(d, n.trim()));
// A pattern must be one each hatch can take, as HATCHEDIT refuses others.
if let Some(v) = str_param(p, "pattern").filter(|v| !v.trim().is_empty())
&& hatch_lines.is_none()
&& hs.iter().any(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Hatch(x)) if !crate::cmd::hatch::takes_pattern(x, v)))
{
return Err(bad("properties.set", format!("unknown pattern {}", v.trim().to_ascii_uppercase())));
@@ -363,7 +366,7 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
}
let prep = Prepared::new(d, p, &hs);
let anno_scale = d.current_anno_scale();
let c = Call { p, color, transparency, thickness, lineweight, linetype, dim_style, text_style, dim_vars, prep, anno_scale };
let c = Call { hatch_lines, p, color, transparency, thickness, lineweight, linetype, dim_style, text_style, dim_vars, prep, anno_scale };
// A failed call changes nothing (a command's error doesn't undo what it did), so the drawing
// is taken for writing, and the layer made, only after every check.
let d = s.doc_mut()?;
@@ -805,7 +808,7 @@ fn dimension_posts(dm: &mut Dimension, c: &Call<'_>, used: &mut Used<'_>) {
fn hatch(ha: &mut Hatch, c: &Call<'_>, used: &mut Used<'_>) {
// HATCHEDIT's pattern edit (a blank name changes nothing, so it's ignored).
if let Some(v) = str_param(c.p, "pattern")
&& crate::cmd::hatch::set_pattern(ha, v)
&& crate::cmd::hatch::set_pattern(ha, v, c.hatch_lines.as_deref())
{
used.insert("pattern");
}
+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"));
}
}
@@ -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,6 +88,7 @@ pub const NO_FILES: &[&str] = &[
"blockspalette",
"dimoverride.clear",
"-dimstyle",
"-style",
"dimstyle.overrides",
"dimstyle.saveas",
"properties.describe",
@@ -241,6 +243,7 @@ pub const NO_FILES: &[&str] = &[
"gradient",
"boundary",
"region",
"hatch.capture",
"hatchedit",
"hatchgenerateboundary",
"hatchpick",
+1 -1
View File
@@ -57,7 +57,7 @@ pub use cadcraft_geom as geom;
pub use cadcraft_render as render;
pub use cmd::blocks::WblockPicks;
pub use cmd::blocks::attedit::{AttributeRow, attributes};
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices};
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices, pattern_choices_in, register_drawing_patterns};
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use prompt::{Accept, AttribAsk, AttribEntry, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
+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)),
+111
View File
@@ -0,0 +1,111 @@
//! ACADVER is the program's release as text, as AutoCAD documents it, so `(atof (getvar
//! "ACADVER"))` reads a number from it. It is read-only, and the drawing's `$ACADVER` stays the
//! file version a save writes, so a drawing read from a 2000 DXF saves as one.
use cadcraft_engine::Session;
use cadcraft_engine::lisp::value::Value;
use serde_json::json;
/// The release text `getvar` and `(getvar "ACADVER")` report.
const RELEASE: &str = "24.3s (CADCraft)";
/// A 2000 DXF (`$ACADVER` `AC1015`) holding one line.
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n\
0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n10.0\n21\n0.0\n31\n0.0\n\
0\nENDSEC\n0\nEOF\n";
/// A LISP expression's value, or its error message.
fn lisp(s: &mut Session, code: &str) -> Result<Value, String> {
match s.lisp_eval(code, false, true, Vec::new()) {
Ok(Some(Ok(v))) => Ok(v),
Ok(Some(Err(e))) => Err(e),
Ok(None) => Err("did not finish".into()),
Err(e) => Err(e.to_string()),
}
}
/// GETVAR's value.
fn getvar(s: &mut Session, name: &str) -> serde_json::Value {
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
}
/// The `$ACADVER` a DXF text declares.
fn file_version(text: &str) -> Option<String> {
let l: Vec<&str> = text.lines().map(str::trim).collect();
let at = l.windows(2).position(|w| w == ["9", "$ACADVER"])?;
l.get(at + 2).filter(|c| **c == "1").and_then(|_| l.get(at + 3)).map(|v| (*v).to_string())
}
#[test]
fn getvar_gives_the_release_text_and_atof_reads_the_number() {
let mut s = Session::new();
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
assert_eq!(getvar(&mut s, "acadver"), json!(RELEASE), "lower-case names work");
assert!(matches!(lisp(&mut s, "(getvar \"ACADVER\")"), Ok(Value::Str(t)) if &*t == RELEASE), "a LISP string");
assert!(matches!(lisp(&mut s, "(atof (getvar \"ACADVER\"))"), Ok(Value::Real(r)) if (r - 24.3).abs() < 1e-9), "(atof) reads the release number");
}
#[test]
fn setvar_refuses_acadver_and_changes_nothing() {
let mut s = Session::new();
let before = s.state().unwrap().doc.header.str("ACADVER", "");
let e = s.execute("setvar", &json!({ "name": "ACADVER", "value": "AC1027" })).unwrap_err().to_string();
assert!(e.contains("read-only"), "{e}");
assert!(lisp(&mut s, "(setvar \"ACADVER\" \"AC1027\")").is_err(), "AutoLISP's setvar too");
// Typed at the command line, SETVAR reports the variable as read-only at its name prompt.
s.cmdline("setvar acadver").unwrap();
assert!(s.log.iter().any(|l| l == &format!("ACADVER = {RELEASE} (read only)")), "{:?}", s.log);
// Neither the release text nor the drawing's file version moved.
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), before);
assert_eq!(before, "AC1032");
}
#[test]
fn a_2000_drawing_saves_as_2000() {
crate::refedit_xref::hooks();
let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("acadver-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("r2000.dxf");
let name = path.to_string_lossy().into_owned();
let mut s = Session::empty();
s.open_drawing(cadcraft_io::read_dxf(DXF.as_bytes()).unwrap(), "r2000.dxf", Some(name.clone()));
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1015", "read as 2000");
assert_eq!(cadcraft_io::save_version(&s.state().unwrap().doc), cadcraft_io::Version::R2000);
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE), "still the release text");
s.execute("qsave", &json!({})).unwrap();
let saved = std::fs::read_to_string(&path).unwrap();
assert_eq!(file_version(&saved).as_deref(), Some("AC1015"), "the file keeps its 2000 version");
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1015");
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
assert_eq!(cadcraft_io::read_dxf(saved.as_bytes()).unwrap().header.str("ACADVER", ""), "AC1015", "and reopens as 2000");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_dollar_name_cannot_change_the_file_version() {
let mut s = Session::new();
let e = s.execute("setvar", &json!({ "name": "$ACADVER", "value": "AC1027" })).unwrap_err().to_string();
assert!(e.contains("read-only"), "{e}");
assert!(lisp(&mut s, "(setvar \"$ACADVER\" \"AC1015\")").is_err(), "AutoLISP's setvar too");
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1032", "the save version did not move");
assert!(cadcraft_engine::sysvars::is_read_only("$acadver"), "SETVAR's prompt sees it as read-only too");
// Other `$` names still reach the header as before, in LISP's units.
assert!(lisp(&mut s, "(setvar \"$ANGBASE\" (/ pi 2))").is_ok());
assert!(matches!(lisp(&mut s, "(getvar \"$ANGBASE\")"), Ok(Value::Real(r)) if (r - std::f64::consts::FRAC_PI_2).abs() < 1e-9));
let r = s.execute("setvar", &json!({ "name": "$OSMODE", "value": 9 })).unwrap();
assert_eq!(r["value"], json!(9), "{r}");
}
#[test]
fn listings_show_the_release_text_without_a_drawing() {
let mut s = Session::empty();
let all = s.execute("sysvars", &json!({})).unwrap();
let text = all.to_string();
assert!(text.contains(RELEASE), "{text}");
let mut s = Session::new();
let all = s.execute("sysvars", &json!({})).unwrap().to_string();
assert!(all.contains(RELEASE) && !all.contains("\"AC1032\""), "{all}");
}
+386
View File
@@ -0,0 +1,386 @@
//! Legacy system variables a LISP routine saves and restores around its work: DIMASO (obsolete in
//! AutoCAD, which reports and sets DIMASSOC through it), TEXTEVAL, REGENMODE (kept in the drawing
//! and its DXF header) and POPUPS (read-only). Before them `(getvar "DIMASO")` read nil, so
//! `(setq o (getvar "DIMASO")) … (setvar "DIMASO" o)` failed and the routine left the drawing's
//! associativity changed.
use cadcraft_engine::Session;
use cadcraft_engine::lisp::value::{Value as LispValue, to_text};
use serde_json::{Value, json};
fn getvar(s: &mut Session, name: &str) -> Value {
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
}
fn setvar(s: &mut Session, name: &str, value: Value) -> bool {
s.execute("setvar", &json!({ "name": name, "value": value })).is_ok()
}
/// The value of a LISP expression, or the error it left.
fn eval(s: &mut Session, src: &str) -> Result<LispValue, String> {
match s.lisp_eval(src, false, true, Vec::new()) {
Ok(Some(v)) => v,
Ok(None) => Err("no value".into()),
Err(e) => Err(e.to_string()),
}
}
/// `(getvar name)` as the integer a routine receives.
fn lisp_getvar(s: &mut Session, name: &str) -> i64 {
let v = eval(s, &format!("(getvar \"{name}\")")).unwrap_or_else(|e| panic!("{name}: {e}"));
let n = v.as_number().unwrap_or_else(|| panic!("{name} is not a number"));
assert_eq!(n.fract(), 0.0, "{name} is a whole number");
n as i64
}
/// `(setvar name value)` from LISP: whether it was accepted.
fn lisp_setvar(s: &mut Session, name: &str, value: &str) -> bool {
eval(s, &format!("(setvar \"{name}\" {value})")).is_ok()
}
/// The DXF pairs `(group code, value)` of a file, both trimmed.
fn pairs(text: &str) -> Vec<(i32, String)> {
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let mut out = Vec::new();
for chunk in lines.chunks(2) {
let [code, value] = chunk else { break };
let Ok(c) = code.parse::<i32>() else { continue };
out.push((c, (*value).to_string()));
}
out
}
/// The HEADER variable names a DXF text writes (the value after each group code 9).
fn header_names(text: &str) -> Vec<String> {
pairs(text).iter().filter(|(c, _)| *c == 9).map(|(_, v)| v.trim_start_matches('$').to_string()).collect()
}
/// The integer a header variable is written with, as `(group code, value)` after its name.
fn header_int(text: &str, name: &str) -> Option<(i32, String)> {
let ps = pairs(text);
let i = ps.iter().position(|(c, v)| *c == 9 && v.trim_start_matches('$') == name)?;
ps.get(i + 1).cloned()
}
#[test]
fn fresh_values_are_integers_a_routine_reads() {
let mut s = Session::new();
for (name, want) in [("DIMASO", 1), ("TEXTEVAL", 0), ("REGENMODE", 1), ("POPUPS", 1)] {
assert_eq!(getvar(&mut s, name), json!(want), "{name}");
assert_eq!(lisp_getvar(&mut s, name), want, "{name} through getvar");
let kind = eval(&mut s, &format!("(type (getvar \"{name}\"))")).unwrap();
assert_eq!(to_text(&kind, true), "INT", "{name} is an integer to LISP");
}
// The list a routine sees (`SETVAR ?`) carries them too.
let all = cadcraft_engine::sysvars::list(&s);
for name in ["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"] {
assert_eq!(all.get(name), Some(&getvar(&mut s, name)), "{name} listed");
}
}
#[test]
fn a_routine_saving_and_restoring_each_one_leaves_it_as_it_was() {
let mut s = Session::new();
for (name, changed) in [("DIMASO", "0"), ("TEXTEVAL", "1"), ("REGENMODE", "0")] {
let before = lisp_getvar(&mut s, name);
// (setq o (getvar X)) … (setvar X o) must give back exactly what it read.
assert!(eval(&mut s, &format!("(setq o (getvar \"{name}\"))")).is_ok(), "{name} readable");
assert!(lisp_setvar(&mut s, name, changed), "{name} takes {changed}");
assert_ne!(lisp_getvar(&mut s, name), before, "{name} changed by {changed}");
assert!(eval(&mut s, &format!("(setvar \"{name}\" o)")).is_ok(), "{name} restored");
assert_eq!(lisp_getvar(&mut s, name), before, "{name} back to {before}");
}
// REGENMODE is the drawing's, kept in its header; TEXTEVAL only the session's.
assert_eq!(s.doc().unwrap().header.i64("REGENMODE", 1), 1);
}
#[test]
fn dimaso_restores_the_dimassoc_mode_it_turned_off() {
// The routine's save/restore through DIMASO, for each associative mode.
for mode in [1, 2] {
let mut s = Session::new();
assert!(setvar(&mut s, "DIMASSOC", json!(mode)));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1), "DIMASO follows DIMASSOC {mode}");
let o = eval(&mut s, "(getvar \"DIMASSOC\")").unwrap().as_number().unwrap();
assert!(lisp_setvar(&mut s, "DIMASO", "0"));
assert_eq!(getvar(&mut s, "DIMASO"), json!(0));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "DIMASO 0 turns associativity off");
assert!(lisp_setvar(&mut s, "DIMASO", "1"));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
assert_eq!(eval(&mut s, "(getvar \"DIMASSOC\")").unwrap().as_number(), Some(o), "DIMASO 1 puts back the DIMASSOC {mode} the routine read");
}
// Set directly, without ever switching it off first, DIMASO 1 leaves the mode alone.
let mut s = Session::new();
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1));
// No non-zero mode was seen: turning associativity back on gives AutoCAD's 2.
let mut s = Session::new();
assert!(setvar(&mut s, "DIMASSOC", json!(0)));
assert!(setvar(&mut s, "DIMASO", json!(0)));
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2), "none was seen: the default 2");
// A drawing whose saved DIMASSOC is no mode DIMASO can restore (a hostile file) gives 2.
let mut s = Session::new();
s.doc_mut().unwrap().header.set_i64("DIMASSOC", 5);
assert!(setvar(&mut s, "DIMASO", json!(0)));
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2));
// Such a mode is not associative, and DIMASO 1 turns associativity on from it too.
s.doc_mut().unwrap().header.set_i64("DIMASSOC", 5);
assert_eq!(getvar(&mut s, "DIMASO"), json!(0));
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2));
}
#[test]
fn typed_setvar_still_takes_digits() {
for (name, digits) in [("DIMASO", "0"), ("TEXTEVAL", "1"), ("REGENMODE", "0")] {
let want = json!(digits.parse::<i64>().unwrap());
let dollar = format!("${name}");
// SETVAR with the name, the bare name, and the `$` form, as typed at the command line.
for lines in [vec!["setvar", name, digits], vec![name, digits], vec!["setvar", dollar.as_str(), digits]] {
let mut s = Session::new();
for line in &lines {
s.cmdline(line).unwrap();
}
assert_eq!(getvar(&mut s, name), want, "typed {lines:?}");
}
// A routine that types the command passes its answers the same way.
let mut s = Session::new();
eval(&mut s, &format!("(command \"SETVAR\" \"{name}\" \"{digits}\")")).unwrap();
assert_eq!(getvar(&mut s, name), want, "(command \"SETVAR\" {name})");
// Typed words are still refused.
let mut s = Session::new();
let before = getvar(&mut s, name);
for line in ["setvar", name, "two"] {
s.cmdline(line).unwrap();
}
assert_eq!(getvar(&mut s, name), before, "typed word refused for {name}");
}
}
#[test]
fn a_new_drawing_writes_regenmode() {
let mut s = Session::new();
// The first drawing, then a new metric and a new imperial one.
for metric in [None, Some(true), Some(false)] {
if let Some(metric) = metric {
s.new_drawing(metric);
}
let text = cadcraft_io::write_dxf(s.doc().unwrap());
assert_eq!(header_int(&text, "REGENMODE"), Some((70, "1".to_string())), "new drawing, metric {metric:?}");
}
}
#[test]
fn hostile_values_are_refused_and_change_nothing() {
let mut s = Session::new();
for (name, v) in [
("REGENMODE", json!(2)),
("REGENMODE", json!(-1)),
("REGENMODE", json!(1.5)),
("REGENMODE", json!("two")),
("REGENMODE", Value::Null),
("TEXTEVAL", json!(-1)),
("TEXTEVAL", json!(2)),
("TEXTEVAL", json!("two")),
("TEXTEVAL", Value::Null),
("DIMASO", json!(3)),
("DIMASO", json!(-1)),
("DIMASO", json!(0.5)),
("DIMASO", json!("two")),
("DIMASO", Value::Null),
// Text a program or a routine passes is refused even when it spells a number.
("REGENMODE", json!("0")),
("TEXTEVAL", json!("1")),
("DIMASO", json!("0")),
("TEXTEVAL", json!(true)),
] {
let before = getvar(&mut s, name);
assert!(!setvar(&mut s, name, v.clone()), "{name} = {v} refused");
assert_eq!(getvar(&mut s, name), before, "{name} unchanged by {v}");
}
// The drawing's associativity is untouched by a refused DIMASO.
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(!setvar(&mut s, "DIMASO", json!(3)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1));
// The same through LISP, where nil and a NaN real arrive as values a variable can't take.
assert!(!lisp_setvar(&mut s, "REGENMODE", "nil"), "nil refused");
assert!(!lisp_setvar(&mut s, "DIMASO", "3"), "DIMASO 3 refused");
assert!(!lisp_setvar(&mut s, "DIMASO", "\"two\""), "DIMASO text refused");
for (name, v) in [("DIMASO", "\"0\""), ("TEXTEVAL", "\"1\""), ("REGENMODE", "\"0\"")] {
assert!(!lisp_setvar(&mut s, name, v), "{name} text {v} refused");
}
assert!(!lisp_setvar(&mut s, "TEXTEVAL", "-1"), "TEXTEVAL -1 refused");
// (- (exp 1000) (exp 1000)) is NaN: not a number JSON can hold, so it is refused as one.
assert!(!lisp_setvar(&mut s, "TEXTEVAL", "(- (exp 1000) (exp 1000))"), "NaN refused");
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(0));
}
#[test]
fn popups_is_read_only() {
let mut s = Session::new();
assert!(cadcraft_engine::sysvars::is_read_only("popups"));
for v in [json!(1), json!(0), json!("1")] {
let e = s.execute("setvar", &json!({ "name": "POPUPS", "value": v })).unwrap_err().to_string();
assert!(e.contains("read-only"), "{v}: {e}");
}
assert!(!lisp_setvar(&mut s, "POPUPS", "0"));
assert_eq!(getvar(&mut s, "POPUPS"), json!(1));
}
#[test]
fn regenmode_is_saved_in_the_dxf_header_and_read_back() {
let mut s = Session::new();
assert!(setvar(&mut s, "REGENMODE", json!(0)));
let text = cadcraft_io::write_dxf(s.doc().unwrap());
assert!(header_names(&text).contains(&"REGENMODE".to_string()), "$REGENMODE is in the header (has {:?})", header_names(&text));
assert_eq!(header_int(&text, "REGENMODE"), Some((70, "0".to_string())), "$REGENMODE is group 70, 0");
// A reopened drawing has the value it was saved with, and saves it back.
let mut back = Session::new();
back.open_drawing(cadcraft_io::read_dxf(text.as_bytes()).unwrap(), "regenmode.dxf", None);
assert_eq!(getvar(&mut back, "REGENMODE"), json!(0));
let again = cadcraft_io::write_dxf(back.doc().unwrap());
assert_eq!(header_int(&again, "REGENMODE"), Some((70, "0".to_string())));
}
#[test]
fn texteval_dimaso_and_popups_are_not_saved() {
let mut s = Session::new();
assert!(setvar(&mut s, "TEXTEVAL", json!(1)));
let text = cadcraft_io::write_dxf(s.doc().unwrap());
let names = header_names(&text);
for name in ["TEXTEVAL", "DIMASO", "POPUPS"] {
assert!(!names.contains(&name.to_string()), "{name} is not a header variable (has {names:?})");
}
// TEXTEVAL is the session's: a drawing opened in this session does not bring its own value.
s.open_drawing(cadcraft_io::read_dxf(text.as_bytes()).unwrap(), "no_legacy_vars.dxf", None);
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(1), "opening a drawing leaves the session's value");
}
#[test]
fn dimaso_remembers_the_mode_of_each_open_drawing() {
// The mode DIMASO turns off is the drawing's, not the session's: two open drawings switched
// between each put back the DIMASSOC mode they had.
let mut s = Session::new();
let first = s.active;
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(setvar(&mut s, "DIMASO", json!(0)));
let second = s.new_drawing(true);
assert_eq!(second, first + 1);
assert!(setvar(&mut s, "DIMASSOC", json!(2)));
assert!(setvar(&mut s, "DIMASO", json!(0)));
s.execute("document.switch", &json!({ "index": first })).unwrap();
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "the first drawing restores its own mode");
s.execute("document.switch", &json!({ "index": second })).unwrap();
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2), "the second drawing restores its own mode");
}
#[test]
fn the_dollar_forms_are_the_same_variables() {
// The DXF header writes these names with a `$` ($DIMASO, $TEXTEVAL, $REGENMODE, $POPUPS), so
// the command line takes them that way too, in any case and with spaces around them.
let mut s = Session::new();
for name in ["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"] {
let plain = getvar(&mut s, name);
let dollar = format!("${name}");
assert_eq!(getvar(&mut s, &dollar), plain, "{dollar} reads like {name}");
let typed = format!(" ${} ", name.to_ascii_lowercase());
assert_eq!(getvar(&mut s, &typed), plain, "{typed:?} reads like {name}");
assert_eq!(cadcraft_engine::sysvars::is_read_only(&dollar), cadcraft_engine::sysvars::is_read_only(name), "{dollar} read-only as {name}");
}
// DIMASO through its DXF name still turns DIMASSOC off and puts its mode back.
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(setvar(&mut s, "$DIMASO", json!(0)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "$DIMASO 0 turns associativity off");
assert!(setvar(&mut s, " $dimaso ", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "$DIMASO 1 puts the mode back");
// TEXTEVAL: set under one name, read under the other.
assert!(setvar(&mut s, "$TEXTEVAL", json!(1)));
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(1), "$TEXTEVAL set TEXTEVAL");
assert!(setvar(&mut s, "TEXTEVAL", json!(0)));
assert_eq!(getvar(&mut s, "$TEXTEVAL"), json!(0));
// REGENMODE takes only the values its plain name takes, and stores the ones it takes.
assert!(!setvar(&mut s, "$REGENMODE", json!(2)), "$REGENMODE 2 is out of range");
assert_eq!(getvar(&mut s, "REGENMODE"), json!(1), "a refused $REGENMODE changed nothing");
assert!(!setvar(&mut s, "$REGENMODE", json!(-1)), "$REGENMODE -1 is out of range");
assert!(setvar(&mut s, "$REGENMODE", json!(0)));
assert_eq!(getvar(&mut s, "$REGENMODE"), json!(0));
assert_eq!(getvar(&mut s, "REGENMODE"), json!(0));
assert_eq!(s.doc().unwrap().header.i64("REGENMODE", 1), 0, "$REGENMODE stored the drawing's value");
// POPUPS is read-only under its DXF name too.
for v in [json!(0), json!("1")] {
let e = s.execute("setvar", &json!({ "name": "$POPUPS", "value": v })).unwrap_err().to_string();
assert!(e.contains("read-only"), "$POPUPS {v}: {e}");
}
assert!(!lisp_setvar(&mut s, "$POPUPS", "0"));
assert_eq!(getvar(&mut s, "$POPUPS"), json!(1));
}
#[test]
fn other_dollar_names_keep_their_own_handling() {
// Only those four take a `$`: LISP's angle variables convert radians for the plain name, and
// `$OSMODE` stays a name of its own rather than becoming the session's OSMODE.
let mut s = Session::new();
assert!(eval(&mut s, "(setvar \"$ANGBASE\" (/ pi 2))").is_ok());
let base = eval(&mut s, "(getvar \"$ANGBASE\")").unwrap().as_number().unwrap_or(f64::NAN);
assert!((base - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "(getvar \"$ANGBASE\") gives pi/2, not {base}");
let osmode = eval(&mut s, "(setvar \"$OSMODE\" 9)").unwrap();
assert_eq!(to_text(&osmode, true), "9", "(setvar \"$OSMODE\" 9) returns 9");
assert_eq!(getvar(&mut s, "OSMODE"), json!(4133), "$OSMODE is not the session's OSMODE");
assert_eq!(getvar(&mut s, "$OSMODE"), json!(9), "$OSMODE still reads back what it was set to");
}
#[test]
fn undo_puts_back_the_mode_dimaso_remembers() {
// The mode DIMASO remembers goes back with DIMASSOC when the changes are undone.
let mut s = Session::new();
for (name, v) in [("DIMASSOC", 1), ("DIMASO", 0), ("DIMASSOC", 2), ("DIMASO", 0)] {
assert!(setvar(&mut s, name, json!(v)), "{name} {v}");
}
s.cmdline("u").unwrap();
s.cmdline("u").unwrap();
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "back to after the first DIMASO 0");
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "the mode remembered then, not the later 2");
}
#[test]
fn repeated_dollars_are_the_same_variables() {
let mut s = Session::new();
assert!(!lisp_setvar(&mut s, "$$REGENMODE", "2"), "out of range under any number of $");
assert_eq!(getvar(&mut s, "REGENMODE"), json!(1), "a refused $$REGENMODE changed nothing");
assert!(!setvar(&mut s, "$$$POPUPS", json!(0)), "read-only under any number of $");
assert!(cadcraft_engine::sysvars::is_read_only("$$POPUPS"));
}
#[test]
fn dimaso_on_while_already_on_leaves_the_drawing_unmodified() {
let mut s = Session::new();
assert_eq!(getvar(&mut s, "DBMOD"), json!(0), "a fresh drawing");
assert!(setvar(&mut s, "DIMASO", json!(1)), "already on");
assert_eq!(getvar(&mut s, "DBMOD"), json!(0), "nothing changed, so not modified");
}
#[test]
fn the_remembered_mode_is_not_a_variable_and_is_not_reported_lost() {
let mut s = Session::new();
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(setvar(&mut s, "DIMASO", json!(0)));
for name in ["CADCRAFT_DIMASO_MODE", "$CADCRAFT_DIMASO_MODE", "cadcraft_dimaso_mode"] {
assert!(s.execute("getvar", &json!({ "name": name })).is_err(), "{name} is not a variable");
assert!(!setvar(&mut s, name, json!(2)), "{name} cannot be set");
}
assert!(eval(&mut s, "(getvar \"CADCRAFT_DIMASO_MODE\")").map_or(true, |v| to_text(&v, false) == "nil"));
// Saved and read back, the drawing has lost nothing a save keeps.
let before = s.doc().unwrap().clone();
let after = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&before).as_bytes()).unwrap();
let cmp = cadcraft_io::roundtrip::compare(&before, &after, &cadcraft_io::roundtrip::Options::default());
assert!(!cmp.differences.iter().any(|d| d.place.contains("DIMASO")), "{:?}", cmp.differences.iter().map(|d| &d.place).collect::<Vec<_>>());
}
+4
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;
@@ -103,6 +104,7 @@ mod layout_prompts;
mod leader_command;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod leader_text_scale;
mod legacy_sysvars;
mod lisp_corpus;
mod lisp_findfile;
mod lisp_undo_in_routine;
@@ -198,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;
+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);
}
}
+17 -14
View File
@@ -122,19 +122,19 @@ fn page_setup_takes_a_device_and_its_papers() {
/// turn back to the axes the user gave, and PLOT hands them on that way (#1266).
fn a_landscape_page_gets_the_papers_margins_back() {
let mut s = session();
s.execute("plottermanager", &json!({"action": "new", "name": "Banner Printer", "output": "pdf"})).unwrap();
s.execute("plottermanager", &json!({"action": "new", "name": "Landscape Banner Printer", "output": "pdf"})).unwrap();
let paper = json!({"name": "Banner", "width": 400, "height": 200, "margins": [150, 0, 150, 0]});
s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": paper})).unwrap();
s.execute("plottermanager", &json!({"action": "set", "name": "Landscape Banner Printer", "paper": paper})).unwrap();
// Stored portrait, 200 x 400, the side margins on the long axis.
let stored = |s: &mut Session| {
let r = s.execute("plottermanager", &json!({"action": "get", "name": "Banner Printer"})).unwrap();
let r = s.execute("plottermanager", &json!({"action": "get", "name": "Landscape Banner Printer"})).unwrap();
r["papers"].as_array().unwrap().iter().find(|p| p["name"] == "Banner").cloned().unwrap()
};
let p = stored(&mut s);
assert_eq!((p["width"].as_f64(), p["height"].as_f64()), (Some(200.0), Some(400.0)));
assert_eq!(p["margins"], json!([0.0, 150.0, 0.0, 150.0]));
s.execute("pagesetup", &json!({"layout": "Layout1", "device": "Banner Printer", "paper": "Banner", "landscape": true})).unwrap();
s.execute("pagesetup", &json!({"layout": "Layout1", "device": "Landscape Banner Printer", "paper": "Banner", "landscape": true})).unwrap();
let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone();
assert_eq!((page.width_mm, page.height_mm, page.margins_mm), (200.0, 400.0, [150.0, 0.0, 150.0, 0.0]));
// The 400 x 200 sheet's printable area is 100 x 200 mm, not the whole sheet.
@@ -150,8 +150,11 @@ fn a_landscape_page_gets_the_papers_margins_back() {
assert_eq!(o["margins"], json!([150.0, 0.0, 150.0, 0.0]));
// Naming the paper landscape again at a new size keeps the margins' axes as well.
s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": {"name": "Banner", "width": 500, "height": 200}}))
.unwrap();
s.execute(
"plottermanager",
&json!({"action": "set", "name": "Landscape Banner Printer", "paper": {"name": "Banner", "width": 500, "height": 200}}),
)
.unwrap();
let p = stored(&mut s);
assert_eq!((p["width"].as_f64(), p["height"].as_f64()), (Some(200.0), Some(500.0)));
assert_eq!(p["margins"], json!([0.0, 150.0, 0.0, 150.0]), "the margins keep the short sides");
@@ -163,11 +166,11 @@ fn a_landscape_page_gets_the_papers_margins_back() {
/// instead of being saved against the wrong axes (#1266).
fn an_orientation_only_pagesetup_turns_the_retained_margins() {
let mut s = session();
s.execute("plottermanager", &json!({"action": "new", "name": "Banner Printer", "output": "pdf"})).unwrap();
s.execute("plottermanager", &json!({"action": "new", "name": "Turning Banner Printer", "output": "pdf"})).unwrap();
let paper = json!({"name": "Banner", "width": 400, "height": 200, "margins": [150, 0, 150, 0]});
s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": paper})).unwrap();
s.execute("plottermanager", &json!({"action": "set", "name": "Turning Banner Printer", "paper": paper})).unwrap();
// The landscape page carries the margins on its 400 mm sides: 150 mm left and right.
s.execute("pagesetup", &json!({"layout": "Layout1", "device": "Banner Printer", "paper": "Banner", "landscape": true})).unwrap();
s.execute("pagesetup", &json!({"layout": "Layout1", "device": "Turning Banner Printer", "paper": "Banner", "landscape": true})).unwrap();
let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone();
assert_eq!((page.width_mm, page.height_mm, page.margins_mm), (200.0, 400.0, [150.0, 0.0, 150.0, 0.0]));
@@ -345,23 +348,23 @@ fn plotwindow_picks_both_corners_with_ortho_on() {
#[test]
fn paper_margins_are_checked_against_their_own_axis() {
let mut s = session();
s.execute("plottermanager", &json!({"action": "new", "name": "Banner Printer", "output": "png"})).unwrap();
let paper = |margins: Value| json!({"action": "set", "name": "Banner Printer", "paper": {"name": "Banner", "width": 400, "height": 200, "margins": margins}});
s.execute("plottermanager", &json!({"action": "new", "name": "Margin Banner Printer", "output": "png"})).unwrap();
let paper = |margins: Value| json!({"action": "set", "name": "Margin Banner Printer", "paper": {"name": "Banner", "width": 400, "height": 200, "margins": margins}});
// 250 mm of bottom + top margin leaves no printable height on a 200 mm paper.
assert!(s.execute("plottermanager", &paper(json!([0, 250, 0, 0]))).is_err());
// 300 mm of left + right margin still leaves 100 mm of printable width on a 400 mm paper.
assert!(s.execute("plottermanager", &paper(json!([150, 0, 150, 0]))).is_ok());
// The paper is stored portrait and the margins turn with it: the 100 x 200 printable area
// of the requested sheet stays 200 x 100 on the stored 200 x 400 one.
let stored = s.execute("plottermanager", &json!({"action": "get", "name": "Banner Printer"})).unwrap();
let stored = s.execute("plottermanager", &json!({"action": "get", "name": "Margin Banner Printer"})).unwrap();
let banner = stored["papers"].as_array().unwrap().iter().find(|p| p["name"] == "Banner").unwrap().clone();
assert_eq!((banner["width"].as_f64().unwrap(), banner["height"].as_f64().unwrap()), (200.0, 400.0));
assert_eq!(banner["margins"], json!([0.0, 150.0, 0.0, 150.0]));
// Setting the same sheet again without margins keeps them: the stored margins belong to the
// portrait sheet and turn back before the per-axis check.
s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": {"name": "Banner", "width": 400, "height": 200}}))
s.execute("plottermanager", &json!({"action": "set", "name": "Margin Banner Printer", "paper": {"name": "Banner", "width": 400, "height": 200}}))
.unwrap();
let stored = s.execute("plottermanager", &json!({"action": "get", "name": "Banner Printer"})).unwrap();
let stored = s.execute("plottermanager", &json!({"action": "get", "name": "Margin Banner Printer"})).unwrap();
let banner = stored["papers"].as_array().unwrap().iter().find(|p| p["name"] == "Banner").unwrap().clone();
assert_eq!(banner["margins"], json!([0.0, 150.0, 0.0, 150.0]));
}
+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);
}
}
}
+4 -1
View File
@@ -35,5 +35,8 @@ craft-pdf = { workspace = true, features = ["read"] }
# Inspect DWG output only where craft-dwg builds its native bridge. An unconditional
# dev-dependency also builds acadrust during --all-targets, breaking FreeBSD aarch64 (#2526).
# The storytold/acadrust fork at tag `storytold/v0.6.6` (upstream v0.6.6), the source craft-dwg moves
# to in storytold/craft-libs#4762; until craft-libs is repinned, craft-dwg still takes the identical
# crates.io 0.6.6.
[target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dev-dependencies]
acadrust = "0.6.6"
acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "5d5c482b3fcb3dc77e8281474461760f32959436" }
+53 -1
View File
@@ -16,7 +16,9 @@ use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number, proxy_has_string_stream};
use cadcraft_doc::foreign::{
Foreign, ForeignExtra, ForeignKey, ForeignObject, VertexId, class_group, class_index, class_number, proxy_has_string_stream,
};
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown};
use craft_dxf::{SectionRef, Tag, Version};
@@ -73,6 +75,8 @@ const OWN_APPS: &[&str] = cadcraft_doc::RESERVED_XDATA_APPS;
/// 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.
@@ -332,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)
+8 -1
View File
@@ -169,7 +169,11 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
w.f(38, elevation);
}
thickness(w, e);
for v in &p.vertices {
// The vertex identifiers the file gave the polyline (DXF 2010 and later), while its
// vertices are where they were read: geometric constraints name its segments by them.
let kept = d.foreign.entities.get(&e.handle).map(|x| x.vertex_ids.as_slice()).filter(|_| cx.target >= Version::R2010);
let ids = kept.and_then(|kept| cadcraft_doc::foreign::vertex_ids_for(kept, p.vertices.iter().map(|v| (v.p.x, v.p.y))));
for (i, v) in p.vertices.iter().enumerate() {
w.p2(10, v.p);
if v.start_width != 0.0 || v.end_width != 0.0 {
w.f(40, v.start_width);
@@ -178,6 +182,9 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
if v.bulge != 0.0 {
w.f(42, v.bulge);
}
if let Some(id) = ids.as_ref().and_then(|ids| ids.get(i)).filter(|id| **id != 0) {
w.i(91, i64::from(*id));
}
}
}
EntityKind::MLine(m) => {
+1
View File
@@ -51,6 +51,7 @@ const HEADER_VARS: &[(&str, i32)] = &[
("PSTYLEMODE", 290),
("INSUNITS", 70),
("MEASUREMENT", 70),
("REGENMODE", 70),
("PSLTSCALE", 70),
// The model view the drawing is saved at, as DXF keeps it in HEADER (the `*ACTIVE` VPORT
// record below repeats it). Written so a drawing opened on its saved view saves it back.
+13 -2
View File
@@ -287,8 +287,19 @@ impl<'o> Out<'o> {
/// Header variables that change on every save (time stamps, the handle seed, GUIDs): not
/// compared.
pub const VOLATILE_HEADER: &[&str] =
&["HANDSEED", "TDCREATE", "TDUCREATE", "TDUPDATE", "TDUUPDATE", "TDINDWG", "TDUSRTIMER", "VERSIONGUID", "FINGERPRINTGUID"];
/// `CADCRAFT_DIMASO_MODE` is the engine's memory of the mode DIMASO turned off; no file keeps it.
pub const VOLATILE_HEADER: &[&str] = &[
"HANDSEED",
"TDCREATE",
"TDUCREATE",
"TDUPDATE",
"TDUUPDATE",
"TDINDWG",
"TDUSRTIMER",
"VERSIONGUID",
"FINGERPRINTGUID",
"CADCRAFT_DIMASO_MODE",
];
/// Compare `before` (the drawing as first opened) with `after` (the same drawing saved and
/// reopened). Differences are reported as what `after` lost, gained or changed.
+130
View File
@@ -0,0 +1,130 @@
//! A lightweight polyline keeps its vertex identifiers (LWPOLYLINE group 91 after a vertex, DXF
//! 2010 and later) through a save while its vertices are where they were read.
//! Geometric constraints name a polyline's segments by these identifiers. CADCraft's polyline has
//! none, so every save wrote the polyline without them, and what the constraints name was gone.
//!
//! The DWG is written here with acadrust, the identifiers out of order and the first vertex not
//! the smallest, as on a polyline that was edited in another program. The harness builds this
//! module only where acadrust builds (see `main.rs`).
use std::io::Cursor;
use acadrust::entities::{EntityType, LwPolyline, LwVertex};
use acadrust::{CadDocument, DxfVersion, Vector2};
use cadcraft_io::{SaveOptions, Version, read, write_with};
const VERTEX_IDS: [i32; 4] = [2, 5, 7, 1];
fn polyline_dwg() -> Vec<u8> {
polyline_dwg_with([(0.0, 0.0), (40.0, 0.0), (40.0, 25.0), (0.0, 25.0)], 1.0)
}
/// A DWG with one closed polyline at `points`, its normal along `normal_z` Z.
fn polyline_dwg_with(points: [(f64, f64); 4], normal_z: f64) -> Vec<u8> {
let mut doc = CadDocument::with_version(DxfVersion::AC1032);
let mut polyline = LwPolyline::new();
polyline.is_closed = true;
polyline.normal = acadrust::Vector3::new(0.0, 0.0, normal_z);
for (id, (x, y)) in VERTEX_IDS.iter().zip(points) {
polyline.vertices.push(LwVertex { vertex_id: *id, ..LwVertex::new(Vector2::new(x, y)) });
}
doc.add_entity(EntityType::LwPolyline(polyline)).expect("add the polyline");
acadrust::DwgWriter::write_to_vec(&doc).expect("write the DWG")
}
/// The vertex identifiers of the one lightweight polyline in DWG bytes.
fn vertex_ids_of(dwg: &[u8]) -> Vec<i32> {
let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg.to_vec())).read().unwrap();
doc.entities()
.find_map(|e| match e {
EntityType::LwPolyline(p) => Some(p.vertices.iter().map(|v| v.vertex_id).collect()),
_ => None,
})
.expect("the polyline is in the DWG")
}
/// The vertex identifiers (groups 91) of the one LWPOLYLINE record in a DXF text.
fn dxf_vertex_ids(dxf: &[u8]) -> Vec<String> {
let text = String::from_utf8_lossy(dxf);
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let mut pairs = lines.chunks(2).filter_map(|pair| Some((*pair.first()?, *pair.get(1)?)));
let record = pairs.by_ref().skip_while(|pair| *pair != ("0", "LWPOLYLINE")).skip(1);
record.take_while(|(code, _)| *code != "0").filter(|(code, _)| *code == "91").map(|(_, value)| value.to_string()).collect()
}
fn save(d: &cadcraft_doc::Drawing, name: &str, version: Version) -> Vec<u8> {
write_with(d, name, &SaveOptions { version: Some(version), binary: false }).unwrap()
}
#[test]
fn a_polyline_keeps_its_vertex_identifiers_through_a_save() {
cadcraft_io::dwg_worker::allow_in_process();
let dwg = polyline_dwg();
assert_eq!(vertex_ids_of(&dwg), VERTEX_IDS, "the fixture as acadrust reads it");
let d = read(&dwg, "polyline.dwg").unwrap();
for version in [Version::R2010, Version::R2018] {
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", version)), VERTEX_IDS, "DWG {version:?}");
}
assert_eq!(dxf_vertex_ids(&save(&d, "saved.dxf", Version::R2018)), ["2", "5", "7", "1"]);
// A DXF before 2010 has no such group.
assert!(dxf_vertex_ids(&save(&d, "saved.dxf", Version::R2000)).is_empty());
let back = read(&save(&d, "saved.dxf", Version::R2018), "saved.dxf").unwrap();
assert_eq!(dxf_vertex_ids(&save(&back, "again.dxf", Version::R2018)), ["2", "5", "7", "1"], "read back from a DXF");
}
/// Once a vertex is elsewhere, the order is another or a vertex is gone, the identifiers no longer
/// say which vertex is which: none are written.
#[test]
fn an_edited_polyline_drops_its_vertex_identifiers() {
cadcraft_io::dwg_worker::allow_in_process();
let mut d = read(&polyline_dwg(), "polyline.dwg").unwrap();
let handle = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap();
let mut after = |edit: fn(&mut cadcraft_doc::LwPolyline)| {
assert!(d.model.modify(handle, |e: &mut cadcraft_doc::Entity| {
if let cadcraft_doc::EntityKind::LwPolyline(p) = &mut e.kind {
edit(p);
}
}));
vertex_ids_of(&save(&d, "edited.dwg", Version::R2018))
};
assert_eq!(after(|p| p.vertices.reverse()), [0; 4], "reversed");
assert_eq!(after(|p| p.vertices.reverse()), VERTEX_IDS, "reversed back: every vertex is where it was read");
assert_eq!(after(|p| p.vertices[1].p.x += 1.0), [0; 4], "a vertex moved");
}
/// A polyline whose normal points down is read mirrored in x; untouched, it keeps its identifiers.
#[test]
fn a_polyline_facing_down_keeps_its_vertex_identifiers() {
cadcraft_io::dwg_worker::allow_in_process();
let d = read(&polyline_dwg_with([(0.0, 0.0), (40.0, 0.0), (40.0, 25.0), (0.0, 25.0)], -1.0), "down.dwg").unwrap();
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", Version::R2018)), VERTEX_IDS);
}
/// Reversed, a polyline symmetric about x = 0 has its mirror image's points: the identifiers still
/// no longer say which vertex is which.
#[test]
fn a_reversed_symmetric_polyline_drops_its_vertex_identifiers() {
cadcraft_io::dwg_worker::allow_in_process();
let mut d = read(&polyline_dwg_with([(-20.0, 0.0), (-20.0, 25.0), (20.0, 25.0), (20.0, 0.0)], 1.0), "sym.dwg").unwrap();
let handle = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap();
assert!(d.model.modify(handle, |e: &mut cadcraft_doc::Entity| {
if let cadcraft_doc::EntityKind::LwPolyline(p) = &mut e.kind {
p.vertices.reverse();
}
}));
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", Version::R2018)), [0; 4]);
}
/// A group 91 inside an application's `102 {` group of the record is not a vertex identifier.
#[test]
fn a_91_inside_an_application_group_is_not_an_identifier() {
cadcraft_io::dwg_worker::allow_in_process();
let d = read(&polyline_dwg(), "polyline.dwg").unwrap();
let dxf = String::from_utf8(save(&d, "saved.dxf", Version::R2018)).unwrap();
let mut lines: Vec<&str> = dxf.lines().collect();
let start = lines.windows(2).position(|pair| pair[0].trim() == "0" && pair[1].trim() == "LWPOLYLINE").unwrap();
// After the first vertex's identifier.
let at = (start..lines.len()).step_by(2).find(|i| lines[*i].trim() == "91").unwrap() + 2;
lines.splice(at..at, ["102", "{SOMEAPP", " 91", "9", "102", "}"]);
let back = read(lines.join("\n").as_bytes(), "app.dxf").unwrap();
assert_eq!(dxf_vertex_ids(&save(&back, "again.dxf", Version::R2018)), ["2", "5", "7", "1"]);
}
+2
View File
@@ -60,6 +60,8 @@ mod low_handseed;
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod ltype_dwg_dash_count;
mod ltype_element_cap;
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod lwpolyline_vertex_ids;
mod minsert_marker;
mod mleader_content;
mod mleader_roundtrip;
+46 -9
View File
@@ -553,15 +553,29 @@ const MAX_SWATCH_WORK: u64 = 2_000_000;
/// A preview of a pattern for a pattern picker: the runs of its line families `lines` inside the
/// `side` × `side` square with a corner at the origin, at a scale that shows a few repeats of the
/// pattern (each family's line spacing or dash repeat, whichever is longer). Empty for a pattern
/// pattern. For sparse, staggered tile edges the area per mark sets the preview scale. Empty for a pattern
/// with no lines (SOLID).
pub fn pattern_swatch(lines: &[PatternLine], side: f64) -> Vec<Vec<Vec2>> {
let repeat =
lines.iter().map(|l| l.delta.1.abs().max(l.dashes.iter().map(|d| d.abs()).sum::<f64>())).filter(|r| r.is_finite()).fold(0.0, f64::max);
let estimate = |sparse: bool| {
lines
.iter()
.map(|l| {
let spacing = l.delta.1.abs();
let period = l.dashes.iter().map(|d| d.abs()).sum::<f64>();
if sparse && l.delta.0 != 0. && matches!(l.dashes.as_slice(), [ink, gap] if *ink > 0. && -*gap > 32. * spacing) {
(period * spacing).sqrt()
} else {
spacing.max(period)
}
})
.filter(|r| r.is_finite())
.fold(0.0, f64::max)
};
let repeat = estimate(true);
if !side.is_finite() || side <= 0.0 || repeat < 1e-9 {
return Vec::new();
}
let h = Hatch {
let mut h = Hatch {
pattern: String::new(),
solid: false,
loops: Vec::new(),
@@ -578,7 +592,16 @@ pub fn pattern_swatch(lines: &[PatternLine], side: f64) -> Vec<Vec<Vec2>> {
let square = vec![Vec2::new(0.0, 0.0), Vec2::new(side, 0.0), Vec2::new(side, side), Vec2::new(0.0, side)];
// The generator stops at the swatch's own limits, so a compact pattern is never made in full
// (about a million runs) to keep a few thousand.
let mut runs = pattern_lines_within(&Drawing::default(), &h, &[square], 0.0, None, None, MAX_SWATCH_RUNS, MAX_SWATCH_WORK);
let loops = [square];
let render = |h: &Hatch| pattern_lines_within(&Drawing::default(), h, &loops, 0.0, None, None, MAX_SWATCH_RUNS, MAX_SWATCH_WORK);
let mut runs = render(&h);
if runs.is_empty() {
let full = estimate(false);
if full > repeat {
h.scale = side / (SWATCH_REPEATS * full);
runs = render(&h);
}
}
runs.truncate(MAX_SWATCH_RUNS);
runs.shrink_to_fit();
runs
@@ -644,14 +667,18 @@ impl Family<'_> {
let k0 = (lo.y / self.spacing).floor() as i64;
let k1 = (hi.y / self.spacing).ceil() as i64;
let max_lines = if view.is_some() { MAX_VIEW_FAMILY_LINES } else { MAX_FAMILY_LINES };
if k1.saturating_sub(k0) > max_lines {
return;
}
let many_rows = k1.saturating_sub(k0) > max_lines;
let pat_len: f64 = self.dashes.iter().map(|d| d.abs()).sum();
// Level of detail: a whole repeat under two pixels reads as a continuous line (when the
// family draws anything at all).
let draws = self.dashes.iter().any(|d| *d >= 0.0);
let solid_line = self.dashes.is_empty() || pat_len < 1e-12 || (px > 0.0 && pat_len < 2.0 * px && draws);
// Captured tile edges can have many tightly spaced rows, each with a long empty gap.
// Reject empty rows by dash phase before walking or sorting any boundary edges.
let sparse = matches!(self.dashes, [ink, gap] if *ink >= 0. && -*gap > hi.x - lo.x) && !solid_line;
if many_rows && (!sparse || k1.abs_diff(k0) >= *work) {
return;
}
// Each scanline visits every boundary edge and sorts the intersections. Charge both the
// traversal and an n*ceil(log2(n)) upper bound for sorting, scaled to one unit per eight
// operations, whether or not any dash is made.
@@ -662,10 +689,20 @@ impl Family<'_> {
if out.len() >= self.max_runs || crossings_charge > *work || is_set(cancel) {
return;
}
let offset = shift_per_line * k as f64;
if many_rows {
*work -= 1;
let phase = (lo.x - offset).rem_euclid(pat_len);
if phase > self.dashes[0] && pat_len - phase > hi.x - lo.x {
continue;
}
if crossings_charge > *work {
return;
}
}
*work -= crossings_charge;
let y = k as f64 * self.spacing;
let xs = crossings(&local, y);
let offset = shift_per_line * k as f64;
for span in xs.chunks(2) {
let [x0, x1] = span else { continue };
let (x0, x1) = match span_cut {
+4 -4
View File
@@ -84,7 +84,7 @@ enum Tab {
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum View {
pub(crate) enum View {
ExtraLarge,
Large,
#[default]
@@ -95,10 +95,10 @@ enum View {
}
impl View {
const ALL: [View; 6] = [View::ExtraLarge, View::Large, View::Medium, View::Small, View::Details, View::List];
pub(crate) const ALL: [View; 6] = [View::ExtraLarge, View::Large, View::Medium, View::Small, View::Details, View::List];
/// The name shown on the view's button.
fn label(self) -> &'static str {
pub(crate) fn label(self) -> &'static str {
match self {
View::ExtraLarge => crate::tl!("Extra Large Icons"),
View::Large => crate::tl!("Large Icons"),
@@ -110,7 +110,7 @@ impl View {
}
/// The side of a gallery tile, for the icon views.
fn tile(self) -> Option<f32> {
pub(crate) fn tile(self) -> Option<f32> {
match self {
View::ExtraLarge => Some(150.0),
View::Large => Some(104.0),
+16 -2
View File
@@ -552,9 +552,23 @@ pub fn start_page(app: &mut CadApp, ui: &mut egui::Ui) {
y += 44.0;
}
let main = Rect::from_min_max(pos2(left.right() + 36.0, r.top() + 40.0), r.max);
p.text(main.min, egui::Align2::LEFT_TOP, crate::tl!("Recent"), egui::FontId::proportional(22.0), t.text);
let mut local_top = main.top();
if app.file_providers.enabled() {
let mut provider_ui = ui.new_child(egui::UiBuilder::new().max_rect(main).layout(egui::Layout::top_down(egui::Align::Min)));
let resource = egui::ScrollArea::vertical()
.id_salt("provider-recents")
.max_height((r.height() * 0.4).clamp(80.0, 240.0))
.show(&mut provider_ui, |ui| app.file_providers.provider_recent_ui(ui))
.inner;
app.file_providers.device_recent_ui(&mut provider_ui);
local_top += provider_ui.min_rect().height() + 20.0;
if let Some(resource) = resource {
let _ = app.run(crate::menus::PROVIDER_RECENT_OPEN, serde_json::json!({"resource":resource}));
}
}
p.text(pos2(main.left(), local_top), egui::Align2::LEFT_TOP, crate::tl!("Recent"), egui::FontId::proportional(22.0), t.text);
let mut recent = None;
let mut y = main.top() + 44.0;
let mut y = local_top + 44.0;
for (i, path) in app.ui.recent_files.iter().enumerate() {
let row = Rect::from_min_size(pos2(main.left(), y), vec2((r.right() - main.left() - 36.0).clamp(0.0, 640.0), 42.0));
let resp = ui.interact(row, ui.scope_id().with(("recent", i)), Sense::click());
+8
View File
@@ -68,6 +68,10 @@ impl CadApp {
/// about each drawing first and quit once all are dealt with. Returns whether the close has to
/// wait (the caller then cancels the window close).
pub fn request_quit(&mut self) -> bool {
if self.file_providers.busy() {
self.set_status("Finish or cancel the pending file provider operation before quitting");
return true;
}
if self.quit_confirmed || !self.session.docs.iter().any(|d| d.is_dirty()) {
return false;
}
@@ -171,6 +175,10 @@ impl CadApp {
}
fn begin_close(&mut self, uids: Vec<u64>) {
if self.file_providers.busy() {
self.set_status("Finish or cancel the pending file provider operation before closing");
return;
}
if self.closing.is_some() {
// A prompt is already open; it has to be answered first.
return;
+133
View File
@@ -0,0 +1,133 @@
//! DXF capture over the existing format hooks; no storage backend or filesystem authority.
use crate::{CadApp, file_providers::Action};
use cadcraft_engine::cmd::file::{self, SaveAs};
use serde_json::{Value, json};
pub(crate) fn save(app: &mut CadApp, save_as: bool) -> Result<Value, String> {
let result = capture(app, save_as);
if let Err(error) = &result {
app.session.echo(error.clone());
app.set_status(error.clone());
}
result
}
/// Queue a provider read through CadApp::run without creating a filesystem picker.
pub(crate) fn open_recent(app: &mut CadApp, params: &Value) -> Result<Value, String> {
let result = params
.get("resource")
.and_then(Value::as_str)
.ok_or_else(|| "a file provider resource ID is required".to_string())
.and_then(|resource| app.file_providers.request_open(resource))
.map(|request| json!({"pending":"fileProvider","requestId":request}));
if let Err(error) = &result {
app.session.echo(error.clone());
app.set_status(error.clone());
}
result
}
fn capture(app: &mut CadApp, save_as: bool) -> Result<Value, String> {
let host = app.file_providers.clone();
let state = app.session.state().map_err(|e| e.to_string())?;
if host.pending_for(state.uid) {
return Err("a provider save is already pending for this drawing".into());
}
if state.block_unsaved() {
return Err("save or discard Block Editor changes before saving with a provider".into());
}
let drawing = state.drawing();
// This single-file transfer does not upload external image or drawing bytes.
if has_external_files(drawing) {
return Err(
"DXF references external images or drawings; make a self-contained drawing before provider save (external files are not uploaded)".into(),
);
}
let mut name = host.bound_filename(state.uid).unwrap_or_else(|| match state.title.rsplit_once('.') {
Some((_, extension)) if extension.eq_ignore_ascii_case("dxf") => state.title.clone(),
Some((stem, extension)) if extension.eq_ignore_ascii_case("dwg") => format!("{stem}.dxf"),
_ => format!("{}.dxf", state.title),
});
if name.trim() == ".dxf" {
name = "Drawing.dxf".into();
}
let bytes = match file::write_as() {
Some(writer) => writer(drawing, &name, &SaveAs::default())?,
None => (file::io().ok_or("file formats are unavailable")?.write)(drawing, &name)?,
};
let request = host.begin(vec![state.clone()], state.uid, state.revision, name, bytes, save_as)?;
app.set_status("Choose where to save the DXF drawing");
Ok(json!({"pending":"fileProvider","requestId":request}))
}
pub(crate) fn tick(app: &mut CadApp) {
let host = app.file_providers.clone();
if !host.connected() {
return;
}
for action in host.take_actions() {
match action {
Action::Save { request, capture, status, resource } => {
let alive = app.session.docs.iter().any(|d| d.uid == capture.doc);
if status == "saved" {
for snapshot in &capture.snapshots {
if let Some(doc) = app.session.docs.iter_mut().find(|d| d.uid == snapshot.uid) {
doc.saved = snapshot.drawing().clone();
doc.path = None;
}
}
app.set_status("Drawing saved with file provider");
} else if status == "failed" {
app.set_status("File provider save failed; drawing remains unsaved");
}
host.finish_save(&request, &capture, &status, &resource, alive);
}
Action::Open { request, resource, name, bytes } => {
let result = open_resource(app, &resource, &name, &bytes);
if let Err(error) = &result {
app.open_failed(error);
}
host.finish_open(&request, &resource, &name, result);
}
}
}
host.refresh(app.session.docs.iter().map(|d| (d.uid, d.revision, d.title.clone(), d.is_dirty())).collect());
}
/// The same modeled dependency boundary applies before provider Save and Open. In particular,
/// provider bytes must not reach native OPEN's automatic IMAGE/XREF filesystem loaders.
fn has_external_files(drawing: &cadcraft_doc::Drawing) -> bool {
drawing
.model
.iter()
.chain(drawing.layouts.iter().flat_map(|layout| layout.entities.iter()))
.chain(drawing.blocks.values().flat_map(|block| block.entities.iter()))
.any(|entity| matches!(&entity.kind, cadcraft_doc::EntityKind::Image(image) if !image.path.is_empty()))
|| drawing.blocks.values().any(|block| block.xref_path.as_ref().is_some_and(|path| !path.is_empty()))
}
fn open_resource(app: &mut CadApp, resource: &str, name: &str, bytes: &[u8]) -> Result<u64, String> {
if let Some((index, uid)) =
app.file_providers.bound_document(resource).and_then(|uid| app.session.docs.iter().position(|doc| doc.uid == uid).map(|index| (index, uid)))
{
return app.run("document.switch", json!({"index":index})).map(|_| uid);
}
// Host admission already bounds these bytes. Preflight with the installed native decoder,
// before any document is opened or the unchanged native command follows external paths.
// The actual Open still runs through CadApp's existing command route and format hooks.
let hooks = file::io().ok_or("file formats are unavailable")?;
// `catch_unwind` only helps native builds: a panic aborts on wasm, where this bridge runs, so the
// readers must stay panic-free and nothing here may rely on recovering from one.
let drawing = std::panic::catch_unwind(|| (hooks.read)(bytes, name)).map_err(|_| "file provider drawing decoder failed".to_string())??;
if has_external_files(&drawing) {
return Err(
"DXF references external images or drawings; open a self-contained drawing with the file provider (external files are not loaded)".into(),
);
}
drop(drawing);
app.run("open", json!({"data":file::base64_encode(bytes),"name":name})).and_then(|value| {
app.opened(Ok(value));
app.session.state().map(|doc| doc.uid).map_err(|error| error.to_string())
})
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,210 @@
#![allow(clippy::unwrap_used)]
use super::*;
use cadcraft_engine::Session;
fn pending() -> (CadApp, String, u64) {
let app = CadApp::new(Session::new(), crate::Services::default());
app.file_providers.set_session("0123456789abcdef0123456789abcdef".into()).unwrap();
app.file_providers.connect("test".into(), "Test storage".into(), "account".into()).unwrap();
let doc = app.session.state().unwrap().clone();
let uid = doc.uid;
// Lifecycle fixture: a fake capture is isolated from the engine's process-global format hooks.
let request = app.file_providers.begin(vec![doc.clone()], uid, doc.revision, "Drawing.dxf".into(), vec![1], false).unwrap();
(app, request, uid)
}
#[test]
fn rejected_provider_save_is_reported_without_consuming_the_capture() {
let (mut app, _, uid) = pending();
let error = save(&mut app, false).unwrap_err();
assert!(error.contains("already pending"));
assert_eq!(app.status.as_ref().map(|(text, _)| text.as_str()), Some(error.as_str()));
assert_eq!(app.session.log.last(), Some(&error));
assert!(app.file_providers.pending_for(uid));
}
#[test]
fn ack_owns_its_document_and_does_not_clean_newer_edits() {
let (mut app, request, uid) = pending();
app.file_providers.resolve_dialog(&request, "provider", "Drawing.dxf").unwrap();
let doc = app.session.docs.iter_mut().find(|d| d.uid == uid).unwrap();
std::sync::Arc::make_mut(&mut doc.doc).handseed += 1;
app.session.new_drawing(false);
app.file_providers.result(request, "saved".into(), "drawing-1".into()).unwrap();
tick(&mut app);
assert!(app.session.docs.iter().find(|d| d.uid == uid).unwrap().is_dirty());
assert_eq!(app.file_providers.bound_document("drawing-1"), Some(uid));
}
#[test]
fn device_result_is_terminal_without_claiming_durable_storage() {
let (mut app, request, uid) = pending();
let doc = app.session.docs.iter_mut().find(|d| d.uid == uid).unwrap();
std::sync::Arc::make_mut(&mut doc.doc).handseed += 1;
app.file_providers.resolve_dialog(&request, "device", "Drawing.dxf").unwrap();
app.file_providers.result(request, "download".into(), String::new()).unwrap();
tick(&mut app);
assert!(app.session.docs.iter().find(|d| d.uid == uid).unwrap().is_dirty());
assert!(app.file_providers.bound_document("drawing-1").is_none());
}
#[test]
fn real_dxf_delivery_failure_preserves_the_owned_drawing_and_later_edits_through_retry() {
let mut app = CadApp::new(Session::new(), crate::Services::default());
app.run("line", json!({"points":[[0,0],[10,10]]})).unwrap();
let host = app.file_providers.clone();
host.set_session("0123456789abcdef0123456789abcdef".into()).unwrap();
host.connect("test".into(), "Test storage".into(), "account".into()).unwrap();
let snapshot = app.session.state().unwrap().clone();
let uid = snapshot.uid;
let checkpoint = snapshot.saved.clone();
// Use the actual native drawing codec without mutating process-global engine hooks.
let bytes = cadcraft_io::write(&snapshot.doc, "Owned.dxf").unwrap();
assert_eq!(cadcraft_io::read(&bytes, "Owned.dxf").unwrap().model.len(), snapshot.doc.model.len());
let request = host.begin(vec![snapshot.clone()], uid, snapshot.revision, "Owned.dxf".into(), bytes, false).unwrap();
host.take_events();
host.resolve_dialog(&request, "provider", "Owned.dxf").unwrap();
app.run("line", json!({"points":[[20,20],[30,30]]})).unwrap();
let later_revision = app.session.state().unwrap().revision;
app.session.new_drawing(false);
let active = app.session.state().unwrap().uid;
assert!(host.publish_events_with(
|metadata, bytes| {
assert_eq!(metadata["type"], "save");
assert_eq!(metadata["requestId"], request);
assert!(bytes.is_some_and(|bytes| !bytes.is_empty()));
Err("synthetic native delivery exception")
},
|_| {},
));
assert!(host.pending_for(uid));
tick(&mut app);
let owned = app.session.docs.iter().find(|doc| doc.uid == uid).unwrap();
assert_eq!(owned.revision, later_revision);
assert!(owned.is_dirty() && std::sync::Arc::ptr_eq(&owned.saved, &checkpoint));
assert_eq!(app.session.state().unwrap().uid, active);
assert!(app.status.as_ref().unwrap().0.contains("File provider save failed"));
assert!(host.result(request.clone(), "saved".into(), "late".into()).is_err());
let mut failed = 0;
assert!(!host.publish_events_with(
|metadata, _| {
assert_eq!(metadata["type"], "saveFailed");
assert_eq!(metadata["requestId"], request);
assert_eq!(metadata["documentId"], uid.to_string());
failed += 1;
Ok::<(), &str>(())
},
|_| {},
));
assert_eq!(failed, 1);
assert!(!host.busy());
let retry_snapshot = app.session.docs.iter().find(|doc| doc.uid == uid).unwrap().clone();
let bytes = cadcraft_io::write(&retry_snapshot.doc, "Owned.dxf").unwrap();
let retry = host.begin(vec![retry_snapshot.clone()], uid, retry_snapshot.revision, "Owned.dxf".into(), bytes, false).unwrap();
host.take_events();
host.resolve_dialog(&retry, "provider", "Owned.dxf").unwrap();
assert!(!host.publish_events_with(
|metadata, bytes| {
assert_eq!(metadata["requestId"], retry);
assert_eq!(cadcraft_io::read(&bytes.unwrap(), "Owned.dxf").unwrap().model.len(), retry_snapshot.doc.model.len());
Ok::<(), &str>(())
},
|_| {},
));
let index = app.session.docs.iter().position(|doc| doc.uid == uid).unwrap();
app.run("document.switch", json!({"index":index})).unwrap();
app.run("line", json!({"points":[[40,40],[50,50]]})).unwrap();
let current_revision = app.session.state().unwrap().revision;
let back = app.session.docs.iter().position(|doc| doc.uid == active).unwrap();
app.run("document.switch", json!({"index":back})).unwrap();
host.result(retry.clone(), "saved".into(), "file-1".into()).unwrap();
tick(&mut app);
let owned = app.session.docs.iter().find(|doc| doc.uid == uid).unwrap();
assert_eq!(owned.revision, current_revision);
assert!(owned.is_dirty() && std::sync::Arc::ptr_eq(&owned.saved, &retry_snapshot.doc));
assert_eq!(app.session.state().unwrap().uid, active);
assert_eq!(host.bound_document("file-1"), Some(uid));
assert_eq!(host.take_events()[0].metadata["type"], "saved");
assert!(!host.busy());
}
fn recent_provider_app() -> CadApp {
let app = CadApp::new(Session::new(), crate::Services::default());
app.file_providers.set_session("0123456789abcdef0123456789abcdef".into()).unwrap();
let connection = app.file_providers.connect("test".into(), "Test storage".into(), "account".into()).unwrap();
app.file_providers
.set_resources(
&connection,
vec![
crate::file_providers::Resource { id: "owned".into(), name: "Owned.dxf".into(), updated_at: String::new() },
crate::file_providers::Resource { id: "other".into(), name: "Other.dxf".into(), updated_at: String::new() },
],
)
.unwrap();
app.file_providers.take_events();
app
}
#[test]
fn provider_recent_command_queues_only_the_selected_resource_without_retargeting_the_drawing() {
let mut app = recent_provider_app();
let before = app.session.state().unwrap().clone();
let local = app.ui.recent_files.clone();
assert!(crate::menus::is_ui_command(crate::menus::PROVIDER_RECENT_OPEN));
let result = app.run(crate::menus::PROVIDER_RECENT_OPEN, json!({"resource":"owned"})).unwrap();
assert_eq!(result["pending"], "fileProvider");
let events = app.file_providers.take_events();
assert_eq!(events.len(), 1);
assert_eq!(events[0].metadata["type"], "openRequested");
assert_eq!(events[0].metadata["resourceId"], "owned");
assert_eq!(events[0].metadata["requestId"], result["requestId"]);
let after = app.session.state().unwrap();
assert_eq!((after.uid, after.revision), (before.uid, before.revision));
assert!(std::sync::Arc::ptr_eq(&after.doc, &before.doc));
assert_eq!(after.path, before.path);
assert_eq!(app.ui.recent_files, local);
}
#[test]
fn provider_recent_command_backpressure_remains_in_status_and_command_history() {
let mut app = recent_provider_app();
let mut full = false;
for _ in 0..128 {
if app.file_providers.request_open("owned").is_err() {
full = true;
break;
}
app.file_providers.take_events();
}
assert!(full, "the fixture must reach the actual bounded read capacity");
let before = app.session.state().unwrap().clone();
let error = app.run(crate::menus::PROVIDER_RECENT_OPEN, json!({"resource":"owned"})).unwrap_err();
assert!(app.file_providers.take_events().is_empty(), "a refused command cannot publish a partial read");
let ctx = egui::Context::default();
let mut output = ctx.run_pass(egui::RawInput::default(), |ctx| app.logic(ctx));
output.textures_delta.clear();
assert_eq!(app.status.as_ref().map(|(text, _)| text.as_str()), Some(error.as_str()));
assert_eq!(app.session.log.last(), Some(&error));
assert_eq!((app.session.state().unwrap().uid, app.session.state().unwrap().revision), (before.uid, before.revision));
}
#[test]
fn provider_recent_command_rejects_malformed_and_disabled_requests_without_opening_files() {
let mut app = CadApp::new(Session::new(), crate::Services::default());
let before = app.session.state().unwrap().clone();
for params in [Value::Null, json!({}), json!({"resource":42}), json!({"resource":""}), json!({"resource":"owned"})] {
assert!(app.run(crate::menus::PROVIDER_RECENT_OPEN, params).is_err());
assert!(!app.file_providers.enabled());
assert!(app.file_providers.take_events().is_empty());
assert_eq!((app.session.state().unwrap().uid, app.session.state().unwrap().revision), (before.uid, before.revision));
assert!(std::sync::Arc::ptr_eq(&app.session.state().unwrap().doc, &before.doc));
}
let mut connected = recent_provider_app();
let before = connected.session.state().unwrap().clone();
let connection = connected.file_providers.snapshot()["connectionId"].clone();
connected.file_providers.set_enabled(false).unwrap();
connected.file_providers.take_events();
let error = connected.run(crate::menus::PROVIDER_RECENT_OPEN, json!({"resource":"owned"})).unwrap_err();
assert!(connected.file_providers.connected() && !connected.file_providers.enabled());
assert_eq!(connected.file_providers.snapshot()["connectionId"], connection);
assert!(connected.file_providers.take_events().is_empty());
assert!(std::sync::Arc::ptr_eq(&connected.session.state().unwrap().doc, &before.doc));
assert_eq!(connected.session.log.last(), Some(&error));
}
+541
View File
@@ -0,0 +1,541 @@
//! Optional same-origin storage capability. No provider is enabled by default.
//!
//! Requests own immutable native project captures. A host result never selects a live tab,
//! revision, filesystem path or account. This module contains no storage or authentication.
use cadcraft_engine::DocState;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex, MutexGuard};
const MAX_BYTES: usize = 80 * 1024 * 1024;
const MAX_PENDING: usize = 16;
const MAX_EVENTS: usize = 64;
const MAX_RESOURCES: usize = 100;
const EXTENSION: &str = ".dxf";
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Resource {
pub id: String,
pub name: String,
#[serde(default)]
pub updated_at: String,
}
pub struct Event {
pub metadata: Value,
pub bytes: Option<Vec<u8>>,
}
impl Event {
fn terminal(&self) -> bool {
matches!(
self.metadata.get("type").and_then(Value::as_str),
Some("saved" | "downloaded" | "saveCancelled" | "saveFailed" | "opened" | "openFailed" | "openCancelled")
)
}
}
#[derive(Clone, PartialEq, Eq)]
struct Identity {
provider_id: String,
label: String,
namespace: String,
}
/// The exact states encoded at Save, including a main document's branch tabs where applicable.
pub(crate) struct Capture {
pub doc: u64,
pub revision: u64,
pub snapshots: Vec<DocState>,
pub name: String,
intent: String,
destination: String,
bytes: Option<Vec<u8>>,
}
pub(crate) enum Action {
Save { request: String, capture: Capture, status: String, resource: String },
Open { request: String, resource: String, name: String, bytes: Vec<u8> },
}
#[derive(Clone, Copy)]
enum TerminalOwner {
Open,
Save,
}
#[derive(Clone)]
struct Terminal {
request: String,
metadata: Value,
owner: TerminalOwner,
}
#[derive(Default)]
struct State {
provider: Option<Identity>,
enabled: bool,
nonce: String,
serial: u64,
connection: String,
resources: Vec<Resource>,
bindings: HashMap<u64, String>,
names: HashMap<u64, String>,
dialogs: HashMap<String, Capture>,
pending: HashMap<String, Capture>,
// Keep every captured document alias owned until its terminal event can be queued.
finishing_saves: HashMap<String, Vec<u64>>,
opens: HashMap<String, String>,
queued_opens: HashSet<String>,
actions: Vec<Action>,
// Only captures already admitted in dialogs/pending enter this inbox: at most 16, no bytes.
delivery_failures: Vec<Action>,
events: Vec<Event>,
// At most MAX_PENDING saves plus MAX_PENDING reads; never stores transfer bytes.
finished: VecDeque<Terminal>,
publishing_terminals: usize,
documents: Value,
}
impl State {
fn busy(&self) -> bool {
!self.dialogs.is_empty()
|| !self.pending.is_empty()
|| !self.finishing_saves.is_empty()
|| !self.opens.is_empty()
|| !self.actions.is_empty()
|| !self.delivery_failures.is_empty()
|| !self.finished.is_empty()
|| self.events.iter().any(Event::terminal)
|| self.publishing_terminals != 0
}
fn next(&mut self, kind: &str) -> Result<String, String> {
if self.nonce.is_empty() {
return Err("file provider session is not initialized".into());
}
self.serial = self.serial.checked_add(1).ok_or("file provider request counter exhausted")?;
Ok(format!("{}-{kind}-{}", self.nonce, self.serial))
}
fn event(&mut self, mut metadata: Value, bytes: Option<Vec<u8>>) {
if let (Some(provider), Some(fields)) = (&self.provider, metadata.as_object_mut()) {
fields.insert("providerId".into(), provider.provider_id.clone().into());
fields.insert("namespace".into(), provider.namespace.clone().into());
fields.insert("connectionId".into(), self.connection.clone().into());
}
self.events.push(Event { metadata, bytes });
}
fn retained_bytes(&self) -> usize {
let captures = self.dialogs.values().chain(self.pending.values()).map(|p| p.bytes.as_ref().map_or(0, Vec::len));
let events = self.events.iter().map(|e| e.bytes.as_ref().map_or(0, Vec::len));
let actions = self.actions.iter().chain(&self.delivery_failures).map(|a| match a {
Action::Open { bytes, .. } => bytes.len(),
_ => 0,
});
captures.chain(events).chain(actions).fold(0, usize::saturating_add)
}
fn pending_for(&self, doc: u64) -> bool {
self.dialogs.values().chain(self.pending.values()).any(|c| c.snapshots.iter().any(|d| d.uid == doc))
|| self.finishing_saves.values().any(|aliases| aliases.contains(&doc))
|| self.actions.iter().any(|a| matches!(a, Action::Save { capture, .. } if capture.snapshots.iter().any(|d| d.uid == doc)))
}
fn flush_finished(&mut self) {
while self.events.len() < MAX_EVENTS {
let Some(terminal) = self.finished.pop_front() else { break };
self.event(terminal.metadata, None);
match terminal.owner {
TerminalOwner::Open => {
self.opens.remove(&terminal.request);
self.queued_opens.remove(&terminal.request);
}
TerminalOwner::Save => {
self.finishing_saves.remove(&terminal.request);
}
}
}
}
fn take_events(&mut self) -> Vec<Event> {
let events = std::mem::take(&mut self.events);
self.flush_finished();
if events.is_empty() { std::mem::take(&mut self.events) } else { events }
}
fn fail_delivery(&mut self, metadata: &Value) {
let Some(request) = metadata.get("requestId").and_then(Value::as_str) else { return };
match metadata.get("type").and_then(Value::as_str) {
Some(kind @ ("save" | "saveDialog")) => {
let capture = if kind == "save" { self.pending.remove(request) } else { self.dialogs.remove(request) };
if let Some(mut capture) = capture {
capture.bytes = None;
self.finishing_saves.insert(request.into(), capture.snapshots.iter().map(|doc| doc.uid).collect());
self.delivery_failures.push(Action::Save { request: request.into(), capture, status: "failed".into(), resource: String::new() });
}
}
Some("openRequested") if !self.queued_opens.contains(request) => {
if let Some(resource) = self.opens.get(request).cloned() {
// The terminal can wait behind a full event queue. Reject late payloads
// now, while retaining the read's account owner until it can be queued.
self.queued_opens.insert(request.into());
self.finished.push_back(Terminal {
request: request.into(),
metadata: json!({"type":"openFailed","requestId":request,"resourceId":resource,"error":"file-provider event delivery failed"}),
owner: TerminalOwner::Open,
});
self.flush_finished();
}
}
_ => {}
}
}
}
#[derive(Clone, Default)]
pub struct Host(Arc<Mutex<State>>);
struct PublishingBatch {
host: Host,
terminals: usize,
}
impl Drop for PublishingBatch {
fn drop(&mut self) {
let mut state = self.host.state();
state.publishing_terminals = state.publishing_terminals.saturating_sub(self.terminals);
}
}
impl Host {
fn state(&self) -> MutexGuard<'_, State> {
self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub fn set_session(&self, nonce: String) -> Result<(), String> {
let mut s = self.state();
if !s.nonce.is_empty() || s.provider.is_some() || !valid_id(&nonce) || nonce.len() < 16 {
return Err("invalid or already initialized file provider session".into());
}
s.nonce = nonce;
Ok(())
}
pub fn connect(&self, provider_id: String, label: String, namespace: String) -> Result<String, String> {
if !valid_id(&provider_id) || !valid_label(&label) || !valid_id(&namespace) {
return Err("invalid file provider identity".into());
}
let mut s = self.state();
let identity = Identity { provider_id, label, namespace };
if let Some(current) = &s.provider {
return if *current == identity { Ok(s.connection.clone()) } else { Err("unregister before changing provider or account".into()) };
}
s.connection = s.next("connection")?;
s.provider = Some(identity);
s.enabled = true;
Ok(s.connection.clone())
}
pub fn disconnect(&self) -> Result<(), String> {
let mut s = self.state();
if s.busy() {
return Err("finish or cancel pending operations and consume completion events before unregistering".into());
}
s.provider = None;
s.enabled = false;
s.connection.clear();
s.resources.clear();
s.bindings.clear();
s.names.clear();
s.events.clear();
s.documents = Value::Null;
Ok(())
}
pub fn connected(&self) -> bool {
self.state().provider.is_some()
}
pub fn enabled(&self) -> bool {
let s = self.state();
s.provider.is_some() && s.enabled
}
pub fn set_enabled(&self, enabled: bool) -> Result<(), String> {
let mut s = self.state();
if s.provider.is_none() {
return Err("file provider is not connected".into());
}
s.enabled = enabled;
Ok(())
}
pub fn busy(&self) -> bool {
self.state().busy()
}
pub fn pending_for(&self, doc: u64) -> bool {
self.state().pending_for(doc)
}
pub fn bound_document(&self, resource: &str) -> Option<u64> {
self.state().bindings.iter().find(|(_, r)| r.as_str() == resource).map(|(d, _)| *d)
}
pub fn bound_filename(&self, doc: u64) -> Option<String> {
self.state().names.get(&doc).cloned()
}
/// Captures are produced synchronously by the editor before this event is issued.
pub(crate) fn begin(
&self,
snapshots: Vec<DocState>,
doc: u64,
revision: u64,
name: String,
bytes: Vec<u8>,
save_as: bool,
) -> Result<String, String> {
let mut s = self.state();
if s.provider.is_none()
|| !s.enabled
|| !valid_native_name(&name)
|| bytes.is_empty()
|| bytes.len() > MAX_BYTES
|| s.retained_bytes().saturating_add(bytes.len()) > MAX_BYTES
|| s.pending_for(doc)
|| s.dialogs.len() + s.pending.len() + s.finishing_saves.len() >= MAX_PENDING
|| s.events.len() >= MAX_EVENTS
|| !snapshots.iter().any(|snapshot| snapshot.uid == doc)
{
return Err("provider unavailable, a save is pending, or capture exceeds 80 MiB".into());
}
let request = s.next("dialog")?;
let intent = if save_as { "saveAs" } else { "save" }.to_string();
s.event(json!({"type":"saveDialog","requestId":request,"documentId":doc.to_string(),"revision":revision.to_string(),"intent":intent,"filename":name}), None);
s.dialogs.insert(request.clone(), Capture { doc, revision, snapshots, name, intent, destination: String::new(), bytes: Some(bytes) });
Ok(request)
}
pub fn resolve_dialog(&self, request: &str, destination: &str, name: &str) -> Result<(), String> {
if !matches!(destination, "provider" | "device" | "cancel") || (destination != "cancel" && !valid_native_name(name)) {
return Err("choose provider, device or cancel and a native project filename".into());
}
let mut s = self.state();
if s.events.len() >= MAX_EVENTS {
return Err("provider event queue is full".into());
}
let mut capture = s.dialogs.remove(request).ok_or("unknown or completed save dialog")?;
if destination == "cancel" {
capture.bytes = None;
s.finishing_saves.insert(request.into(), capture.snapshots.iter().map(|doc| doc.uid).collect());
s.actions.push(Action::Save { request: request.into(), capture, status: "cancel".into(), resource: String::new() });
return Ok(());
}
capture.name = name.into();
capture.destination = destination.into();
let resource = if capture.intent == "save" { s.bindings.get(&capture.doc).cloned() } else { None };
let bytes = capture.bytes.take();
s.event(json!({"type":"save","requestId":request,"documentId":capture.doc.to_string(),"revision":capture.revision.to_string(),"intent":capture.intent,"filename":name,"resourceId":resource,"destination":destination}), bytes);
s.pending.insert(request.into(), capture);
Ok(())
}
pub fn result(&self, request: String, status: String, resource: String) -> Result<(), String> {
if !matches!(status.as_str(), "saved" | "download" | "failed" | "cancel") || (!resource.is_empty() && !valid_id(&resource)) {
return Err("invalid provider result".into());
}
let mut s = self.state();
let capture = s.pending.get(&request).ok_or("unknown or completed save request")?;
if (status == "saved" && (capture.destination != "provider" || !valid_id(&resource)))
|| (status == "download" && capture.destination != "device")
{
return Err("result does not match the chosen destination".into());
}
if status == "saved" && s.bindings.iter().any(|(doc, id)| *doc != capture.doc && *id == resource) {
return Err("resource is bound to another open document".into());
}
if status == "saved" && capture.intent == "saveAs" && s.bindings.get(&capture.doc) == Some(&resource) {
return Err("Save As must produce a distinct resource".into());
}
if s.actions.len() >= MAX_PENDING {
return Err("provider command queue is full".into());
}
let capture = s.pending.remove(&request).ok_or("unknown save request")?;
s.finishing_saves.insert(request.clone(), capture.snapshots.iter().map(|doc| doc.uid).collect());
s.actions.push(Action::Save { request, capture, status, resource });
Ok(())
}
pub fn set_resources(&self, connection: &str, resources: Vec<Resource>) -> Result<(), String> {
let mut seen = HashSet::new();
if resources.len() > MAX_RESOURCES
|| resources.iter().any(|r| !valid_id(&r.id) || !valid_native_name(&r.name) || r.updated_at.len() > 100 || !seen.insert(r.id.clone()))
{
return Err("invalid native project resource list".into());
}
let mut s = self.state();
if s.provider.is_none() || s.connection != connection {
return Err("resource list belongs to another connection".into());
}
s.resources = resources;
Ok(())
}
pub fn request_open(&self, resource: &str) -> Result<String, String> {
let mut s = self.state();
if !s.enabled
|| s.provider.is_none()
|| s.opens.len() >= MAX_PENDING
|| s.events.len() >= MAX_EVENTS
|| !s.resources.iter().any(|r| r.id == resource)
{
return Err("resource is unavailable in the current provider account".into());
}
let request = s.next("open")?;
s.opens.insert(request.clone(), resource.into());
s.event(json!({"type":"openRequested","requestId":request,"resourceId":resource}), None);
Ok(request)
}
pub fn open(&self, request: String, name: String, bytes: Vec<u8>) -> Result<(), String> {
if !valid_native_name(&name) || bytes.is_empty() || bytes.len() > MAX_BYTES {
return Err("invalid native project resource".into());
}
let mut s = self.state();
if s.actions.len() >= MAX_PENDING || s.retained_bytes().saturating_add(bytes.len()) > MAX_BYTES {
return Err("provider command queue is full".into());
}
if s.queued_opens.contains(&request) {
return Err("open response already queued".into());
}
let resource = s.opens.get(&request).cloned().ok_or("unknown or completed open request")?;
s.queued_opens.insert(request.clone());
s.actions.push(Action::Open { request, resource, name, bytes });
Ok(())
}
pub fn cancel_open(&self, request: String, error: String) -> Result<(), String> {
if error.len() > 1024 {
return Err("invalid open result".into());
}
let mut s = self.state();
if s.queued_opens.contains(&request) {
return Err("open response already queued".into());
}
if s.events.len() >= MAX_EVENTS {
return Err("provider event queue is full".into());
}
let resource = s.opens.remove(&request).ok_or("unknown or completed open request")?;
s.event(json!({"type":if error.is_empty(){"openCancelled"}else{"openFailed"},"requestId":request,"resourceId":resource,"error":error}), None);
Ok(())
}
pub(crate) fn take_actions(&self) -> Vec<Action> {
let mut state = self.state();
let mut actions = std::mem::take(&mut state.actions);
actions.append(&mut state.delivery_failures);
actions
}
pub fn take_events(&self) -> Vec<Event> {
self.state().take_events()
}
/// Failed publication consumes only a still-owned request, never an accepted callback.
/// Recovery actions retain captured aliases until the real application produces a terminal.
/// Returns whether the platform must request a repaint for failure consumption.
pub fn publish_events_with<E>(&self, mut dispatch: impl FnMut(&Value, Option<Vec<u8>>) -> Result<(), E>, mut on_error: impl FnMut(E)) -> bool {
let mut failed = false;
for _ in 0..2 {
let (events, _publishing) = {
let mut state = self.state();
let events = state.take_events();
let terminals = events.iter().filter(|event| event.terminal()).count();
state.publishing_terminals = state.publishing_terminals.saturating_add(terminals);
(events, PublishingBatch { host: self.clone(), terminals })
};
if events.is_empty() {
break;
}
for event in events {
if let Err(error) = dispatch(&event.metadata, event.bytes) {
failed = true;
self.state().fail_delivery(&event.metadata);
on_error(error);
}
}
}
failed
}
pub fn snapshot(&self) -> Value {
let s = self.state();
json!({"protocolVersion":1,"enabled":s.enabled && s.provider.is_some(),"provider":s.provider.as_ref().map(|p|json!({"id":p.provider_id,"label":p.label,"namespace":p.namespace})),"connectionId":s.connection,"resources":s.resources,"documents":s.documents,"pending":s.busy()})
}
pub(crate) fn refresh(&self, docs: Vec<(u64, u64, String, bool)>) {
let mut s = self.state();
let live: HashSet<_> = docs.iter().map(|d| d.0).collect();
s.bindings.retain(|id, _| live.contains(id));
s.names.retain(|id, _| live.contains(id));
s.documents = json!(docs.into_iter().map(|(id,rev,name,dirty)|json!({"id":id.to_string(),"revision":rev.to_string(),"name":name,"dirty":dirty,"resourceId":s.bindings.get(&id)})).collect::<Vec<_>>());
}
pub(crate) fn finish_save(&self, request: &str, capture: &Capture, status: &str, resource: &str, alive: bool) {
let mut s = self.state();
if !s.finishing_saves.get(request).is_some_and(|aliases| aliases.contains(&capture.doc))
|| s.finished.iter().any(|terminal| terminal.request == request)
{
return;
}
if status == "saved" {
if alive {
s.bindings.insert(capture.doc, resource.into());
s.names.insert(capture.doc, capture.name.clone());
}
s.resources.retain(|r| r.id != resource);
s.resources.insert(0, Resource { id: resource.into(), name: capture.name.clone(), updated_at: String::new() });
s.resources.truncate(MAX_RESOURCES);
}
let metadata = json!({"type":match status { "saved"=>"saved", "download"=>"downloaded", "cancel"=>"saveCancelled", _=>"saveFailed" },"requestId":request,"documentId":capture.doc.to_string(),"revision":capture.revision.to_string(),"resourceId":resource,"filename":capture.name,"documentOpen":alive});
s.finished.push_back(Terminal { request: request.into(), metadata, owner: TerminalOwner::Save });
s.flush_finished();
}
pub(crate) fn finish_open(&self, request: &str, resource: &str, name: &str, result: Result<u64, String>) {
let mut s = self.state();
if !s.opens.get(request).is_some_and(|owned| owned == resource)
|| !s.queued_opens.contains(request)
|| s.finished.iter().any(|terminal| terminal.request == request)
{
return;
}
let metadata = match result {
Ok(doc) => {
s.bindings.insert(doc, resource.into());
s.names.insert(doc, name.into());
json!({"type":"opened","requestId":request,"resourceId":resource,"documentId":doc.to_string()})
}
Err(error) => json!({"type":"openFailed","requestId":request,"resourceId":resource,"error":bounded_error(&error)}),
};
s.finished.push_back(Terminal { request: request.into(), metadata, owner: TerminalOwner::Open });
s.flush_finished();
}
/// Draw the recent lists and return a selected resource; the caller dispatches its command.
pub fn recent_ui(&self, ui: &mut egui::Ui) -> Option<String> {
let selected = self.provider_recent_ui(ui);
self.device_recent_ui(ui);
selected
}
pub(crate) fn provider_recent_ui(&self, ui: &mut egui::Ui) -> Option<String> {
let (label, resources, enabled) = {
let s = self.state();
(s.provider.as_ref().map(|p| p.label.clone()), s.resources.clone(), s.enabled)
};
let label = label.filter(|_| enabled)?;
ui.add_space(12.0);
ui.strong(format!("Recent files — {label}"));
if resources.is_empty() {
ui.weak("No recent files from this provider");
}
let mut selected = None;
for resource in resources {
if ui.button(&resource.name).on_hover_text(&resource.updated_at).clicked() {
selected = Some(resource.id);
ui.ctx().request_repaint();
}
}
selected
}
pub(crate) fn device_recent_ui(&self, ui: &mut egui::Ui) {
if self.enabled() {
ui.separator();
ui.weak("Recent files on this device");
}
}
}
fn bounded_error(message: &str) -> String {
let mut error = String::new();
for ch in message.chars().filter(|ch| !ch.is_control()) {
if error.len().saturating_add(ch.len_utf8()) > 1024 {
break;
}
error.push(ch);
}
error
}
fn valid_id(value: &str) -> bool {
!value.is_empty() && value.len() <= 160 && value.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b':'))
}
fn valid_label(value: &str) -> bool {
!value.trim().is_empty() && value.len() <= 100 && !value.chars().any(char::is_control)
}
fn valid_native_name(value: &str) -> bool {
!value.trim().is_empty()
&& value.len() <= 255
&& !value.chars().any(|c| c.is_control() || matches!(c, '/' | '\\'))
&& value.to_ascii_lowercase().ends_with(EXTENSION)
}
#[cfg(test)]
mod tests;
+518
View File
@@ -0,0 +1,518 @@
#![allow(clippy::unwrap_used)]
use super::*;
use cadcraft_engine::Session;
fn host() -> Host {
let h = Host::default();
h.set_session("0123456789abcdef0123456789abcdef".into()).unwrap();
h.connect("test".into(), "Test storage".into(), "account-a".into()).unwrap();
h
}
fn capture(h: &Host, save_as: bool) -> (String, u64) {
let mut session = Session::new();
session.execute("new", &json!({})).unwrap();
let doc = session.state().unwrap().clone();
let uid = doc.uid;
(h.begin(vec![doc.clone()], uid, doc.revision, "example.dxf".into(), vec![1, 2, 3], save_as).unwrap(), uid)
}
#[test]
fn off_until_explicit_registration_and_session_is_single_use() {
let h = Host::default();
assert!(!h.enabled());
assert!(!h.connected());
assert!(h.connect("test".into(), "Test".into(), "a".into()).is_err());
assert!(host().set_session("0123456789abcdef".into()).is_err());
}
#[test]
fn each_save_has_a_choice_and_cancel_never_acknowledges_a_document() {
let h = host();
let (request, uid) = capture(&h, false);
assert_eq!(h.take_events()[0].metadata["type"], "saveDialog");
assert!(h.pending_for(uid));
h.resolve_dialog(&request, "cancel", "").unwrap();
let actions = h.take_actions();
assert!(matches!(&actions[..],[Action::Save { status, .. }] if status == "cancel"));
assert!(h.state().bindings.is_empty());
assert!(h.result(request, "saved".into(), "file".into()).is_err());
}
#[test]
fn durable_ack_owns_its_capture_and_is_single_use() {
let h = host();
let (request, uid) = capture(&h, false);
h.take_events();
assert!(h.disconnect().is_err());
h.resolve_dialog(&request, "provider", "durable.dxf").unwrap();
let event = h.take_events().remove(0);
assert_eq!(event.metadata["type"], "save");
assert_eq!(event.bytes, Some(vec![1, 2, 3]));
h.result(request.clone(), "saved".into(), "file-1".into()).unwrap();
assert!(h.result(request, "saved".into(), "file-1".into()).is_err());
assert!(matches!(h.take_actions().as_slice(),[Action::Save { capture,resource,.. }] if capture.doc==uid && resource=="file-1"));
}
#[test]
fn replies_cannot_cross_the_chosen_destination_or_an_open_resource_alias() {
let h = host();
let (request, uid) = capture(&h, false);
h.resolve_dialog(&request, "device", "local.dxf").unwrap();
assert!(h.result(request.clone(), "saved".into(), "remote".into()).is_err());
h.result(request, "download".into(), String::new()).unwrap();
h.take_actions();
h.take_events();
let (request, _) = capture(&h, false);
h.state().bindings.insert(uid, "already-open".into());
h.resolve_dialog(&request, "provider", "new.dxf").unwrap();
assert!(h.result(request, "saved".into(), "already-open".into()).is_err());
}
#[test]
fn unregister_clears_cached_account_documents_before_reconnect() {
let h = host();
h.state().bindings.insert(42, "account-a-resource".into());
h.state().names.insert(42, "Account A.dxf".into());
h.refresh(vec![(42, 1, "Account A.dxf".into(), false)]);
assert_eq!(h.snapshot()["documents"][0]["resourceId"], "account-a-resource");
h.disconnect().unwrap();
let disconnected = h.snapshot();
assert!(disconnected["documents"].is_null());
assert!(disconnected["resources"].as_array().unwrap().is_empty());
assert!(h.state().bindings.is_empty());
assert!(h.state().names.is_empty());
h.connect("test".into(), "Test storage".into(), "account-b".into()).unwrap();
assert!(h.snapshot()["documents"].is_null());
}
#[test]
fn resource_reads_and_lists_are_scoped_to_current_account_connection() {
let h = host();
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
let rows = vec![Resource { id: "file-1".into(), name: "remote.dxf".into(), updated_at: String::new() }];
assert!(h.set_resources("another-connection", rows.clone()).is_err());
h.set_resources(&connection, rows).unwrap();
assert!(h.request_open("unknown").is_err());
let request = h.request_open("file-1").unwrap();
assert!(h.open("forged".into(), "remote.dxf".into(), vec![1]).is_err());
h.open(request.clone(), "remote.dxf".into(), vec![1]).unwrap();
assert!(h.open(request.clone(), "remote.dxf".into(), vec![1]).is_err());
assert!(h.cancel_open(request.clone(), String::new()).is_err());
assert!(h.disconnect().is_err());
h.take_actions();
h.finish_open(&request, "file-1", "remote.dxf", Err("invalid archive".into()));
assert!(h.disconnect().is_err());
let completion = h.take_events();
assert!(completion.iter().any(|event| event.metadata["type"] == "openFailed" && event.metadata["requestId"] == request));
h.disconnect().unwrap();
let next = h.connect("test".into(), "Test storage".into(), "account-b".into()).unwrap();
assert_ne!(connection, next);
assert!(h.set_resources(&connection, Vec::new()).is_err());
assert!(h.snapshot()["resources"].as_array().unwrap().is_empty());
}
#[test]
fn names_are_native_filenames_and_resource_ids_are_opaque() {
assert!(valid_native_name("with accents áé.dxf"));
assert!(!valid_native_name("../project.dxf"));
assert!(!valid_native_name("project.svg"));
assert!(!valid_id("../../project"));
assert!(!valid_native_name("project.dxf\0"));
}
#[test]
fn disabled_provider_does_not_discard_a_capture_already_awaiting_ack() {
let h = host();
let (request, uid) = capture(&h, false);
h.set_enabled(false).unwrap();
assert!(!h.enabled());
assert!(h.pending_for(uid));
h.resolve_dialog(&request, "provider", "in-flight.dxf").unwrap();
h.result(request, "saved".into(), "file-1".into()).unwrap();
assert!(matches!(h.take_actions().as_slice(),[Action::Save { status,.. }] if status=="saved"));
}
fn fill_transport_event_queue(h: &Host) {
let mut state = h.state();
for ordinal in state.events.len()..MAX_EVENTS {
state.event(json!({"type":"queued","ordinal":ordinal}), None);
}
}
fn terminal_resource(h: &Host) -> String {
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
let filename = format!("Remote{EXTENSION}");
h.set_resources(&connection, vec![Resource { id: "file-1".into(), name: filename.clone(), updated_at: String::new() }]).unwrap();
filename
}
#[test]
fn full_event_queue_retains_open_terminals_until_ordered_drain() {
let h = host();
let filename = terminal_resource(&h);
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
let success = h.request_open("file-1").unwrap();
h.open(success.clone(), filename.clone(), vec![1]).unwrap();
let failure = h.request_open("file-1").unwrap();
h.open(failure.clone(), filename.clone(), vec![1]).unwrap();
h.take_actions();
fill_transport_event_queue(&h);
h.finish_open(&success, "file-1", &filename, Ok(42));
h.finish_open(&failure, "file-1", &filename, Err("é\n".repeat(1000)));
h.finish_open(&success, "file-1", &filename, Err("duplicate".into()));
h.finish_open("unowned", "file-1", &filename, Ok(99));
assert_eq!(h.state().events.len(), MAX_EVENTS);
assert_eq!(h.state().finished.len(), 2);
assert!(h.disconnect().is_err());
let first = h.take_events();
assert_eq!(first.len(), MAX_EVENTS);
assert!(!first.iter().any(|event| matches!(event.metadata["type"].as_str(), Some("opened" | "openFailed"))));
let terminals = h.take_events();
assert_eq!(terminals.len(), 2);
assert_eq!(terminals[0].metadata["type"], "opened");
assert_eq!(terminals[1].metadata["type"], "openFailed");
assert_eq!(terminals.iter().map(|event| event.metadata["requestId"].as_str().unwrap()).collect::<Vec<_>>(), [success.as_str(), failure.as_str()]);
for event in &terminals {
assert_eq!(event.metadata["connectionId"], connection);
assert_eq!(event.metadata["namespace"], "account-a");
}
let error = terminals[1].metadata["error"].as_str().unwrap();
assert!(error.len() <= 1024 && error.chars().all(|ch| !ch.is_control()));
assert_eq!(h.bound_document("file-1"), Some(42));
assert!(!h.busy());
assert!(h.take_events().is_empty());
}
#[test]
fn full_event_queue_retains_save_failure_without_duplicate_or_unowned_terminals() {
let h = host();
let (request, uid) = capture(&h, false);
h.resolve_dialog(&request, "provider", &format!("Failed{EXTENSION}")).unwrap();
h.result(request.clone(), "failed".into(), String::new()).unwrap();
let Action::Save { capture, .. } = h.take_actions().remove(0) else { panic!("expected save action") };
fill_transport_event_queue(&h);
h.finish_save(&request, &capture, "failed", "", true);
h.finish_save(&request, &capture, "failed", "", true);
h.finish_save("unowned", &capture, "failed", "", true);
assert_eq!(h.state().events.len(), MAX_EVENTS);
assert_eq!(h.state().finished.len(), 1);
assert!(h.pending_for(uid));
assert_eq!(h.take_events().len(), MAX_EVENTS);
let terminals = h.take_events();
assert_eq!(terminals.len(), 1);
assert_eq!(terminals[0].metadata["type"], "saveFailed");
assert_eq!(terminals[0].metadata["requestId"], request);
assert!(!h.pending_for(uid));
assert!(!h.busy());
assert!(h.take_events().is_empty());
}
#[test]
fn retained_terminals_are_bounded_by_admitted_reads_and_saves() {
let h = host();
let filename = terminal_resource(&h);
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
for _ in 0..MAX_PENDING {
let (request, _) = capture(&h, false);
h.resolve_dialog(&request, "provider", &format!("Failed{EXTENSION}")).unwrap();
h.result(request, "failed".into(), String::new()).unwrap();
}
let saves: Vec<_> = h
.take_actions()
.into_iter()
.map(|action| match action {
Action::Save { request, capture, .. } => (request, capture),
_ => panic!("expected save action"),
})
.collect();
assert!(h.state().events.len() < MAX_EVENTS);
let mut extra = saves[0].1.snapshots.clone();
extra[0].uid = u64::MAX;
assert!(h.begin(extra, u64::MAX, 1, format!("Extra{EXTENSION}"), vec![1], false).is_err());
let mut reads = Vec::new();
for _ in 0..MAX_PENDING {
let request = h.request_open("file-1").unwrap();
h.open(request.clone(), filename.clone(), vec![1]).unwrap();
reads.push(request);
}
h.take_actions();
fill_transport_event_queue(&h);
for (request, capture) in &saves {
h.finish_save(request, capture, "failed", "", true);
}
for request in &reads {
h.finish_open(request, "file-1", &filename, Err("read failed".into()));
}
assert_eq!(h.state().finished.len(), 2 * MAX_PENDING);
assert_eq!(h.state().finishing_saves.len(), MAX_PENDING);
assert_eq!(h.state().opens.len(), MAX_PENDING);
assert!(h.request_open("file-1").is_err());
assert!(h.disconnect().is_err());
assert_eq!(h.take_events().len(), MAX_EVENTS);
let terminals = h.take_events();
assert_eq!(terminals.len(), 2 * MAX_PENDING);
let expected: Vec<_> = saves.iter().map(|(request, _)| request.as_str()).chain(reads.iter().map(String::as_str)).collect();
assert_eq!(terminals.iter().map(|event| event.metadata["requestId"].as_str().unwrap()).collect::<Vec<_>>(), expected);
for event in &terminals {
assert_eq!(event.metadata["connectionId"], connection);
assert_eq!(event.metadata["namespace"], "account-a");
}
assert!(!h.busy());
assert!(h.take_events().is_empty());
}
#[test]
fn capture_target_must_belong_to_its_snapshot_aliases() {
let h = host();
let (request, _) = capture(&h, false);
let snapshots = h.state().dialogs.get(&request).unwrap().snapshots.clone();
assert!(h.begin(snapshots, u64::MAX, 1, format!("Other{EXTENSION}"), vec![1], false).is_err());
assert!(!h.pending_for(u64::MAX));
}
#[test]
fn failed_save_delivery_has_a_bounded_inbox_and_keeps_all_captured_aliases() {
let h = host();
let mut session = Session::new();
session.execute("new", &json!({})).unwrap();
let first = session.state().unwrap().clone();
session.execute("new", &json!({})).unwrap();
let alias = session.state().unwrap().clone();
let request = h.begin(vec![first.clone(), alias.clone()], first.uid, first.revision, "Captured.dxf".into(), vec![1, 2, 3], false).unwrap();
h.take_events();
h.resolve_dialog(&request, "provider", "Captured.dxf").unwrap();
let name = terminal_resource(&h);
for _ in 0..MAX_PENDING {
let read = h.request_open("file-1").unwrap();
h.open(read, name.clone(), vec![1]).unwrap();
}
assert!(h.result(request.clone(), "saved".into(), "file-1".into()).unwrap_err().contains("queue is full"));
let mut errors = 0;
assert!(h.publish_events_with(
|metadata, bytes| {
if metadata["type"] == "save" {
assert_eq!(metadata["requestId"], request);
assert_eq!(bytes, Some(vec![1, 2, 3]));
Err("copy failed")
} else {
Ok(())
}
},
|_| errors += 1,
));
assert_eq!(errors, 1);
assert_eq!(h.state().actions.len(), MAX_PENDING, "ordinary admission capacity is unchanged");
assert_eq!(h.state().delivery_failures.len(), 1);
assert!(h.pending_for(first.uid) && h.pending_for(alias.uid));
assert!(h.result(request.clone(), "saved".into(), "late".into()).is_err());
let actions = h.take_actions();
assert_eq!(actions.len(), MAX_PENDING + 1);
for action in actions {
match action {
Action::Save { request: owned, capture, status, resource } => {
assert_eq!(owned, request);
assert_eq!((capture.doc, capture.revision), (first.uid, first.revision));
assert_eq!(capture.snapshots.iter().map(|doc| doc.uid).collect::<Vec<_>>(), vec![first.uid, alias.uid]);
assert!(Arc::ptr_eq(&capture.snapshots[0].doc, &first.doc));
assert!(capture.bytes.is_none() && resource.is_empty());
assert_eq!(status, "failed");
h.finish_save(&owned, &capture, &status, &resource, true);
}
Action::Open { request, resource, name, .. } => h.finish_open(&request, &resource, &name, Err("fixture complete".into())),
}
}
assert!(!h.publish_events_with(|_, _| Ok::<(), &str>(()), |_| {}));
assert!(!h.busy() && !h.pending_for(first.uid) && !h.pending_for(alias.uid));
assert!(h.bound_document("file-1").is_none());
h.disconnect().unwrap();
}
#[test]
fn successful_and_reentrant_save_results_are_not_replaced_by_delivery_recovery() {
for reentrant in [false, true] {
let h = host();
let (request, uid) = capture(&h, false);
h.take_events();
h.resolve_dialog(&request, "provider", "Original.dxf").unwrap();
let failed = h.publish_events_with(
|metadata, _| {
assert_eq!(metadata["type"], "save");
if reentrant {
h.result(request.clone(), "saved".into(), "file-1".into()).unwrap();
Err("dispatch failed after an accepted result")
} else {
Ok(())
}
},
|_| {},
);
assert_eq!(failed, reentrant);
assert!(h.state().delivery_failures.is_empty());
if !reentrant {
assert!(h.pending_for(uid), "successful delivery is not an ACK");
h.result(request.clone(), "saved".into(), "file-1".into()).unwrap();
}
let Action::Save { request: owned, capture, status, resource } = h.take_actions().remove(0) else { panic!("expected save action") };
assert_eq!((owned.as_str(), status.as_str(), resource.as_str()), (request.as_str(), "saved", "file-1"));
h.finish_save(&owned, &capture, &status, &resource, true);
assert!(h.disconnect().is_err(), "the queued saved terminal still owns its account");
assert_eq!(h.take_events()[0].metadata["type"], "saved");
assert_eq!(h.bound_document("file-1"), Some(uid));
assert!(!h.busy());
}
}
#[test]
fn failed_chooser_delivery_preserves_capacity_errors_and_synchronous_resolution() {
for accepted in [false, true] {
let h = host();
let (request, uid) = capture(&h, false);
if !accepted {
fill_transport_event_queue(&h);
assert!(h.resolve_dialog(&request, "provider", "Retry.dxf").is_err());
assert!(h.state().dialogs.contains_key(&request));
}
assert!(h.publish_events_with(
|metadata, _| {
if metadata["type"] == "saveDialog" {
if accepted {
h.resolve_dialog(&request, "provider", "Accepted.dxf").unwrap();
}
Err("chooser delivery failed")
} else {
Ok(())
}
},
|_| {},
));
if accepted {
assert!(h.state().pending.contains_key(&request));
assert!(h.state().delivery_failures.is_empty());
h.result(request.clone(), "failed".into(), String::new()).unwrap();
} else {
assert!(h.resolve_dialog(&request, "provider", "Late.dxf").is_err());
assert_eq!(h.state().delivery_failures.len(), 1);
}
let Action::Save { request: owned, capture, status, resource } = h.take_actions().remove(0) else { panic!("expected failure action") };
assert_eq!(owned, request);
assert_eq!(status, "failed");
assert!(capture.bytes.is_none());
h.finish_save(&owned, &capture, &status, &resource, true);
let terminal = h.take_events();
assert_eq!(terminal[0].metadata["type"], "saveFailed");
assert_eq!(terminal[0].metadata["requestId"], request);
assert!(!h.busy() && !h.pending_for(uid));
let retry = h.begin(capture.snapshots.clone(), capture.doc, capture.revision, "Retry.dxf".into(), vec![1], false).unwrap();
assert_ne!(retry, request);
}
}
#[test]
fn failed_read_delivery_releases_only_unconsumed_owners_and_preserves_queued_open() {
let h = host();
let name = terminal_resource(&h);
let failed = h.request_open("file-1").unwrap();
let accepted = h.request_open("file-1").unwrap();
let mut terminals = Vec::new();
assert!(h.publish_events_with(
|metadata, _| {
if metadata["type"] == "openRequested" {
if metadata["requestId"] == accepted {
h.open(accepted.clone(), name.clone(), vec![7]).unwrap();
}
Err("open request delivery failed")
} else {
terminals.push(metadata.clone());
Ok(())
}
},
|_| {},
));
assert_eq!(terminals.len(), 1);
assert_eq!(terminals[0]["type"], "openFailed");
assert_eq!(terminals[0]["requestId"], failed);
assert_eq!(terminals[0]["resourceId"], "file-1");
assert!(h.open(failed, name.clone(), vec![1]).is_err());
let actions = h.take_actions();
assert_eq!(actions.len(), 1);
let Action::Open { request, resource, name, bytes } = &actions[0] else { panic!("expected accepted open") };
assert_eq!(request, &accepted);
assert_eq!(bytes.as_slice(), [7]);
h.finish_open(request, resource, name, Err("fixture complete".into()));
assert!(!h.publish_events_with(|_, _| Ok::<(), &str>(()), |_| {}));
assert!(!h.busy());
let retry = h.request_open("file-1").unwrap();
h.cancel_open(retry, String::new()).unwrap();
assert!(!h.publish_events_with(|_, _| Ok::<(), &str>(()), |_| {}));
h.disconnect().unwrap();
}
#[test]
fn current_batch_and_nested_terminal_delivery_keep_the_original_account_owned() {
let h = host();
let name = terminal_resource(&h);
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
let request = h.request_open("file-1").unwrap();
h.open(request.clone(), name.clone(), vec![7]).unwrap();
h.take_actions();
h.finish_open(&request, "file-1", &name, Ok(42));
let mut delivered = Vec::new();
assert!(!h.publish_events_with(
|metadata, _| {
assert!(h.disconnect().is_err());
assert_eq!(h.snapshot()["connectionId"], connection);
if metadata["type"] == "openRequested" {
let nested = h.request_open("file-1").unwrap();
h.cancel_open(nested, String::new()).unwrap();
assert!(!h.publish_events_with(
|_, _| {
assert!(h.disconnect().is_err(), "nested delivery cannot release an outer taken terminal");
Ok::<(), &str>(())
},
|_| {},
));
assert!(h.disconnect().is_err());
} else {
delivered.push(metadata.clone());
}
Ok::<(), &str>(())
},
|_| {},
));
assert_eq!(delivered.len(), 1);
assert_eq!(delivered[0]["type"], "opened");
assert_eq!(delivered[0]["requestId"], request);
assert_eq!(delivered[0]["connectionId"], connection);
assert_eq!(h.bound_document("file-1"), Some(42));
assert!(!h.busy());
h.disconnect().unwrap();
}
#[test]
fn read_delivery_recovery_retains_its_terminal_through_a_reentrant_full_event_queue() {
let h = host();
terminal_resource(&h);
let request = h.request_open("file-1").unwrap();
assert!(h.publish_events_with(
|metadata, _| {
if metadata["type"] == "openRequested" {
fill_transport_event_queue(&h);
Err("delivery failed after another callback filled the queue")
} else {
assert_eq!(metadata["type"], "queued");
assert!(h.disconnect().is_err());
Ok(())
}
},
|_| {
assert!(h.open(request.clone(), "Remote.dxf".into(), vec![1]).is_err(), "a retained failure cannot accept a late payload");
assert!(h.cancel_open(request.clone(), String::new()).is_err());
},
));
assert!(h.busy() && h.disconnect().is_err(), "bounded drains leave the undelivered terminal owned for the next call");
let mut seen = 0;
assert!(!h.publish_events_with(
|metadata, _| {
assert_eq!(metadata["type"], "openFailed");
assert_eq!(metadata["requestId"], request);
assert!(h.disconnect().is_err());
seen += 1;
Ok::<(), &str>(())
},
|_| {},
));
assert_eq!(seen, 1);
assert!(!h.busy());
h.disconnect().unwrap();
}
+220 -12
View File
@@ -46,7 +46,10 @@ pub struct Fill {
/// The dialog while open (and while a pick it started runs).
#[derive(Clone, Debug, PartialEq)]
pub struct HatchDlgState {
choices: Vec<cadcraft_engine::PatternChoice>,
pub fill: Fill,
custom: Option<CustomPattern>,
saved_source: Option<String>,
/// The fill as the dialog opened: edit mode sends only what changed.
pub opened: Fill,
/// The hatches being edited; empty in create mode.
@@ -61,6 +64,8 @@ pub struct HatchDlgState {
pub remove_loops: Vec<usize>,
/// A HATCHPICK the dialog started that hasn't ended yet.
pub picking: Option<PickMode>,
/// The next point pick defines a repeating tile for the custom pattern.
capture_tile: bool,
/// The last command error, shown in the dialog.
pub error: Option<String>,
/// The drawing the dialog belongs to (`DocState::uid`).
@@ -70,9 +75,79 @@ pub struct HatchDlgState {
pub space: Space,
}
#[derive(Clone, Debug, PartialEq)]
struct CustomPattern {
name: String,
families: Vec<PatternFamily>,
}
#[derive(Clone, Debug, PartialEq)]
struct PatternFamily {
origin: (f64, f64),
shift: f64,
angle: f64,
spacing: f64,
dashes: String,
}
impl Default for PatternFamily {
fn default() -> Self {
Self { origin: (0., 0.), shift: 0., angle: 45.0, spacing: 5.0, dashes: String::new() }
}
}
fn available_name(base: &str) -> String {
let choices = cadcraft_engine::pattern_choices();
let used = |name: &str| choices.iter().any(|p| p.name.eq_ignore_ascii_case(name));
let mut name = base.to_owned();
let mut suffix = 2;
while used(&name) {
name = format!("{base}_{suffix}");
suffix += 1;
}
name
}
impl Default for CustomPattern {
fn default() -> Self {
Self { name: available_name("MY_PATTERN"), families: vec![PatternFamily::default()] }
}
}
impl CustomPattern {
fn encode(&self) -> Option<(String, String)> {
let name = self.name.trim().to_ascii_uppercase();
if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') || cadcraft_doc::library::is_reserved_pattern_name(&name)
{
return None;
}
let mut text = format!("*{name}, Custom pattern\n");
for family in &self.families {
if !family.angle.is_finite() || !family.spacing.is_finite() || family.spacing <= 0.0 {
return None;
}
text.push_str(&format!("{},{},{},{},{}", family.angle, family.origin.0, family.origin.1, family.shift, family.spacing));
if !family.dashes.trim().is_empty() {
let dashes: Vec<_> =
family.dashes.split_whitespace().map(|value| value.parse::<f64>().ok().filter(|v| v.is_finite())).collect::<Option<_>>()?;
if dashes.iter().all(|d| *d == 0.0) {
return None;
}
for dash in dashes {
text.push_str(&format!(",{dash}"));
}
}
text.push('\n');
}
let parsed = cadcraft_doc::library::files::parse_pat(&text);
(parsed.items.len() == 1 && parsed.warnings.is_empty()).then_some((name, text))
}
}
/// Create mode, from the drawing's HATCH settings (HPNAME, HPSCALE, HPANG, HPASSOC, HPSEPARATE,
/// HPORIGINMODE, HPISLANDDETECTION); values a file got wrong fall back to the defaults.
pub fn create_state(d: &Drawing, uid: u64, gradient: bool) -> HatchDlgState {
cadcraft_engine::register_drawing_patterns(d);
let h = &d.header;
let scale = Some(h.f64("HPSCALE", 1.0)).filter(|v| v.is_finite() && *v > 0.0).unwrap_or(1.0);
let angle = Some(h.f64("HPANG", 0.0).to_degrees()).filter(|v| v.is_finite()).unwrap_or(0.0);
@@ -96,8 +171,11 @@ pub fn create_state(d: &Drawing, uid: u64, gradient: bool) -> HatchDlgState {
style: u8::try_from(h.i64("HPISLANDDETECTION", 0).clamp(0, 2)).unwrap_or(0),
};
HatchDlgState {
choices: cadcraft_engine::pattern_choices_in(d),
opened: fill.clone(),
fill,
custom: None,
saved_source: None,
edit: Vec::new(),
separate: h.i64("HPSEPARATE", 0) != 0,
points: Vec::new(),
@@ -105,6 +183,7 @@ pub fn create_state(d: &Drawing, uid: u64, gradient: bool) -> HatchDlgState {
loop_outer: Vec::new(),
remove_loops: Vec::new(),
picking: None,
capture_tile: false,
error: None,
uid,
space: Space::Model,
@@ -189,7 +268,17 @@ pub fn ok_call(st: &HatchDlgState) -> Option<(&'static str, Value)> {
p.insert("color2".into(), json!(f.color2.name()));
p.insert("centered".into(), json!(f.centered));
} else {
p.insert("pattern".into(), json!(f.pattern));
let pattern = if let Some(custom) = &st.custom {
let (name, text) = custom.encode()?;
p.insert("patternText".into(), json!(text));
name
} else {
if let Some(text) = &st.saved_source {
p.insert("patternText".into(), json!(text));
}
f.pattern.clone()
};
p.insert("pattern".into(), json!(pattern));
p.insert("scale".into(), json!(f.scale));
}
p.insert("angle".into(), json!(f.angle));
@@ -260,7 +349,7 @@ pub fn ok_call(st: &HatchDlgState) -> Option<(&'static str, Value)> {
/// Take a HATCHPICK's picks into the dialog (Hatch picks are taken by `resume`).
pub fn merge_picks(st: &mut HatchDlgState, picks: HatchPicks) {
match picks.mode {
PickMode::Points | PickMode::Objects => {
PickMode::Points | PickMode::TileRect | PickMode::Objects => {
st.points.extend(picks.points.iter().map(|q| [q.x, q.y]));
for h in picks.handles {
if !st.handles.contains(&h) {
@@ -324,6 +413,7 @@ pub fn start_pick(app: &mut CadApp, mode: PickMode) {
app.start("hatchpick");
let kw = match mode {
PickMode::Points => "Points",
PickMode::TileRect => "TileRect",
PickMode::Objects => "Objects",
PickMode::Origin => "oRigin",
PickMode::Hatch => "Hatch",
@@ -335,6 +425,27 @@ pub fn start_pick(app: &mut CadApp, mode: PickMode) {
}
}
/// Convert the engine's PAT result into editable fields in the dialog.
fn capture_draft(app: &mut CadApp, a: cadcraft_geom::Vec2, b: cadcraft_geom::Vec2) -> Result<CustomPattern, String> {
let params = json!({"first":[a.x,a.y], "second":[b.x,b.y], "name":available_name("CAPTURED_TILE")});
let result = app.run("hatch.capture", params)?;
let text = result["patternText"].as_str().ok_or_else(|| crate::tl!("Missing captured PAT definition").to_owned())?;
let parsed = cadcraft_doc::library::files::parse_pat(text);
let pattern = parsed.items.into_iter().next().ok_or_else(|| crate::tl!("Invalid captured PAT definition").to_owned())?;
let families = pattern
.lines
.into_iter()
.map(|line| PatternFamily {
origin: line.origin,
shift: line.delta.0,
angle: line.angle,
spacing: line.delta.1,
dashes: line.dashes.iter().map(ToString::to_string).collect::<Vec<_>>().join(" "),
})
.collect();
Ok(CustomPattern { name: pattern.name, families })
}
/// Every frame: once a HATCHPICK the dialog started has ended, take its picks and bring the
/// dialog back (unchanged when the pick was cancelled). A different drawing by then drops the
/// dialog and its picks; a Hatch pick that found none closes it.
@@ -356,7 +467,17 @@ pub fn resume(app: &mut CadApp) {
next.space = st.space.clone();
st = next;
} else if let Some(p) = picks {
merge_picks(&mut st, p);
if st.capture_tile && mode == PickMode::TileRect {
st.capture_tile = false;
if let [a, b] = p.points.as_slice() {
match capture_draft(app, *a, *b) {
Ok(pattern) => st.custom = Some(pattern),
Err(message) => st.error = Some(message),
}
}
} else {
merge_picks(&mut st, p);
}
}
app.hatch_dlg = Some(st);
app.ui.dialog = Some("hatch".into());
@@ -370,8 +491,12 @@ pub fn ok(app: &mut CadApp) -> bool {
app.hatch_dlg = None;
return true;
};
let authored = p["pattern"].as_str().zip(p["patternText"].as_str()).map(|(n, t)| (n.to_owned(), t.to_owned()));
match app.run(cmd, p) {
Ok(_) => {
if let Some((name, text)) = authored {
app.ui.hatch_patterns.insert(name, text);
}
app.hatch_dlg = None;
true
}
@@ -384,7 +509,31 @@ pub fn ok(app: &mut CadApp) -> bool {
}
}
/// Register a finished draft even when the user has not picked a surface to fill.
fn save_pattern(app: &mut CadApp) {
let Some((name, text)) = app.hatch_dlg.as_ref().and_then(|s| s.custom.as_ref()).and_then(CustomPattern::encode) else { return };
let result = app.run("hatch.patterns", json!({"text": text}));
let Some(st) = app.hatch_dlg.as_mut() else { return };
match result {
Ok(value) if value["added"].as_array().is_some_and(|a| a.iter().any(|n| n.as_str() == Some(&name))) => {
st.saved_source = Some(text.clone());
app.ui.hatch_patterns.insert(name.clone(), text);
st.fill.pattern = name;
if let Ok(d) = app.session.doc() {
st.choices = cadcraft_engine::pattern_choices_in(d);
}
st.custom = None;
st.error = None;
}
Ok(value) => {
st.error = Some(value["warnings"].as_array().into_iter().flatten().filter_map(Value::as_str).collect::<Vec<_>>().join("\n"));
}
Err(error) => st.error = Some(error),
}
}
enum Action {
SavePattern,
None,
Ok,
Cancel,
@@ -429,12 +578,16 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
return;
};
let title = if st.edit.is_empty() { crate::tl!("Hatch and Gradient") } else { crate::tl!("Hatch Edit") };
let mut action = Action::None;
// Esc cancels, as the Cancel button does.
let mut action = if crate::framework::escape_pressed(ctx) { Action::Cancel } else { Action::None };
egui::Window::new(title).id(egui::Id::unique("hatch_dialog")).open(open).collapsible(false).resizable(false).show(ctx, |ui| {
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
ui.set_width(340.0);
fill_ui(ui, &mut st.fill, &mut action);
fill_ui(ui, &mut st.fill, &st.choices, &mut st.saved_source, &mut action);
if st.edit.is_empty() && !st.fill.gradient {
custom_pattern_ui(ui, &mut st.custom, &mut st.capture_tile, &mut action);
}
});
// Space, not a vertical separator: a separator takes the height available, and the
// window grew by it every frame until the buttons left the screen.
@@ -449,7 +602,8 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
}
ui.separator();
ui.horizontal(|ui| {
let ready = !st.edit.is_empty() || !(st.points.is_empty() && st.handles.is_empty());
let valid = st.fill.gradient || st.custom.as_ref().is_none_or(|draft| draft.encode().is_some());
let ready = valid && (!st.edit.is_empty() || !(st.points.is_empty() && st.handles.is_empty()));
if ui.add_enabled(ready, egui::Button::new(crate::tl!("OK"))).clicked() {
action = Action::Ok;
}
@@ -469,6 +623,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
app.hatch_dlg = None;
*open = false;
}
Action::SavePattern => save_pattern(app),
Action::Pick(mode) => start_pick(app, mode),
Action::None => {
if !*open {
@@ -478,8 +633,62 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
}
}
fn custom_pattern_ui(ui: &mut egui::Ui, custom: &mut Option<CustomPattern>, capture_tile: &mut bool, action: &mut Action) {
let mut enabled = custom.is_some();
if ui.checkbox(&mut enabled, crate::tl!("Create a custom hatch pattern")).changed() {
*custom = enabled.then(CustomPattern::default);
}
let Some(draft) = custom else { return };
if ui
.button(crate::tl!("Capture square tile from drawing"))
.on_hover_text(crate::tl!("Pick two opposite corners to define the repeating tile"))
.clicked()
{
// The two corners become the horizontal and vertical repeat steps.
// The normal boundary picker remains available separately.
*capture_tile = true;
*action = Action::Pick(PickMode::TileRect);
}
let name = ui.label(crate::tl!("Pattern name"));
ui.add(egui::TextEdit::singleline(&mut draft.name).char_limit(31)).labelled_by(name.id);
ui.label(crate::tl!("Use spaces between dashes: positive draws, negative skips, zero marks a dot."));
let mut remove = None;
egui::ScrollArea::vertical().id_salt("custom-hatch-families").max_height(125.0).show(ui, |ui| {
for (index, family) in draft.families.iter_mut().enumerate() {
ui.push_id(index, |ui| {
ui.horizontal(|ui| {
let angle = ui.label(crate::tl!("Angle"));
ui.add(egui::DragValue::new(&mut family.angle).suffix("°")).labelled_by(angle.id);
let spacing = ui.label(crate::tl!("Spacing"));
ui.add(egui::DragValue::new(&mut family.spacing).range(0.0001..=1e6).clamp_existing_to_range(false)).labelled_by(spacing.id);
let dashes = ui.label(crate::tl!("Dashes"));
ui.add(egui::TextEdit::singleline(&mut family.dashes).char_limit(120).desired_width(70.0)).labelled_by(dashes.id);
if ui.small_button("×").on_hover_text(crate::tl!("Remove")).clicked() {
remove = Some(index);
}
})
});
}
});
if let Some(index) = remove
&& draft.families.len() > 1
{
draft.families.remove(index);
}
if ui.add_enabled(draft.families.len() < 16, egui::Button::new(crate::tl!("Add line family"))).clicked() {
draft.families.push(PatternFamily::default());
}
let valid = draft.encode().is_some();
if ui.add_enabled(valid, egui::Button::new(crate::tl!("Save pattern"))).clicked() {
*action = Action::SavePattern;
}
if !valid {
ui.colored_label(Tokens::get().warn, crate::tl!("Check the pattern name, spacing and dash values."));
}
}
/// Pattern/gradient fill selector and its controls; an origin pick is reported through `action`.
fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, action: &mut Action) {
fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, choices: &[cadcraft_engine::PatternChoice], saved_source: &mut Option<String>, action: &mut Action) {
ui.horizontal(|ui| {
ui.selectable_value(&mut f.gradient, false, crate::tl!("Pattern"));
ui.selectable_value(&mut f.gradient, true, crate::tl!("Gradient"));
@@ -515,11 +724,10 @@ fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, action: &mut Action) {
ui.end_row();
});
} else {
egui::ScrollArea::vertical().id_salt("hatch_swatches").max_height(220.0).show(ui, |ui| {
if let Some(name) = crate::palettes::patterns::grid(ui, &f.pattern, "") {
f.pattern = name;
}
});
if let Some(name) = crate::palettes::patterns::manager(ui, &f.pattern, choices) {
*saved_source = None;
f.pattern = name;
}
egui::Grid::new("hatch_pattern").num_columns(2).spacing(vec2(12.0, 6.0)).show(ui, |ui| {
ui.label(crate::tl!("Angle"));
ui.add(egui::DragValue::new(&mut f.angle).speed(1.0).range(-360.0..=360.0).clamp_existing_to_range(false).suffix("°"));
+377
View File
@@ -19,6 +19,13 @@ fn app_with_rect() -> (CadApp, Handle) {
(CadApp::new(s, Services::default()), r)
}
#[test]
fn capture_errors_use_the_dialog_translation_keys() {
let mut app = CadApp::new(Session::new(), Services::default());
assert_eq!(capture_draft(&mut app, Vec2::ZERO, Vec2::ZERO).unwrap_err(), crate::tl!("Pick two opposite corners for the tile"));
assert_eq!(capture_draft(&mut app, Vec2::ZERO, Vec2::new(10., 10.)).unwrap_err(), crate::tl!("No complete line segments in the selected tile."));
}
#[test]
fn pick_points_hides_the_dialog_and_brings_it_back_with_the_points() {
let (mut app, _) = app_with_rect();
@@ -471,3 +478,373 @@ fn edit_mode_leaves_out_a_selected_hatch_the_viewport_does_not_draw() {
assert_eq!(app.hatch_dlg.as_ref().map(|d| d.edit.clone()), Some(Vec::new()), "a hatch the viewport does not draw must not be edited");
assert!(app.session.running.is_some(), "HATCHPICK must be asking for a hatch");
}
#[test]
fn captured_tile_keeps_l_segments_and_excludes_outside_line() {
use cadcraft_doc::{Common, Line};
use cadcraft_engine::geom::Vec3;
let mut app = CadApp::new(Session::new(), Services::default());
for (a, b) in [([32., 42.], [32., 46.]), ([35., 42.], [32., 42.]), ([50., 60.], [57., 60.])] {
app.session
.doc_mut()
.unwrap()
.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::new(a[0], a[1], 0.), b: Vec3::new(b[0], b[1], 0.) }))
.unwrap();
}
open_create(&mut app, false);
app.hatch_dlg.as_mut().unwrap().capture_tile = true;
start_pick(&mut app, PickMode::TileRect);
for point in [Vec2::new(40., 50.), Vec2::new(30., 40.)] {
app.session.input(cadcraft_engine::Input::Point(point)).unwrap();
}
resume(&mut app);
let (_, text) = app.hatch_dlg.as_ref().unwrap().custom.as_ref().unwrap().encode().unwrap();
assert!(text.contains(",3,-7"), "horizontal L segment must repeat every 10 units: {text}");
assert!(text.contains(",4,-6"), "vertical L segment must repeat every 10 units: {text}");
assert!(!text.contains(",7,-3"), "outside segment must be excluded");
let rect = app.session.execute("rectang", &json!({"p1":[0,0],"p2":[30,20]})).unwrap();
app.hatch_dlg.as_mut().unwrap().handles.push(Handle::parse_hex(rect["handle"].as_str().unwrap()).unwrap());
assert!(ok(&mut app));
let d = app.session.doc().unwrap();
let reopened = cadcraft_io::read_dxf(cadcraft_io::write_dxf(d).as_bytes()).unwrap();
for drawing in [d, &reopened] {
let handle = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle;
let list = cadcraft_render::build(drawing, &Space::Model, &Default::default());
let segments: Vec<_> = list
.prims
.iter()
.filter(|p| p.handle == handle && p.kind == cadcraft_render::Kind::Polyline)
.map(|p| &list.verts[p.start as usize..(p.start + p.len) as usize])
.collect();
assert_eq!(segments.len(), 12, "two segments in each of six tiles: {segments:?}");
for x in [2., 12., 22.] {
for y in [2., 12.] {
let corner = Vec2::new(x, y);
for tip in [corner + Vec2::new(3., 0.), corner + Vec2::new(0., 4.)] {
assert!(
segments.iter().any(|s| s.len() == 2
&& ((s[0].dist(corner) < 1e-7 && s[1].dist(tip) < 1e-7) || (s[1].dist(corner) < 1e-7 && s[0].dist(tip) < 1e-7))),
"missing {corner:?} to {tip:?}: {segments:?}"
);
}
}
}
}
}
#[test]
fn tile_corners_do_not_require_closed_boundaries() {
let mut app = CadApp::new(Session::new(), Services::default());
open_create(&mut app, false);
start_pick(&mut app, PickMode::TileRect);
app.session.input(cadcraft_engine::Input::Enter).unwrap();
assert!(app.session.prompt_text().contains("first corner"));
app.session.input(cadcraft_engine::Input::Point(Vec2::new(20.0, 30.0))).unwrap();
app.session.input(cadcraft_engine::Input::Enter).unwrap();
assert!(app.session.prompt_text().contains("opposite corner"));
app.session.cmdline("Undo").unwrap();
assert!(app.session.prompt_text().contains("first corner"));
app.session.input(cadcraft_engine::Input::Point(Vec2::new(20.0, 30.0))).unwrap();
app.session.input(cadcraft_engine::Input::Point(Vec2::new(40.0, 50.0))).unwrap();
assert!(app.session.running.is_none());
assert_eq!(app.session.hatch_picks.as_ref().unwrap().points.len(), 2);
}
#[test]
fn a_custom_hatch_created_in_the_dialog_stores_its_line_families() {
let (mut app, boundary) = app_with_rect();
open_create(&mut app, false);
let state = app.hatch_dlg.as_mut().unwrap();
state.handles.push(boundary);
state.custom = Some(CustomPattern {
name: "DIEVART_TEST_HATCH".into(),
families: vec![PatternFamily::default(), PatternFamily { angle: 90.0, spacing: 3.0, dashes: "2 -1".into(), ..Default::default() }],
});
assert!(ok(&mut app));
let drawing = app.session.doc().unwrap();
let hatch = drawing.model.iter().find_map(|e| if let EntityKind::Hatch(hatch) = &e.kind { Some(hatch) } else { None }).unwrap();
assert_eq!(hatch.pattern, "DIEVART_TEST_HATCH");
assert_eq!(hatch.pattern_lines.len(), 2);
let expected = hatch.pattern_lines.clone();
let prefs = app.prefs_json();
let mut restarted = CadApp::new(Session::new(), Services::default());
// Replace the in-memory definition so success requires reading the saved families.
restarted.session.execute("hatch.patterns", &json!({"text":"*DIEVART_TEST_HATCH, temporary\n0,0,0,0,7\n"})).unwrap();
restarted.load_prefs(&prefs);
let restored = cadcraft_engine::pattern_choices().into_iter().find(|p| p.name == hatch.pattern).unwrap();
assert_eq!(restored.lines, expected);
assert_ne!(available_name(&hatch.pattern), hatch.pattern);
assert_eq!(restarted.ui.hatch_patterns, app.ui.hatch_patterns);
// An older DXF has an embedded definition, even on a machine without the author's preferences.
let dxf = cadcraft_io::write_dxf(drawing).replace("DIEVART_TEST_HATCH", "OLDER_EMBEDDED_TEST");
let reopened = cadcraft_io::read_dxf(dxf.as_bytes()).unwrap();
create_state(&reopened, 99, false);
let embedded = cadcraft_engine::pattern_choices().into_iter().find(|p| p.name == "OLDER_EMBEDDED_TEST").unwrap();
assert_eq!(embedded.lines.len(), expected.len());
}
#[test]
fn escape_closes_the_dialog_as_cancel_does() {
let (mut app, _) = app_with_rect();
open_create(&mut app, false);
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut open = true;
let esc = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
let mut out = ctx.run_ui(egui::RawInput { events: vec![esc], ..Default::default() }, |ui| dialog(&mut app, ui.ctx(), &mut open));
out.textures_delta.clear();
assert!(!open && app.hatch_dlg.is_none());
}
#[test]
fn stone_tile_excludes_skewed_frame_and_repeats_open_and_closed_polylines() {
use cadcraft_doc::{Common, LwPolyline};
use cadcraft_geom::PolyVertex;
let mut app = CadApp::new(Session::new(), Services::default());
let u = Vec2::new(700., 0.35);
let v = Vec2::new(0., 700.);
let stone = [Vec2::new(111.23, 161.71), Vec2::new(132.01, 158.33), Vec2::new(120.57, 147.83)];
let joint = [Vec2::new(0., 611.31), Vec2::new(21.49, 621.15), Vec2::new(66.21, 615.19)];
for (points, closed) in [(&[Vec2::ZERO, u, u + v, v][..], true), (&stone[..], true), (&joint[..], false)] {
let poly =
LwPolyline { vertices: points.iter().copied().map(PolyVertex::new).collect(), closed, const_width: 0., elevation: 0., plinegen: false };
app.session.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::LwPolyline(poly)).unwrap();
}
let custom = capture_draft(&mut app, u + v, Vec2::ZERO).unwrap();
assert_eq!(custom.families.len(), 5);
open_create(&mut app, false);
let rect = app.session.execute("rectang", &json!({"p1":[0,0],"p2":[1400,700]})).unwrap();
let state = app.hatch_dlg.as_mut().unwrap();
state.custom = Some(custom);
state.handles.push(Handle::parse_hex(rect["handle"].as_str().unwrap()).unwrap());
assert!(ok(&mut app));
let drawing = cadcraft_io::read_dxf(cadcraft_io::write_dxf(app.session.doc().unwrap()).as_bytes()).unwrap();
let handle = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle;
let list = cadcraft_render::build(&drawing, &Space::Model, &Default::default());
let runs: Vec<_> = list
.prims
.iter()
.filter(|p| p.handle == handle && p.kind == cadcraft_render::Kind::Polyline)
.map(|p| &list.verts[p.start as usize..(p.start + p.len) as usize])
.collect();
for offset in [Vec2::ZERO, u] {
for (a, b) in [(stone[0], stone[1]), (stone[1], stone[2]), (stone[2], stone[0]), (joint[0], joint[1]), (joint[1], joint[2])] {
let (a, b) = (a + offset, b + offset);
assert!(
runs.iter().any(|s| s.len() == 2 && ((s[0].dist(a) < 0.25 && s[1].dist(b) < 0.25) || (s[1].dist(a) < 0.25 && s[0].dist(b) < 0.25))),
"missing {a:?} to {b:?}"
);
}
}
}
#[test]
fn crossed_four_corner_polyline_is_part_of_the_motif() {
use cadcraft_doc::{Common, LwPolyline};
use cadcraft_geom::PolyVertex;
let mut app = CadApp::new(Session::new(), Services::default());
let corners = [Vec2::ZERO, Vec2::new(10., 10.), Vec2::new(0., 10.), Vec2::new(10., 0.)];
let poly =
LwPolyline { vertices: corners.into_iter().map(PolyVertex::new).collect(), closed: true, const_width: 0., elevation: 0., plinegen: false };
app.session.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::LwPolyline(poly)).unwrap();
let custom = capture_draft(&mut app, Vec2::ZERO, corners[1]).unwrap();
assert_eq!(custom.families.len(), 4);
}
#[test]
fn shallow_captured_edge_repeats_over_a_hundred_by_a_hundred_tiles() {
let mut app = CadApp::new(Session::new(), Services::default());
let tile = 10.;
let a = Vec2::new(0., 2.);
let b = a + Vec2::new(2047., 1.) * (tile / 2048.);
app.session.execute("line", &json!({"points":[[a.x,a.y],[b.x,b.y]]})).unwrap();
let capture = app.session.execute("hatch.capture", &json!({"first":[0,0],"second":[tile,tile],"name":"SHALLOW_CAPTURE_TEST"})).unwrap();
let text = &capture["patternText"];
let r = app.session.execute("rectang", &json!({"p1":[0,0],"p2":[1000,1000]})).unwrap();
app.session.execute("hatch", &json!({"handles":[r["handle"]],"pattern":"SHALLOW_CAPTURE_TEST","patternText":text})).unwrap();
let d = app.session.doc().unwrap();
let h = d.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle;
let list = cadcraft_render::build(d, &Space::Model, &Default::default());
let runs = list.prims.iter().filter(|p| p.handle == h && p.kind == cadcraft_render::Kind::Polyline);
let full = runs
.filter(|p| {
let seg = &list.verts[p.start as usize..(p.start + p.len) as usize];
seg.len() == 2 && (seg[0].dist(seg[1]) - a.dist(b)).abs() < 1e-6
})
.count();
assert_eq!(full, 10000);
}
#[test]
fn save_pattern_without_applying_it_then_use_it_in_a_new_drawing() {
let mut app = CadApp::new(Session::new(), Services::default());
open_create(&mut app, false);
app.hatch_dlg.as_mut().unwrap().custom = Some(CustomPattern { name: "UNAPPLIED_TILE_TEST".into(), families: vec![PatternFamily::default()] });
save_pattern(&mut app);
let st = app.hatch_dlg.as_ref().unwrap();
assert_eq!(st.fill.pattern, "UNAPPLIED_TILE_TEST");
assert!(st.custom.is_none() && st.error.is_none() && app.session.doc().unwrap().model.iter().next().is_none());
let (mut reopened, boundary) = app_with_rect();
reopened.load_prefs(&app.prefs_json());
open_create(&mut reopened, false);
let st = reopened.hatch_dlg.as_mut().unwrap();
st.fill.pattern = cadcraft_engine::pattern_choices().into_iter().find(|p| p.name == "UNAPPLIED_TILE_TEST").unwrap().name;
st.handles.push(boundary);
assert!(ok(&mut reopened));
assert!(
reopened
.session
.doc()
.unwrap()
.model
.iter()
.any(|e| matches!(&e.kind, EntityKind::Hatch(h) if h.pattern=="UNAPPLIED_TILE_TEST" && h.pattern_lines.len()==1))
);
}
#[test]
fn gallery_filters_by_description_and_selects_the_pattern_in_list_view() {
use egui_kittest::{Harness, kittest::Queryable};
let mut session = Session::new();
session.execute("hatch.patterns", &json!({"text":"*GALLERY_TEST, Quarry sample\n0,0,0,0,1\n"})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(360., 420.)).build_ui_state(
|ui, selected: &mut String| {
if let Some(name) = crate::palettes::patterns::manager(ui, selected, &cadcraft_engine::pattern_choices()) {
*selected = name;
}
},
String::new(),
);
h.get_by_label("Filter").click();
h.run_steps(3);
h.get_by_role(egui::accesskit::Role::TextInput).click();
h.run_steps(2);
h.get_by_role(egui::accesskit::Role::TextInput).type_text("quarry");
h.run_steps(3);
assert!(h.query_by_label("ANSI31").is_none());
h.get_by_role(egui::accesskit::Role::ComboBox).click();
h.run_steps(3);
h.get_by_label("List").click();
h.run_steps(3);
h.get_by_label("GALLERY_TEST").click();
h.run_steps(3);
assert_eq!(h.state(), "GALLERY_TEST");
}
#[test]
fn same_name_in_two_drawings_uses_the_active_drawings_geometry() {
let name = "SHARED_DXF_NAME_TEST";
let make = |spacing| {
let (mut app, boundary) = app_with_rect();
app.run("hatch", json!({"handles":[boundary.hex()],"pattern":name,"patternText":format!("*{name}, local\n0,0,0,0,{spacing}\n")})).unwrap();
let reopened = cadcraft_io::read_dxf(cadcraft_io::write_dxf(app.session.doc().unwrap()).as_bytes()).unwrap();
app.session.open_drawing(reopened, "Reopened", None);
(app, boundary, spacing)
};
let first = make(3);
let second = make(7);
for (mut app, boundary, spacing) in [first, second] {
open_create(&mut app, false);
let st = app.hatch_dlg.as_mut().unwrap();
let choice = st.choices.iter().find(|c| c.name == name).unwrap();
assert_eq!(choice.lines[0].delta.1, f64::from(spacing));
st.fill.pattern = name.into();
st.handles.push(boundary);
assert!(ok(&mut app));
let drawing = app.session.doc().unwrap();
let hatches: Vec<_> = drawing
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Hatch(h) => Some(h),
_ => None,
})
.collect();
assert_eq!(hatches.len(), 2);
assert!(hatches.iter().all(|h| h.pattern_lines[0].delta.1 == f64::from(spacing)));
}
}
#[test]
fn aligned_sparse_marks_still_get_a_visible_swatch() {
let family = cadcraft_doc::library::PatternLine { angle: 0., origin: (70., 0.), delta: (100., 1.), dashes: vec![1., -99.] };
assert!(!cadcraft_render::pattern_swatch(&[family], 1.).is_empty());
}
#[test]
fn capture_refuses_a_polyline_with_a_segment_lost_to_rounding() {
use cadcraft_doc::{Common, LwPolyline};
use cadcraft_geom::PolyVertex;
let mut app = CadApp::new(Session::new(), Services::default());
let vertices = [Vec2::new(1., 1.), Vec2::new(1.001, 1.), Vec2::new(8., 6.)].into_iter().map(PolyVertex::new).collect();
let poly = LwPolyline { vertices, closed: false, const_width: 0., elevation: 0., plinegen: false };
app.session.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::LwPolyline(poly)).unwrap();
assert_eq!(
capture_draft(&mut app, Vec2::ZERO, Vec2::new(10., 10.)).unwrap_err(),
crate::tl!("A segment is too small for the tile capture precision.")
);
}
#[test]
fn applying_a_just_saved_pattern_uses_its_new_spacing() {
let (mut app, boundary) = app_with_rect();
let name = "SAVED_OVER_EMBEDDED_TEST";
let old = app.run("hatch", json!({"handles":[boundary.hex()], "pattern":name, "patternText":format!("*{name}, old\n0,0,0,0,3\n")})).unwrap();
let old = Handle::parse_hex(old["handle"].as_str().unwrap()).unwrap();
open_create(&mut app, false);
let st = app.hatch_dlg.as_mut().unwrap();
st.handles.push(boundary);
st.custom = Some(CustomPattern { name: name.into(), families: vec![PatternFamily { spacing: 7., ..Default::default() }] });
save_pattern(&mut app);
assert!(app.hatch_dlg.as_ref().unwrap().custom.is_none());
assert!(ok(&mut app));
let drawing = app.session.doc().unwrap();
let hatches: Vec<_> = drawing
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Hatch(h) if h.pattern == name => Some((e.handle, h.pattern_lines[0].delta.1)),
_ => None,
})
.collect();
assert_eq!(hatches.len(), 2);
assert!(hatches.contains(&(old, 3.)));
assert!(hatches.iter().any(|(handle, spacing)| *handle != old && *spacing == 7.));
}
#[test]
fn reserved_user_hatch_cannot_be_shadowed_by_a_custom_pattern() {
use cadcraft_doc::library::is_user_pattern;
let (mut app, boundary) = app_with_rect();
let reserved = "_uSeR";
let ordinary = "RESERVED_NAME_CONTROL";
let draft = CustomPattern { name: reserved.into(), families: vec![PatternFamily::default()] };
assert!(draft.encode().is_none());
assert!(app.run("hatch.capture", json!({"first":[0,0], "second":[10,10], "name":reserved})).is_err());
let source = format!("*{reserved}, collision\n0,0,0,0,13\n*{ordinary}, named\n30,0,0,0,7\n");
let registered = app.run("hatch.patterns", json!({"text":source})).unwrap();
assert_eq!(registered["added"], json!([ordinary]));
assert!(!registered["warnings"].as_array().unwrap().is_empty());
app.session.cmdline("(command \"_.hatch\" \"_u\" 45 100 \"_y\" \"_l\" \"\")").unwrap();
app.run("hatch", json!({"handles":[boundary.hex()], "pattern":ordinary})).unwrap();
let drawing = app.session.doc().unwrap();
let hatch = |name: &str| {
drawing
.model
.iter()
.find_map(|e| match &e.kind {
EntityKind::Hatch(h) if h.pattern.eq_ignore_ascii_case(name) => Some(h),
_ => None,
})
.unwrap()
};
let native = hatch(reserved);
assert_eq!(native.pattern_lines, cadcraft_doc::library::user_defined_lines(true));
assert_eq!(native.scale, 100.);
assert_eq!(hatch(ordinary).pattern_lines[0].delta.1, 7.);
cadcraft_engine::register_drawing_patterns(drawing);
assert!(!cadcraft_engine::pattern_choices_in(drawing).iter().any(|p| is_user_pattern(&p.name)));
assert!(!cadcraft_engine::pattern_choices().iter().any(|p| is_user_pattern(&p.name)));
}
+1
View File
@@ -185,6 +185,7 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet<String> {
"layers",
"bedit",
"palettes",
"managers/textstyle",
"managers/dimstyle",
"parametric",
"quick",
+4
View File
@@ -411,6 +411,7 @@
List 列表
List Blocks 列出块
List Dimension Styles 列出标注样式
List Fonts 列出字体
List Groups 列出编组
List Layer States 列出图层状态
List Layouts 列出布局
@@ -499,6 +500,7 @@
One of the Crafting Apps by the ArtCraft team and community. 由 ArtCraft 团队和社区打造的 Crafting 系列应用之一。
Oops 恢复已擦除对象
Open (⌘O) 打开 (⌘O)
Open Provider File 打开提供方文件
Open Sample Drawing 打开示例图形
Open sample drawing 打开示例图形
Open... 打开...
@@ -924,6 +926,7 @@
Text 文字
Text Editor 文字编辑器
Text Height 文字高度
Text Style 文字样式
Text Style... 文字样式...
Text height 文字高度
Text override 文字替代
@@ -1447,6 +1450,7 @@
B B
Backup copy 备份副本
Block to create or edit 要创建或编辑的块
Capture hatch tile 捕获图案填充单元
Choose the command the alias starts. 选择别名要启动的命令。
Click the ruler to add a tab stop, right-click to remove one 单击标尺可添加制表位,右键单击可将其删除
Command 命令
1 # CADCraft Simplified Chinese interface catalog — original translations.
411
412
413
414
415
416
417
500
501
502
503
504
505
506
926
927
928
929
930
931
932
1450
1451
1452
1453
1454
1455
1456
+7 -1
View File
@@ -116,6 +116,8 @@ pub enum Icon {
QuickProps,
Gear,
Annotation,
/// An annotative style or object: a drafting set square.
Annotative,
Workspace,
ChevronDown,
ChevronUp,
@@ -815,7 +817,7 @@ fn paint_layer_tools(pen: &Pen<'_>, icon: Icon, _b: Color32, _a: Color32, dim: b
}
}
fn paint_display_toggles(pen: &Pen<'_>, icon: Icon, b: Color32, _a: Color32, dim: bool) {
fn paint_display_toggles(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, dim: bool) {
let alpha = |c: Color32| if dim { c.gamma_multiply(0.4) } else { c };
use Icon::*;
match icon {
@@ -924,6 +926,10 @@ fn paint_display_toggles(pen: &Pen<'_>, icon: Icon, b: Color32, _a: Color32, dim
pen.l(12.0, 9.0, 12.0, 15.0);
pen.fill_c(12.0, 17.5, 1.0, b);
}
Annotative => {
pen.poly(&[(4.0, 3.0), (4.0, 20.0), (21.0, 20.0)], true, b);
pen.poly(&[(7.5, 10.5), (7.5, 16.5), (13.5, 16.5)], true, a);
}
Workspace => {
pen.rect(3.0, 4.0, 18.0, 16.0, b);
pen.l(9.0, 4.0, 9.0, 20.0);
+38 -1
View File
@@ -81,6 +81,8 @@ pub mod vpscale;
pub mod wblock;
pub mod exchange;
mod file_provider_app;
pub mod file_providers;
use std::path::Path;
use std::sync::mpsc::Receiver;
@@ -143,6 +145,7 @@ pub struct UiState {
pub save_version: String,
/// Drawings opened from a path, newest first (File ▸ Open Recent and the Start page).
pub recent_files: Vec<String>,
pub(crate) hatch_patterns: std::collections::BTreeMap<String, String>,
/// The folder the last APPLOAD file came from: the next pick starts there.
pub last_lisp_dir: Option<String>,
/// The folder the Command Aliases dialog last imported a `.pgp` file from.
@@ -224,6 +227,7 @@ impl Default for UiState {
save_format: SaveFormat::default(),
save_version: SaveVersion::default().year().to_string(),
recent_files: Vec::new(),
hatch_patterns: Default::default(),
last_lisp_dir: None,
last_pgp_dir: None,
}
@@ -304,6 +308,8 @@ pub struct CadApp {
/// The interface's own preferences from the Options dialog ([`options`]).
pub options: options::UiOptions,
pub services: Services,
/// Disabled until an explicit same-origin web host registers a provider.
pub file_providers: file_providers::Host,
pub canvas: canvas::CanvasState,
/// Desktop HID status and navigation preferences; the web host supplies no HID backend.
pub spacemouse: spacemouse::State,
@@ -414,6 +420,7 @@ impl CadApp {
ui: UiState::default(),
options: options::UiOptions::default(),
services,
file_providers: file_providers::Host::default(),
canvas: canvas::CanvasState::default(),
spacemouse: spacemouse::State::default(),
quickcalc: palettes::quickcalc::State::default(),
@@ -620,13 +627,26 @@ impl CadApp {
/// Run a command programmatically (or a UI command).
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
if self.file_providers.busy() && matches!(id, "close" | "closeall" | "revert") {
return Err("finish or cancel the pending file provider operation before closing or reverting".into());
}
if let Some(r) = menus::run_ui_command(self, id, &params) {
return r;
}
// The bars as the interface shows them now (a `ui.set` may have just changed one), and any
// MENUBAR or TOOLBAR request applied at once.
self.sync_bars();
let r = self.session.execute(id, &params).map_err(|e| e.to_string());
let r = self.session.execute(id, &params).map_err(|error| match &error {
cadcraft_engine::EngineError::BadParams { cmd, msg } if cmd == "hatch.capture" => match msg.as_str() {
"Pick two opposite corners for the tile" => crate::tl!("Pick two opposite corners for the tile").to_owned(),
"A segment is too small for the tile capture precision." => {
crate::tl!("A segment is too small for the tile capture precision.").to_owned()
}
"No complete line segments in the selected tile." => crate::tl!("No complete line segments in the selected tile.").to_owned(),
_ => error.to_string(),
},
_ => error.to_string(),
});
self.sync_bars();
if let Ok(v) = &r
&& let Some(m) = v.get("message").and_then(Value::as_str)
@@ -750,6 +770,9 @@ impl CadApp {
if self.spacemouse.settings != spacemouse::Settings::default() {
prefs["spacemouse"] = json!(self.spacemouse.settings);
}
if !self.ui.hatch_patterns.is_empty() {
prefs["hatchPatterns"] = json!(self.ui.hatch_patterns);
}
if !self.ui.recent_files.is_empty() {
prefs["recentFiles"] = json!(self.ui.recent_files);
}
@@ -768,6 +791,19 @@ impl CadApp {
/// Restore preferences saved by [`Self::prefs_json`]; unknown or malformed values are ignored.
pub fn load_prefs(&mut self, json: &str) {
let Ok(v) = serde_json::from_str::<Value>(json) else { return };
if let Some(patterns) = v["hatchPatterns"].as_object() {
for (name, text) in patterns {
if let Some(text) = text.as_str()
&& self
.session
.execute("hatch.patterns", &json!({"text":text}))
.ok()
.is_some_and(|v| v["added"].as_array().is_some_and(|a| a.iter().any(|n| n.as_str() == Some(name))))
{
self.ui.hatch_patterns.insert(name.clone(), text.to_owned());
}
}
}
if let Some(calculator) = v.get("quickcalc") {
self.quickcalc.load_prefs(calculator);
}
@@ -1007,6 +1043,7 @@ impl CadApp {
/// pass index is zero. `current_pass_index() == 0` is therefore the frame guard: true on the
/// first pass and every hidden tick, false on later passes.
pub fn logic(&mut self, ctx: &egui::Context) {
file_provider_app::tick(self);
// Consume-based queues: each item is handled once, whichever callback delivers it. A
// reply arriving during a later pass is never starved until the next frame.
self.drain_control(ctx);
+3 -27
View File
@@ -21,6 +21,8 @@ mod battman;
mod dimstyle;
/// Named Viewports (View > Viewports > Named Viewports...).
mod named_vports;
/// The Text Style dialog (STYLE).
mod textstyle;
/// Open the dialog for a typed or menu-invoked command. `None` if `id` has no dialog here or the
/// call carries parameters.
@@ -55,7 +57,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, name: &str, open: &mut bool
"battman" => battman::dialog(app, ctx, open),
"linetype" => linetype(app, ctx, open),
"ptype" => point_style(app, ctx, open),
"textstyle" => text_style(app, ctx, open),
"textstyle" => textstyle::dialog(app, ctx, open),
"dimstyle" => dimstyle::dialog(app, ctx, open),
"tablestyle" => table_style(app, ctx, open),
"mleaderstyle" => mleader_style(app, ctx, open),
@@ -351,32 +353,6 @@ struct Style {
fields: Vec<Field>,
}
fn text_style(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action {
let Ok(d) = app.session.doc() else {
no_drawing(ctx, "Text Style", open);
return None;
};
let mut styles: Vec<Style> = d
.text_styles
.iter()
.map(|s| Style {
name: s.name.clone(),
fields: vec![
Field::Num("height", "Height (0 = ask)", s.height, NumRule::NonNegative),
Field::Num("widthFactor", "Width factor", s.width_factor, NumRule::Positive),
Field::Bool("backwards", "Backwards", s.backwards),
Field::Bool("upsideDown", "Upside down", s.upside_down),
],
})
.collect();
if styles.is_empty() {
let s = cadcraft_doc::TextStyle::default();
styles.push(Style { name: s.name, fields: Vec::new() });
}
let current = d.header.str("TEXTSTYLE", "Standard");
style_manager(ctx, open, "Text Style", "style", &current, &styles)
}
fn table_style(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action {
let Ok(d) = app.session.doc() else {
no_drawing(ctx, "Table Style", open);
+931
View File
@@ -0,0 +1,931 @@
//! The Text Style dialog (STYLE): the drawing's text styles (all, or those in use) with a
//! preview, Set Current, New, Rename and Delete; the selected style's font by family and style
//! from the installed fonts, its height (the paper height of an annotative style) and its
//! effects. Edits wait for Apply, and leaving a style with edits not applied asks first, as
//! AutoCAD does.
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use cadcraft_engine::doc::{Common, Drawing, EntityKind, Space, Text, TextStyle};
use cadcraft_fonts::BUILTIN_FONT;
use cadcraft_fonts::ttf::FontEntry;
use egui::{RichText, vec2};
use serde_json::{Value, json};
use crate::CadApp;
use crate::icons::{self, Icon};
use crate::parametric::expr_field;
use crate::theme::Tokens;
const STATE: &str = "textstyle_dialog";
/// What waits for an answer about edits not applied yet.
#[derive(Clone, PartialEq)]
enum After {
Select(String),
SetCurrent,
New,
Close,
}
#[derive(Clone, Default)]
struct State {
/// The drawing whose pending edits and field buffers this state belongs to.
doc_uid: u64,
/// The style chosen in the list.
selected: String,
in_use_only: bool,
/// The chosen style as edited, until Apply (`None`: no edits).
edit: Option<TextStyle>,
/// The style as it was when the first edit began: Apply sends only what differs from it, so a
/// change made to another field by another route meanwhile is not written back over.
base: TextStyle,
/// Why the last entry in a number field was refused, shown until the next one is accepted.
bad_input: Option<String>,
/// Asking whether to apply the edits before doing this.
confirm: Option<After>,
/// The name being typed for New.
new_name: Option<String>,
/// (style, new name) while renaming.
renaming: Option<(String, String)>,
font_filter: String,
/// Use Big Font ticked while no big font is named yet.
big_font_on: bool,
/// The control to take the focus on the next frame: the dialog has just opened, or its page changed.
take_focus: bool,
/// What had the focus when the dialog opened, to give it back when the dialog closes.
focus_before: Option<egui::Id>,
/// The pass that last drew the dialog: a gap means it was closed or replaced and has just
/// opened again.
last_pass: Option<u64>,
/// The dialog's window layer, to tell whether the focus or a click is in it.
layer: Option<egui::LayerId>,
/// Whether the keys are the dialog's: the focus is in it, or was and nothing has taken it.
/// egui drops the focus when an Escape arrives, before this code runs, when a control goes
/// away and on a click on blank space; a list or menu holds it for a while. So only the focus
/// moving to another window, or a click outside, takes the keys away. Then an Escape for a
/// command running in the drawing is left to it.
has_keys: bool,
/// Whether a popup was open at the end of the pass before: a menu that an Escape closes
/// earlier in the same pass is then still counted as open.
popup_was: bool,
/// The control of the dialog that last had the focus, to give it back when a list or menu
/// opened from the dialog closes.
last_focus: Option<egui::Id>,
/// The control a closed list or menu owes the focus, with the pass it closed in.
restore_to: Option<(egui::Id, u64)>,
/// The pass a popup last closed in by a key: for a pass or two its item still looks focused.
popup_closed: u64,
/// The rename field takes the focus when it first shows.
rename_focus: bool,
}
/// The page the dialog shows.
#[derive(Clone, Copy, Default, PartialEq)]
enum Page {
/// The styles and the chosen style's settings.
#[default]
Main,
/// Asking whether to apply the edits before going on.
Confirm,
/// Naming a new style.
New,
}
fn page(st: &State) -> Page {
if st.confirm.is_some() {
Page::Confirm
} else if st.new_name.is_some() {
Page::New
} else {
Page::Main
}
}
/// Follows who has the keys (see `State::has_keys`) from where the focus and the pointer are.
fn track_keys(ctx: &egui::Context, st: &mut State, popup_open: bool, pass: u64) {
let focus_layer = ctx.memory(|memory| memory.focused()).and_then(|id| ctx.read_response(id)).map(|widget| widget.layer_id);
match focus_layer {
Some(layer) if Some(layer) == st.layer => st.has_keys = true,
// A list or menu: opened from the dialog or from anywhere else, so nothing changes. One that
// has just closed still shows its item as focused for a pass or two.
Some(layer) if layer.order == egui::Order::Foreground && (popup_open || pass <= st.popup_closed.saturating_add(2)) => {}
// The drawing, the command line, another window, or an editor over the drawing.
Some(_) => st.has_keys = false,
None => {}
}
if let Some(at) = ctx.input(|i| if i.pointer.any_pressed() { i.pointer.interact_pos() } else { None }) {
// The topmost window under the pointer decides: the dialog gives it the keys, an item of a
// list or menu changes nothing, anything else (another window, the drawing, a bar) takes
// them away, even when a list is open and the click closes it.
match ctx.layer_id_at(at) {
Some(layer) if Some(layer) == st.layer => st.has_keys = true,
Some(layer) if layer.order == egui::Order::Foreground && popup_open => {}
_ => st.has_keys = false,
}
}
}
/// The style command's parameters for `st` as `name`, not made current.
fn apply_params(name: &str, st: &TextStyle) -> Value {
json!({
"name": name,
"font": st.font,
"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": false,
})
}
/// The style command's parameters for the fields `edit` changed from `base` only, so Apply
/// leaves alone what another route changed in the style since the edit began.
fn changed_params(name: &str, base: &TextStyle, edit: &TextStyle) -> Value {
let (all, was) = (apply_params(name, edit), apply_params(name, base));
let Value::Object(mut all) = all else { return Value::Null };
all.retain(|key, value| matches!(key.as_str(), "name" | "current") || was.get(key) != Some(value));
Value::Object(all)
}
/// "style1", "style2", … : the first name not taken, as AutoCAD offers.
fn new_name(d: &Drawing) -> String {
(1..10_000).map(|i| format!("style{i}")).find(|n| d.text_style(n).is_none()).unwrap_or_else(|| "style".into())
}
/// A name no text style can have (as -STYLE refuses it), trimmed.
fn bad_name(name: &str) -> bool {
name.is_empty() || name.len() > 255 || name.contains(['<', '>', '/', '\\', '"', ':', ';', '?', '*', '|', ',', '=', '`'])
}
/// Whether style `name` can be deleted: not Standard, the current style or a style in use.
fn deletable(name: &str, current: &str, used: &[String]) -> bool {
!name.eq_ignore_ascii_case("Standard") && !name.eq_ignore_ascii_case(current) && !used.iter().any(|n| n.eq_ignore_ascii_case(name))
}
/// The text styles in use, worked out again only when the drawing changes.
fn in_use(ctx: &egui::Context, app: &CadApp) -> Arc<Vec<String>> {
let Ok(st) = app.session.state() else { return Arc::default() };
let key = (st.uid, st.revision);
let id = egui::Id::unique("textstyle_in_use");
if let Some((k, v)) = ctx.data(|m| m.get_temp::<((u64, u64), Arc<Vec<String>>)>(id))
&& k == key
{
return v;
}
let v = Arc::new(cadcraft_engine::cmd::text_styles_in_use(&st.doc));
ctx.data_mut(|m| m.insert_temp(id, (key, v.clone())));
v
}
/// The installed fonts, listed once.
fn fonts(ctx: &egui::Context) -> Arc<Vec<FontEntry>> {
let id = egui::Id::unique("textstyle_fonts");
if let Some(v) = ctx.data(|m| m.get_temp::<Arc<Vec<FontEntry>>>(id)) {
return v;
}
let v = Arc::new(cadcraft_fonts::ttf::installed_fonts());
ctx.data_mut(|m| m.insert_temp(id, v.clone()));
v
}
fn is_builtin(font: &str) -> bool {
font.trim().is_empty() || font.trim().eq_ignore_ascii_case(BUILTIN_FONT)
}
/// The installed face a style's font names: by file name ("arialbd.ttf", "arialbd"), else by
/// family (its Regular face, or its first).
fn face_of<'a>(font: &str, fonts: &'a [FontEntry]) -> Option<&'a FontEntry> {
let f = font.trim().to_ascii_lowercase();
// The catalog resolves bare outline names. Explicit SHX names must not match by stem.
if f.is_empty() || f.ends_with(".shx") {
return None;
}
// Any case: font files are often named in capitals (ARIALN.TTF), and the renderer finds them so.
let stem = |s: &str| s.rsplit_once('.').map_or(s, |(a, _)| a).to_ascii_lowercase();
fonts
.iter()
.find(|e| e.file.eq_ignore_ascii_case(&f) || stem(&e.file) == stem(&f))
.or_else(|| fonts.iter().filter(|e| e.family.eq_ignore_ascii_case(&f)).min_by_key(|e| !e.style.eq_ignore_ascii_case("Regular")))
}
pub(super) fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> super::Action {
let used = in_use(ctx, app);
let fonts = fonts(ctx);
let Ok(doc_state) = app.session.state() else {
super::no_drawing(ctx, crate::tl!("Text Style"), open);
return None;
};
let d = &*doc_state.doc;
let mut st: State = super::temp(ctx, STATE).unwrap_or_default();
// The first pass of an opening: the dialog takes the focus, and remembers what had it, so
// closing gives it back. It is drawn on every pass while it is open, so a gap means it was
// closed (by any route, or replaced by another dialog) and has opened again.
let pass = ctx.cumulative_pass_nr();
let opening = st.last_pass.is_none_or(|last| last.saturating_add(1) < pass);
st.last_pass = Some(pass);
// Read before the dialog draws: a popup closes itself on an Escape while it is drawn.
let popup_open = st.popup_was || egui::Popup::is_any_open(ctx);
track_keys(ctx, &mut st, popup_open, pass);
if opening {
st.focus_before = ctx.memory(|memory| memory.focused());
st.has_keys = true;
}
// The focus a closed list or menu owes back: only to a control that is still there and
// enabled (the choice may have turned a button off, hidden a row or deleted a style); else the
// chosen style takes it. A focus request already waiting is not overridden.
if let Some((id, since)) = st.restore_to
&& pass >= since.saturating_add(2)
{
st.restore_to = None;
if st.has_keys {
if !st.take_focus && ctx.read_response(id).is_some_and(|widget| widget.enabled()) {
ctx.memory_mut(|memory| memory.request_focus(id));
} else {
st.take_focus = true;
}
}
}
if st.doc_uid != doc_state.uid {
// A drawing switch starts the page state again. What the dialog remembers about the focus
// belongs to the dialog, not to the drawing, and a field of the old drawing that held the
// focus is gone: the styles take it when the dialog has the keys.
st = State {
doc_uid: doc_state.uid,
focus_before: st.focus_before,
last_pass: st.last_pass,
layer: st.layer,
has_keys: st.has_keys,
popup_was: st.popup_was,
last_focus: st.last_focus,
take_focus: st.has_keys,
..State::default()
};
}
let current = d.header.str("TEXTSTYLE", "Standard");
if d.text_style(&st.selected).is_none() {
st.selected = current.clone();
st.edit = None;
}
let saved = d.text_style(&st.selected).cloned().unwrap_or_default();
let mut actions: Vec<(&'static str, Value)> = Vec::new();
let mut keep = true;
let page_before = page(&st);
let shown = egui::Window::new(crate::tl!("Text Style"))
.id(egui::Id::unique(STATE))
.open(&mut keep)
.default_size(vec2(720.0, 400.0))
.resizable(true)
.collapsible(false)
.show(ctx, |ui| {
if let Some(after) = st.confirm.clone() {
confirm_page(ui, d, &mut st, &saved, after, &mut actions, open);
} else if st.new_name.is_some() {
new_page(ui, d, &mut st, &saved, &mut actions);
} else {
main_page(ui, d, &mut st, &saved, &current, &used, &fonts, &mut actions, open);
}
});
if let Some(window) = &shown {
st.layer = Some(window.response.layer_id);
}
if !keep {
request(d, &mut st, After::Close, &mut actions, open);
}
// Escape cancels the innermost thing first: a question (keeping the edits), the New page or a
// rename. Only the plain styles page closes on it, asking first when edits wait. A popup with
// the keys (the font list) takes the Escape itself, so it closes the list, not the dialog; and
// an Escape meant for something else (a command running in the drawing) is left to it.
if *open && keep && st.has_keys && !popup_open && crate::framework::escape_pressed(ctx) {
if st.confirm.is_some() {
st.confirm = None;
} else if st.new_name.is_some() {
st.new_name = None;
} else if st.renaming.take().is_some() {
st.take_focus = true;
} else {
request(d, &mut st, After::Close, &mut actions, open);
}
}
// A page that has just appeared takes the focus: the question, the name field, or the styles.
if opening || page(&st) != page_before {
st.take_focus = true;
}
if !*open {
// The focus goes back only when the dialog had the keys and the control is still there (a
// menu item that opened the dialog is gone): not taken from what the person moved to since.
let there = |id: &egui::Id| ctx.read_response(*id).is_some();
if let Some(id) = st.focus_before.take().filter(|id| st.has_keys && there(id)) {
ctx.memory_mut(|memory| memory.request_focus(id));
}
}
// A list or menu of the dialog that a key closed (Escape, or Enter or Space on an item) gives
// the focus back to the control that opened it, while the dialog has the keys. egui drops the
// focus as an Escape arrives and takes a chosen item's focus with the list, so nothing else
// would hold it.
let by_key = crate::framework::escape_pressed(ctx) || ctx.input(|i| i.key_pressed(egui::Key::Enter) || i.key_pressed(egui::Key::Space));
let popup_now = egui::Popup::is_any_open(ctx);
if popup_open
&& !popup_now
&& by_key
&& st.has_keys
&& let Some(id) = st.last_focus
{
// Given back two passes later, once what the menu or list did has been drawn.
st.restore_to = Some((id, pass));
}
// Only a list or menu that a key closed: its last item then still looks focused for a pass or
// two. One that a click closed gives the focus to whatever was clicked, an editor over the
// drawing included.
if popup_open && !popup_now && by_key {
st.popup_closed = pass;
}
st.popup_was = popup_now;
if let Some(id) =
ctx.memory(|memory| memory.focused()).filter(|id| ctx.read_response(*id).is_some_and(|widget| Some(widget.layer_id) == st.layer))
{
st.last_focus = Some(id);
}
super::set_temp(ctx, STATE, st);
// Errors are echoed on the command line by `run`; a failed step stops the rest.
for (cmd, p) in actions {
if app.run(cmd, p).is_err() {
break;
}
}
None
}
/// Do `after` now, or ask first when the chosen style has edits not applied.
fn request(d: &Drawing, st: &mut State, after: After, actions: &mut Vec<(&'static str, Value)>, open: &mut bool) {
if st.edit.is_some() {
st.confirm = Some(after);
} else {
perform(d, st, after, actions, open);
}
}
fn perform(d: &Drawing, st: &mut State, after: After, actions: &mut Vec<(&'static str, Value)>, open: &mut bool) {
match after {
After::Select(name) => {
st.selected = name;
st.edit = None;
st.bad_input = None;
st.big_font_on = false;
}
After::SetCurrent => {
actions.push(("style.current", json!({ "name": st.selected })));
// The button disables itself: the focus goes to the styles, not nowhere.
st.take_focus = true;
}
After::New => st.new_name = Some(new_name(d)),
After::Close => {
// The page state outlives the window: the next STYLE opens on the styles, not on New
// or a rename left open.
st.new_name = None;
st.renaming = None;
*open = false;
}
}
}
fn confirm_page(
ui: &mut egui::Ui,
d: &Drawing,
st: &mut State,
saved: &TextStyle,
after: After,
actions: &mut Vec<(&'static str, Value)>,
open: &mut bool,
) {
ui.label(crate::tf!("The style {style} has been modified. Do you want to save your changes?", style = saved.name));
ui.add_space(8.0);
ui.horizontal(|ui| {
let yes = ui.button(crate::tl!("Yes"));
if st.take_focus {
yes.request_focus();
st.take_focus = false;
}
if yes.clicked() {
if let Some(e) = st.edit.take() {
actions.push(("style", changed_params(&saved.name, &st.base, &e)));
}
st.bad_input = None;
st.confirm = None;
perform(d, st, after.clone(), actions, open);
}
if ui.button(crate::tl!("No")).clicked() {
st.edit = None;
st.confirm = None;
perform(d, st, after.clone(), actions, open);
}
if ui.button(crate::tl!("Cancel")).clicked() {
st.confirm = None;
}
});
}
fn new_page(ui: &mut egui::Ui, d: &Drawing, st: &mut State, saved: &TextStyle, actions: &mut Vec<(&'static str, Value)>) {
let mut name = st.new_name.clone().unwrap_or_default();
ui.label(RichText::new(crate::tl!("New Text Style")).strong());
let mut enter = false;
ui.horizontal(|ui| {
let caption = ui.label(crate::tl!("Style Name"));
let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(220.0)).labelled_by(caption.id);
if st.take_focus {
r.request_focus();
st.take_focus = false;
}
enter = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
});
let trimmed = name.trim().to_string();
let taken = d.text_style(&trimmed).is_some();
let bad = bad_name(&trimmed);
if taken {
ui.label(RichText::new(crate::tl!("A text style with this name already exists.")).color(Tokens::get().text_dim));
}
ui.add_space(8.0);
ui.horizontal(|ui| {
if (ui.add_enabled(!taken && !bad, egui::Button::new(crate::tl!("OK"))).clicked() || enter && !taken && !bad) && st.new_name.is_some() {
// The new style starts with the chosen style's settings.
actions.push(("style", apply_params(&trimmed, saved)));
st.selected = trimmed.clone();
st.edit = None;
st.new_name = None;
}
if ui.button(crate::tl!("Cancel")).clicked() {
st.new_name = None;
}
});
if st.new_name.is_some() {
st.new_name = Some(name);
}
}
#[allow(clippy::too_many_arguments)]
fn main_page(
ui: &mut egui::Ui,
d: &Drawing,
st: &mut State,
saved: &TextStyle,
current: &str,
used: &[String],
fonts: &[FontEntry],
actions: &mut Vec<(&'static str, Value)>,
open: &mut bool,
) {
let t = Tokens::get();
ui.label(RichText::new(crate::tf!("Current text style: {style}", style = current)).color(t.text_dim));
ui.add_space(4.0);
let mut v = st.edit.clone().unwrap_or_else(|| saved.clone());
let before = st.selected.clone();
let mut deleted = false;
let mut pending = None;
ui.horizontal_top(|ui| {
// The styles and the preview.
ui.vertical(|ui| {
ui.set_width(200.0);
let styles = ui.label(RichText::new(crate::tl!("Styles")).strong());
let focus_target = style_list(ui, d, st, current, used, actions, &mut pending);
let filter = egui::ComboBox::from_id_salt("textstyle_list_filter")
.selected_text(if st.in_use_only { crate::tl!("Styles in use") } else { crate::tl!("All styles") })
.show_ui(ui, |ui| {
// A choice made with Enter or Space closes the list, as a click does.
for (value, label) in [(false, crate::tl!("All styles")), (true, crate::tl!("Styles in use"))] {
if ui.selectable_value(&mut st.in_use_only, value, label).clicked() {
ui.close();
}
}
});
// Named by the heading over it: its own text is the answer it shows.
let filter = filter.response.labelled_by(styles.id);
// The dialog opens on the chosen style, so a keyboard user starts there rather than in
// the document behind it; the filter takes the focus when it hides every style.
if st.take_focus {
focus_target.unwrap_or(filter).request_focus();
st.take_focus = false;
}
ui.add_space(6.0);
ui.label(RichText::new(crate::tl!("Preview")).strong());
preview(ui, d, &v, vec2(200.0, 70.0));
});
ui.add_space(12.0);
// The font, size and effects.
ui.vertical(|ui| {
ui.set_width(330.0);
font_group(ui, st, &mut v, fonts);
ui.add_space(6.0);
size_group(ui, d, &mut v, st.doc_uid, &mut st.bad_input);
ui.add_space(6.0);
effects_group(ui, &mut v, st.doc_uid, &mut st.bad_input);
if let Some(why) = &st.bad_input {
// The field went back to its value: say why. Focus stays in the field's row, so
// a screen reader is told through a live region.
let shown = ui.label(RichText::new(why.as_str()).color(t.warn));
ui.ctx().accesskit_node_builder(shown.id, |node| node.set_live(egui::accesskit::Live::Polite));
}
});
// The buttons.
ui.vertical(|ui| {
let w = vec2(110.0, 22.0);
if ui.add_enabled(!st.selected.eq_ignore_ascii_case(current), egui::Button::new(crate::tl!("Set Current")).min_size(w)).clicked() {
pending = Some(After::SetCurrent);
}
if ui.add(egui::Button::new(crate::tl!("New...")).min_size(w)).clicked() {
pending = Some(After::New);
}
// The list's context menu has Rename for the pointer; this is the way by the keyboard.
if ui.add_enabled(!st.selected.eq_ignore_ascii_case("Standard"), egui::Button::new(crate::tl!("Rename")).min_size(w)).clicked() {
st.renaming = Some((st.selected.clone(), st.selected.clone()));
st.rename_focus = true;
}
if ui.add_enabled(deletable(&st.selected, current, used), egui::Button::new(crate::tl!("Delete")).min_size(w)).clicked() {
actions.push(("style.delete", json!({ "name": st.selected })));
deleted = true;
}
});
});
// An edit made this frame, or none when it is back to the saved style (kept as it was when
// another style was chosen or a question is waiting).
if deleted {
st.edit = None;
st.take_focus = true;
} else if st.selected == before && st.confirm.is_none() && st.new_name.is_none() {
// Measured from the style as the first edit found it, so that Apply sends what changed.
let unchanged = if st.edit.is_some() { v == st.base } else { v == *saved };
if unchanged {
st.edit = None;
} else {
if st.edit.is_none() {
st.base = saved.clone();
}
st.edit = Some(v);
}
}
if let Some(after) = pending {
request(d, st, after, actions, open);
}
ui.separator();
ui.horizontal(|ui| {
if ui.add_enabled(st.edit.is_some(), egui::Button::new(crate::tl!("Apply"))).clicked()
&& let Some(e) = st.edit.take()
{
actions.push(("style", changed_params(&saved.name, &st.base, &e)));
st.bad_input = None;
// Apply disables itself: the focus goes to the styles, not nowhere.
st.take_focus = true;
}
if ui.button(crate::tl!("Close")).clicked() {
request(d, st, After::Close, actions, open);
}
});
}
fn style_list(
ui: &mut egui::Ui,
d: &Drawing,
st: &mut State,
current: &str,
used: &[String],
actions: &mut Vec<(&'static str, Value)>,
pending: &mut Option<After>,
) -> Option<egui::Response> {
let mut chosen = None;
let mut first = None;
egui::Frame::group(ui.style()).show(ui, |ui| {
egui::ScrollArea::vertical().id_salt("textstyle_list").max_height(170.0).auto_shrink([false, true]).show(ui, |ui| {
for s in &d.text_styles {
let is_current = s.name.eq_ignore_ascii_case(current);
if st.in_use_only && !is_current && !used.iter().any(|n| n.eq_ignore_ascii_case(&s.name)) {
continue;
}
ui.horizontal(|ui| {
// Annotative styles are marked, as AutoCAD marks them.
let (r, _) = ui.allocate_exact_size(vec2(14.0, 14.0), egui::Sense::hover());
if s.annotative {
icons::paint(ui.painter(), r, Icon::Annotative, false);
}
let mut label = RichText::new(&s.name);
if is_current {
label = label.strong();
}
let resp = ui.selectable_label(st.selected == s.name, label);
// The painted mark is also in the name, which starts with the visible style name.
let resp = if s.annotative { resp.accessible_name(crate::tf!("{style} (annotative)", style = s.name)) } else { resp };
if st.selected == s.name {
chosen = Some(resp.clone());
}
first.get_or_insert_with(|| resp.clone());
if resp.clicked() && st.selected != s.name {
*pending = Some(After::Select(s.name.clone()));
}
resp.context_menu(|ui| {
if ui.add_enabled(!is_current, egui::Button::new(crate::tl!("Set Current"))).clicked() {
actions.push(("style.current", json!({ "name": s.name })));
ui.close();
}
if ui.add_enabled(!s.name.eq_ignore_ascii_case("Standard"), egui::Button::new(crate::tl!("Rename"))).clicked() {
st.renaming = Some((s.name.clone(), s.name.clone()));
ui.close();
}
if ui.add_enabled(deletable(&s.name, current, used), egui::Button::new(crate::tl!("Delete"))).clicked() {
actions.push(("style.delete", json!({ "name": s.name })));
// The row goes: the focus goes to the styles, not nowhere.
st.take_focus = true;
ui.close();
}
});
});
}
});
});
if let Some((from, to)) = &mut st.renaming {
let from = from.clone();
let mut done = false;
ui.horizontal(|ui| {
let r = ui.add(egui::TextEdit::singleline(to).desired_width(120.0)).accessible_name(crate::tl!("Name"));
if st.rename_focus {
r.request_focus();
st.rename_focus = false;
}
let name = to.trim().to_string();
// Only a name the rename takes: a refused one would leave the selection on no style
// (and drop the edits waiting for Apply).
let usable = !bad_name(&name) && d.text_style(&name).is_none_or(|t| t.name.eq_ignore_ascii_case(&from));
let enter = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
if ui.add_enabled(usable, egui::Button::new(crate::tl!("OK"))).clicked() || enter && usable {
if name != from {
actions.push(("style.rename", json!({ "from": from, "to": name })));
if st.selected == from {
// Edits waiting for Apply belong to the style under its new name.
if let Some(e) = &mut st.edit {
e.name.clone_from(&name);
st.base.name.clone_from(&name);
}
st.selected = name;
}
}
done = true;
}
});
if done {
st.renaming = None;
st.take_focus = true;
}
}
// Where the dialog puts the focus: the chosen style, or the first one shown when the filter
// hides the chosen one.
chosen.or(first)
}
fn heading(ui: &mut egui::Ui, text: &str) {
ui.label(RichText::new(text).strong());
}
fn font_group(ui: &mut egui::Ui, st: &mut State, v: &mut TextStyle, fonts: &[FontEntry]) {
heading(ui, crate::tl!("Font"));
let face = face_of(&v.font, fonts).cloned();
let mut families: Vec<&str> = Vec::new();
for e in fonts {
if families.last() != Some(&e.family.as_str()) {
families.push(&e.family);
}
}
egui::Grid::new("textstyle_font").num_columns(2).spacing(vec2(10.0, 6.0)).show(ui, |ui| {
let font_label = ui.label(crate::tl!("Font Name"));
let shown = match &face {
Some(f) => f.family.clone(),
None if is_builtin(&v.font) => BUILTIN_FONT.to_string(),
None => crate::tf!("{font} (not installed)", font = v.font),
};
let font_name = egui::ComboBox::from_id_salt("textstyle_font_name")
.selected_text(shown)
.width(220.0)
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
.show_ui(ui, |ui| {
ui.add(egui::TextEdit::singleline(&mut st.font_filter).hint_text(crate::tl!("Search fonts")).desired_width(200.0))
.accessible_name(crate::tl!("Search fonts"));
let filter = st.font_filter.trim().to_lowercase();
egui::ScrollArea::vertical().id_salt("textstyle_font_list").max_height(280.0).show(ui, |ui| {
if (filter.is_empty() || BUILTIN_FONT.to_lowercase().contains(&filter))
&& ui.selectable_label(is_builtin(&v.font), BUILTIN_FONT).clicked()
{
v.font = BUILTIN_FONT.to_string();
ui.close();
}
for fam in families.iter().filter(|f| filter.is_empty() || f.to_lowercase().contains(&filter)) {
if ui.selectable_label(face.as_ref().is_some_and(|f| f.family == *fam), *fam).clicked() {
// The same style in the new family when it has one, else Regular.
let want = face.as_ref().map_or("Regular", |f| f.style.as_str());
let in_family = || fonts.iter().filter(|e| e.family == *fam);
let pick = in_family()
.find(|e| e.style.eq_ignore_ascii_case(want))
.or_else(|| in_family().find(|e| e.style.eq_ignore_ascii_case("Regular")))
.or_else(|| in_family().next());
if let Some(p) = pick {
v.font = p.file.clone();
}
ui.close();
}
}
});
});
font_name.response.labelled_by(font_label.id);
ui.end_row();
let style_label = ui.label(crate::tl!("Font Style"));
ui.label_inputs_by(style_label.id, |ui| match &face {
Some(f) => {
egui::ComboBox::from_id_salt("textstyle_font_style").selected_text(&f.style).width(220.0).show_ui(ui, |ui| {
for e in fonts.iter().filter(|e| e.family == f.family) {
if ui.selectable_label(e.style == f.style, &e.style).clicked() {
v.font = e.file.clone();
ui.close();
}
}
});
}
None => {
ui.add_enabled_ui(false, |ui| {
egui::ComboBox::from_id_salt("textstyle_font_style_off").selected_text(crate::tl!("Regular")).width(220.0).show_ui(ui, |_| {});
});
}
});
ui.end_row();
});
// A big font extends an SHX font with Asian characters.
let shx = face.is_none() && cadcraft_fonts::is_shx_name(&v.font);
let mut use_big = shx && (!v.big_font.is_empty() || st.big_font_on);
if ui.add_enabled(shx, egui::Checkbox::new(&mut use_big, crate::tl!("Use Big Font"))).changed() {
st.big_font_on = use_big;
if !use_big {
v.big_font.clear();
}
}
if use_big {
ui.horizontal(|ui| {
let caption = ui.label(crate::tl!("Big Font"));
ui.add(egui::TextEdit::singleline(&mut v.big_font).desired_width(160.0)).labelled_by(caption.id);
});
}
}
/// A number field that commits what the user entered when `accept` takes it. An entry it refuses
/// leaves the value as it was and sets `note` to `refused`, which the dialog shows; an accepted
/// one clears the note.
fn checked_field<T>(
ui: &mut egui::Ui,
id: egui::Id,
shown: &str,
label: egui::Id,
note: &mut Option<String>,
accept: impl FnOnce(&str) -> Option<T>,
refused: impl FnOnce() -> String,
) -> Option<T> {
let entered = expr_field(ui, id, shown, Some(label))?;
let value = accept(&entered);
*note = if value.is_some() { None } else { Some(refused()) };
value
}
fn size_group(ui: &mut egui::Ui, d: &Drawing, v: &mut TextStyle, doc_uid: u64, note: &mut Option<String>) {
heading(ui, crate::tl!("Size"));
ui.checkbox(&mut v.annotative, crate::tl!("Annotative"));
ui.add_enabled(false, egui::Checkbox::new(&mut false, crate::tl!("Match text orientation to layout")))
.on_disabled_hover_text(crate::tl!("Not available yet: CADCraft doesn't keep this setting."));
let (lu, lp) = (d.header.i64("LUNITS", 2), d.header.i64("LUPREC", 4));
ui.horizontal(|ui| {
let label = ui.label(if v.annotative { crate::tl!("Paper Text Height") } else { crate::tl!("Height") });
let shown = cadcraft_engine::units::format_distance(v.height, lu, lp);
let id = egui::Id::unique(("textstyle_height", doc_uid, &v.name));
let accept = |t: &str| cadcraft_engine::units::parse_distance(t).filter(|h| h.is_finite() && *h >= 0.0);
if let Some(h) = checked_field(ui, id, &shown, label.id, note, accept, || crate::tl!("The height must be a number, 0 or more.").to_string()) {
v.height = h;
}
})
.response
.on_hover_text(crate::tl!("0 asks for the height each time text is placed; a fixed height is used for all text in the style."));
}
/// A number as a field shows it: up to four decimals, without trailing zeros.
fn trimmed(v: f64) -> String {
let s = format!("{v:.4}");
let s = s.trim_end_matches('0').trim_end_matches('.');
if s == "-0" { "0".into() } else { s.to_string() }
}
fn effects_group(ui: &mut egui::Ui, v: &mut TextStyle, doc_uid: u64, note: &mut Option<String>) {
heading(ui, crate::tl!("Effects"));
egui::Grid::new("textstyle_effects").num_columns(2).spacing(vec2(16.0, 6.0)).show(ui, |ui| {
ui.checkbox(&mut v.upside_down, crate::tl!("Upside down"));
ui.horizontal(|ui| {
let label = ui.label(crate::tl!("Width Factor"));
let id = egui::Id::unique(("textstyle_width", doc_uid, &v.name));
let accept = |t: &str| t.trim().parse::<f64>().ok().filter(|w| w.is_finite() && *w > 0.0 && *w <= 100.0);
let why = || crate::tl!("The width factor must be above 0 and at most 100.").to_string();
if let Some(w) = checked_field(ui, id, &trimmed(v.width_factor), label.id, note, accept, why) {
v.width_factor = w;
}
});
ui.end_row();
ui.checkbox(&mut v.backwards, crate::tl!("Backwards"));
ui.horizontal(|ui| {
let label = ui.label(crate::tl!("Oblique Angle"));
let id = egui::Id::unique(("textstyle_oblique", doc_uid, &v.name));
let accept = |t: &str| t.trim().parse::<f64>().ok().filter(|a| a.is_finite() && a.abs() <= 85.0);
let why = || crate::tl!("The oblique angle must be between -85 and 85 degrees.").to_string();
if let Some(a) = checked_field(ui, id, &trimmed(v.oblique.to_degrees()), label.id, note, accept, why) {
v.oblique = a.to_radians();
}
});
ui.end_row();
let mut vertical = v.vertical;
ui.add_enabled(false, egui::Checkbox::new(&mut vertical, crate::tl!("Vertical")))
.on_disabled_hover_text(crate::tl!("Vertical text isn't available yet."));
ui.end_row();
});
}
/// "AaBb123" set in `style`.
fn preview(ui: &mut egui::Ui, d: &Drawing, style: &TextStyle, size: egui::Vec2) {
let (w, h) = (size.x.max(16.0) as u32, size.y.max(16.0) as u32);
let mut hasher = std::hash::DefaultHasher::new();
serde_json::to_string(style).unwrap_or_default().hash(&mut hasher);
// The drawing area's color, as the theme and the user's model background give it.
let bg = Tokens::get().canvas;
(w, h, bg.to_array()).hash(&mut hasher);
let key = hasher.finish();
let id = egui::Id::unique(("textstyle_preview", w, h));
let cached = ui.data(|m| m.get_temp::<(u64, egui::TextureHandle)>(id)).filter(|(k, _)| *k == key).map(|(_, t)| t);
let tex = match cached {
Some(t) => Some(t),
None => sample(d, style, w, h, bg).map(|img| {
let t = ui.ctx().load_texture("textstyle_preview", img, egui::TextureOptions::LINEAR);
ui.data_mut(|m| m.insert_temp(id, (key, t.clone())));
t
}),
};
match tex {
Some(t) => {
// A drawn surface: named by the heading over it.
ui.image((t.id(), size)).accessible_name(crate::tl!("Preview"));
}
None => {
ui.allocate_space(size);
}
}
}
fn sample(d: &Drawing, style: &TextStyle, w: u32, h: u32, bg: egui::Color32) -> Option<egui::ColorImage> {
let mut s = cadcraft_engine::Session::new();
{
let doc = s.doc_mut().ok()?;
doc.text_styles = vec![TextStyle { name: "Preview".into(), ..style.clone() }].into();
doc.linetypes.clone_from(&d.linetypes);
let text = Text {
insert: Default::default(),
align_pt: None,
height: 1.0,
value: "AaBb123".into(),
rotation: 0.0,
width_factor: style.width_factor,
oblique: style.oblique,
style: "Preview".into(),
halign: Default::default(),
valign: Default::default(),
backwards: style.backwards,
upside_down: style.upside_down,
};
doc.add(&Space::Model, Common::default(), EntityKind::Text(text)).ok()?;
}
let doc = s.doc().ok()?;
let list = cadcraft_engine::render::build(doc, &Space::Model, &cadcraft_engine::render::Options::default());
let view = cadcraft_engine::render::raster::View::fit(&list.bounds, w, h, 0.12);
let background = cadcraft_color::Rgb(bg.r(), bg.g(), bg.b());
let png = cadcraft_engine::render::raster::render_png(
&list,
&view,
&cadcraft_engine::render::raster::RasterOptions { background, ..Default::default() },
)?;
let img = image::load_from_memory(&png).ok()?.to_rgba8();
Some(egui::ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], img.as_raw()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_font_named_without_its_extension_is_found_in_any_case() {
let fonts = [FontEntry { family: "CADCraft Test Narrow".into(), style: "Regular".into(), file: "CADCRAFT-TEST-NARROW.TTF".into() }];
for name in ["cadcraft-test-narrow", "CADCRAFT-TEST-NARROW", "cadcraft-test-narrow.ttf", "CADCraft Test Narrow"] {
assert_eq!(face_of(name, &fonts), fonts.first(), "{name}");
}
assert!(face_of("cadcraft-test", &fonts).is_none());
assert!(face_of("cadcraft-test-narrow.SHX", &fonts).is_none());
}
}
+46 -9
View File
@@ -74,6 +74,8 @@ pub const OPEN_RECENT: &str = "Open Recent";
pub const CLEAR_RECENT: &str = "Clear Recent Files";
const RECENT_ITEM: &str = "ui.recent.";
pub const RECENT_CLEAR: &str = "ui.recent.clear";
/// Open a resource from the registered provider through the ordinary application command route.
pub const PROVIDER_RECENT_OPEN: &str = "ui.provider.open";
/// UI-only commands: (id, label, menu path, shortcut).
pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
@@ -83,6 +85,7 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
("ui.dock", "Arrange Panel", &[], None),
("ui.dock.reset", "Reset Panel Layout", &["Window", "Reset Panel Layout"], None),
("ui.open", "Open...", &[], Some("Cmd+O")),
(PROVIDER_RECENT_OPEN, "Open Provider File", &[], None),
("ui.newtemplate", "New from Template...", &["File", "New from Template..."], None),
("ui.saveas", "Save As...", &[], None),
("ui.sample", "Open Sample Drawing", &["Help", "Open Sample Drawing"], None),
@@ -211,6 +214,19 @@ fn run_recent_file_command(app: &mut CadApp, id: &str) -> Option<Result<Value, S
None
}
fn run_provider_file_command(app: &mut CadApp, id: &str, params: &Value, no_path: bool) -> Option<Result<Value, String>> {
let result = match id {
PROVIDER_RECENT_OPEN => crate::file_provider_app::open_recent(app, params),
"ui.saveas" | "saveas" if no_path && app.file_providers.enabled() => match suggested_save_format(params, crate::SaveFormat::Dxf) {
Ok(crate::SaveFormat::Dxf) => crate::file_provider_app::save(app, true),
Ok(crate::SaveFormat::Dwg) => return None,
Err(error) => Err(error),
},
_ => return None,
};
Some(result)
}
fn run_preference_command(app: &mut CadApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
let r = match id {
"ui.theme.system" | "ui.theme.light" | "ui.theme.dark" => {
@@ -387,12 +403,31 @@ fn should_pick_file_path(id: &str, params: &Value) -> bool {
/// content asks first. `None` lets the engine save. JSON calls carry params and never get here;
/// they report the loss in their result instead.
fn user_qsave(app: &mut CadApp) -> Option<Result<Value, String>> {
if app.file_providers.enabled() {
return Some(crate::file_provider_app::save(app, false));
}
if app.session.state().is_ok_and(|s| s.path.is_none()) {
return run_ui_command(app, "ui.saveas", &Value::Null);
}
app.hold_lossy_save().then_some(Ok(Value::Null))
}
fn run_settings_and_close_command(app: &mut CadApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
if let Some(result) = run_preference_command(app, id, params) {
return Some(result);
}
if let Some(result) = run_ui_toggle_command(app, id, params) {
return Some(result);
}
if let Some(result) = run_language_command(app, id, params) {
return Some(result);
}
if let Some(result) = run_close_command(app, id, params) {
return Some(result);
}
None
}
fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
if let Some(result) = route_ui_subsystems(app, id, params) {
return Some(result);
@@ -404,16 +439,10 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option<Re
if let Some(result) = run_recent_file_command(app, id) {
return Some(result);
}
if let Some(result) = run_preference_command(app, id, params) {
if let Some(result) = run_settings_and_close_command(app, id, params) {
return Some(result);
}
if let Some(result) = run_ui_toggle_command(app, id, params) {
return Some(result);
}
if let Some(result) = run_language_command(app, id, params) {
return Some(result);
}
if let Some(result) = run_close_command(app, id, params) {
if let Some(result) = run_provider_file_command(app, id, params, no_path) {
return Some(result);
}
// FIND typed, or chosen from Edit ▸ Find..., opens the window; a JSON call carries `find`
@@ -807,8 +836,16 @@ pub fn menu_bar(app: &mut CadApp, ui: &mut egui::Ui) {
// Titles first, so a hovered title can take over before any menu is drawn.
let titles: Vec<egui::Response> = tree.iter().map(|(name, _)| ui.add(egui::Button::new(crate::i18n::menu(name)))).collect();
switch_on_hover(ui.ctx(), &titles);
for ((_, entries), title) in tree.iter().zip(&titles) {
for ((menu, entries), title) in tree.iter().zip(&titles) {
egui::Popup::menu(title).show(|ui| {
if menu == "File" && app.file_providers.enabled() {
let resource = ui.menu_button("Open Recent — file provider", |ui| app.file_providers.recent_ui(ui)).inner.flatten();
if let Some(resource) = resource
&& app.run(PROVIDER_RECENT_OPEN, json!({"resource":resource})).is_ok()
{
ui.close();
}
}
for e in entries {
entry_ui(ui, e, &mut clicked);
}
+2 -2
View File
@@ -1349,7 +1349,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) {
EntityKind::Hatch(hh) => {
prop_row(ui, "Pattern", |ui| {
ui.menu_button(hh.pattern.clone(), |ui| {
if let Some(name) = patterns::menu(ui, &hh.pattern) {
if let Some(name) = patterns::menu(ui, &hh.pattern, d) {
set = Some(json!({ "handles": ids, "pattern": name }));
ui.close();
}
@@ -1599,7 +1599,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) {
let pattern = shared("hatch.pattern", &|k| if let EntityKind::Hatch(h) = k { Some(h.pattern.clone()) } else { None });
prop_row(ui, "Pattern", |ui| {
ui.menu_button(pattern.clone(), |ui| {
if let Some(name) = patterns::menu(ui, &pattern) {
if let Some(name) = patterns::menu(ui, &pattern, d) {
set = Some(json!({ "handles": ids, "pattern": name }));
ui.close();
}
+62 -18
View File
@@ -6,7 +6,7 @@ use std::cell::RefCell;
use std::sync::Arc;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::{Input, PatternChoice, Picker, pattern_choices};
use cadcraft_engine::{Input, PatternChoice, Picker, pattern_choices_in};
use egui::{Align2, Rect, Sense, Stroke, pos2, vec2};
use crate::CadApp;
@@ -29,8 +29,8 @@ struct Swatch {
solid: bool,
}
/// The patterns' names and line family counts, and their swatches.
type Swatches = (Vec<(String, usize)>, Arc<Vec<Swatch>>);
/// The complete definitions used to build the cached swatches.
type Swatches = (Vec<PatternChoice>, Arc<Vec<Swatch>>);
thread_local! {
static SWATCHES: RefCell<Swatches> = RefCell::new((Vec::new(), Arc::new(Vec::new())));
@@ -38,27 +38,26 @@ thread_local! {
/// The swatches of the patterns offered now, made again only when the list changes (a `.pat`
/// file loaded more patterns).
fn swatches() -> Arc<Vec<Swatch>> {
let choices = pattern_choices();
let key: Vec<(String, usize)> = choices.iter().map(|c| (c.name.clone(), c.lines.len())).collect();
fn swatches(choices: &[PatternChoice]) -> Arc<Vec<Swatch>> {
SWATCHES.with(|cell| {
let mut cache = cell.borrow_mut();
if cache.0 != key {
*cache = (key, Arc::new(choices.into_iter().map(swatch).collect()));
if cache.0 != choices {
let previews = choices.iter().map(swatch).collect();
*cache = (choices.to_vec(), Arc::new(previews));
}
cache.1.clone()
})
}
fn swatch(c: PatternChoice) -> Swatch {
fn swatch(c: &PatternChoice) -> Swatch {
let solid = c.lines.is_empty();
Swatch { runs: cadcraft_engine::render::pattern_swatch(&c.lines, 1.0), name: c.name, description: c.description, solid }
Swatch { runs: cadcraft_engine::render::pattern_swatch(&c.lines, 1.0), name: c.name.clone(), description: c.description.clone(), solid }
}
/// Draw one swatch in `r` (the square and the name under it).
fn paint(p: &egui::Painter, r: Rect, s: &Swatch, selected: bool, hovered: bool) {
let t = Tokens::get();
let square = Rect::from_min_size(r.min, vec2(CELL, CELL));
let square = Rect::from_min_size(r.min, vec2(r.width(), r.width()));
p.rect_filled(square, 3.0, t.field);
let inner = square.shrink(3.0);
if s.solid {
@@ -91,18 +90,61 @@ fn paint(p: &egui::Painter, r: Rect, s: &Swatch, selected: bool, hovered: bool)
/// The swatches whose name or description holds `filter`, `current` marked; returns the
/// pattern clicked.
pub fn grid(ui: &mut egui::Ui, current: &str, filter: &str) -> Option<String> {
pub fn grid(ui: &mut egui::Ui, current: &str, filter: &str, choices: &[PatternChoice]) -> Option<String> {
gallery(ui, current, filter, Some(CELL), false, choices)
}
pub(crate) fn manager(ui: &mut egui::Ui, current: &str, choices: &[PatternChoice]) -> Option<String> {
use crate::blocks_palette::View;
let id = ui.make_persistent_id("hatch-gallery-settings");
let (mut view, mut filtering, mut filter): (View, bool, String) = ui.data_mut(|data| data.get_temp(id)).unwrap_or_default();
ui.horizontal(|ui| {
let label = ui.label(crate::tl!("View"));
egui::ComboBox::from_id_salt("hatch-view")
.selected_text(view.label())
.show_ui(ui, |ui| {
for v in View::ALL {
ui.selectable_value(&mut view, v, v.label());
}
})
.response
.labelled_by(label.id);
ui.toggle_value(&mut filtering, crate::tl!("Filter"));
});
if filtering {
ui.add(egui::TextEdit::singleline(&mut filter).hint_text(crate::tl!("Search for pattern")));
}
let chosen = egui::ScrollArea::vertical()
.id_salt("hatch_swatches")
.max_height(220.0)
.show(ui, |ui| gallery(ui, current, if filtering { &filter } else { "" }, view.tile(), view == View::Details, choices))
.inner;
ui.data_mut(|data| data.insert_temp(id, (view, filtering, filter)));
chosen
}
fn gallery(ui: &mut egui::Ui, current: &str, filter: &str, side: Option<f32>, details: bool, choices: &[PatternChoice]) -> Option<String> {
let filter = filter.trim().to_lowercase();
let mut chosen = None;
let row_width = ui.available_width();
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(GAP, GAP);
let shown = swatches();
let shown = swatches(choices);
for s in
shown.iter().filter(|s| filter.is_empty() || s.name.to_lowercase().contains(&filter) || s.description.to_lowercase().contains(&filter))
{
let (r, resp) = ui.allocate_exact_size(vec2(CELL, CELL + LABEL_H), Sense::click());
let Some(side) = side else {
let label = if details { format!("{} {}", s.name, s.description) } else { s.name.clone() };
if ui.add_sized([row_width, LABEL_H + GAP], egui::Button::selectable(s.name.eq_ignore_ascii_case(current), label)).clicked() {
chosen = Some(s.name.clone());
}
continue;
};
let (r, resp) = ui.allocate_exact_size(vec2(side, side + LABEL_H), Sense::click());
let selected = s.name.eq_ignore_ascii_case(current);
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, resp.enabled(), selected, &s.name));
if ui.is_rect_visible(r) {
paint(ui.painter(), r, s, s.name.eq_ignore_ascii_case(current), resp.hovered());
paint(ui.painter(), r, s, selected, resp.hovered() || resp.has_focus());
}
let tip = if s.description.is_empty() { s.name.clone() } else { format!("{}\n{}", s.name, s.description) };
if resp.on_hover_text(tip).clicked() {
@@ -115,9 +157,9 @@ pub fn grid(ui: &mut egui::Ui, current: &str, filter: &str) -> Option<String> {
/// The Properties palette's pattern menu: the swatch grid, scrolling; returns the pattern
/// clicked.
pub fn menu(ui: &mut egui::Ui, current: &str) -> Option<String> {
pub fn menu(ui: &mut egui::Ui, current: &str, d: &cadcraft_doc::Drawing) -> Option<String> {
ui.set_width(MENU_COLUMNS * (CELL + GAP));
egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| grid(ui, current, "")).inner
egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| grid(ui, current, "", &pattern_choices_in(d))).inner
}
/// The picker window while the prompt offers one (HATCH's boundary and pattern prompts,
@@ -139,7 +181,9 @@ pub fn prompt_picker(app: &mut CadApp, ctx: &egui::Context) {
.on_hover_text(crate::tl!("Search for pattern"));
ui.add_space(4.0);
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
chosen = grid(ui, &current, &filter);
if let Ok(d) = app.session.doc() {
chosen = grid(ui, &current, &filter, &pattern_choices_in(d));
}
});
});
ctx.data_mut(|d| d.insert_temp(filter_id, filter));
+1
View File
@@ -56,6 +56,7 @@ mod style_dialogs;
mod system_cursor;
mod text_double_click;
mod text_edit_in_place;
mod textstyle_dialog;
mod toolsets_gear;
mod toolsets_parametric;
mod typed_open;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,398 @@
//! Real CadApp command/format boundaries. This integration binary owns its process-global
//! format hooks: every hook delegates to cadcraft-io, and no writer reports synthetic success.
#![cfg(not(target_arch = "wasm32"))]
use cadcraft_engine::cmd::file::{IoHooks, SaveAs, set_io, set_write_as};
use cadcraft_engine::doc::geom::Vec3;
use cadcraft_engine::doc::{Block, Drawing, Entity, EntityKind, Image, Layout, Line};
use cadcraft_engine::{DocState, Session};
use cadcraft_ui_egui::file_providers::{Event, Resource};
use cadcraft_ui_egui::{CadApp, Services};
use serde_json::{Value, json};
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
#[path = "support/temp_dir.rs"]
mod temp_dir;
use temp_dir::TempDir;
const EXTERNAL_REFERENCE_ERROR: &str =
"DXF references external images or drawings; make a self-contained drawing before provider save (external files are not uploaded)";
thread_local! {
// Hooks run synchronously on the command's thread. Parallel cases cannot consume one
// another's observations; all cases install exactly the same immutable OnceLock hooks.
static WRITES: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}
fn real_read(bytes: &[u8], name: &str) -> Result<Drawing, String> {
cadcraft_io::read(bytes, name).map_err(|error| error.to_string())
}
fn real_write(drawing: &Drawing, name: &str) -> Result<Vec<u8>, String> {
WRITES.with(|writes| writes.borrow_mut().push(name.into()));
cadcraft_io::write(drawing, name).map_err(|error| error.to_string())
}
fn real_write_as(drawing: &Drawing, name: &str, options: &SaveAs) -> Result<Vec<u8>, String> {
WRITES.with(|writes| writes.borrow_mut().push(name.into()));
let options = cadcraft_io::SaveOptions { version: options.version, binary: options.binary };
cadcraft_io::write_with(drawing, name, &options).map_err(|error| error.to_string())
}
fn writes() -> Vec<String> {
WRITES.with(|writes| writes.borrow().clone())
}
/// Observe the actual picker invocation without replacing either the encoder or disk writer.
fn picker(path: Option<String>) -> (Services, Rc<RefCell<Vec<String>>>) {
let names = Rc::new(RefCell::new(Vec::new()));
let seen = names.clone();
let services = Services {
pick_save: Some(Box::new(move |name| {
seen.borrow_mut().push(name.into());
path.clone()
})),
..Services::default()
};
(services, names)
}
fn app_with_real_formats(services: Services) -> Result<CadApp, String> {
set_io(IoHooks { read: real_read, write: real_write, plot: None });
set_write_as(real_write_as);
WRITES.with(|writes| writes.borrow_mut().clear());
let mut app = CadApp::new(Session::new(), services);
app.run("line", json!({"points":[[0,0],[10,20]]}))?;
assert!(app.session.state().map_err(|error| error.to_string())?.is_dirty());
app.ui.recent_files = vec!["existing-local-history.dxf".into()];
Ok(app)
}
fn logic(app: &mut CadApp) {
let ctx = egui::Context::default();
let mut output = ctx.run_pass(egui::RawInput::default(), |ctx| app.logic(ctx));
output.textures_delta.clear();
}
fn connect(app: &mut CadApp) -> Result<(), String> {
let host = &app.file_providers;
host.set_session("0123456789abcdef0123456789abcdef".into())?;
let connection = host.connect("boundary-provider".into(), "Boundary storage".into(), "boundary-account".into())?;
host.set_resources(
&connection,
vec![Resource { id: "existing-provider-resource".into(), name: "Existing.dxf".into(), updated_at: "before".into() }],
)?;
logic(app);
assert!(app.file_providers.take_events().is_empty());
Ok(())
}
struct Before {
document: DocState,
active: usize,
epoch: u64,
document_count: usize,
recents: Vec<String>,
provider: Value,
log_len: usize,
}
fn before(app: &CadApp) -> Result<Before, String> {
Ok(Before {
document: app.session.state().map_err(|error| error.to_string())?.clone(),
active: app.session.active,
epoch: app.session.doc_epoch,
document_count: app.session.docs.len(),
recents: app.ui.recent_files.clone(),
provider: app.file_providers.snapshot(),
log_len: app.session.log.len(),
})
}
/// A refusal or an unacknowledged capture must not change the drawing or its saved checkpoint.
fn assert_document_unchanged(app: &CadApp, before: &Before) -> Result<(), String> {
let after = app.session.state().map_err(|error| error.to_string())?;
let original = &before.document;
assert_eq!((app.session.active, app.session.doc_epoch, app.session.docs.len()), (before.active, before.epoch, before.document_count));
assert_eq!((after.uid, after.revision), (original.uid, original.revision));
assert!(Arc::ptr_eq(&after.doc, &original.doc));
assert!(Arc::ptr_eq(&after.saved, &original.saved));
assert_eq!((&after.path, &after.title, &after.space), (&original.path, &original.title, &original.space));
assert_eq!((&after.selection, &after.previous_selection), (&original.selection, &original.previous_selection));
assert_eq!((after.undo.len(), after.redo.len(), after.is_dirty()), (original.undo.len(), original.redo.len(), original.is_dirty()));
assert_eq!(app.ui.recent_files, before.recents);
Ok(())
}
#[derive(Clone, Copy, Debug)]
enum ImageSpace {
Model,
Layout,
Block,
}
fn insert_external_image(app: &mut CadApp, space: ImageSpace) -> Result<(), String> {
let state = app.session.state_mut().map_err(|error| error.to_string())?;
let drawing = Arc::make_mut(&mut state.doc);
let handle = drawing.new_handle();
let image = Entity::new(handle, EntityKind::Image(Image { path: "synthetic-external-image.png".into(), ..Image::default() }));
match space {
ImageSpace::Model => drawing.model.push(image),
ImageSpace::Layout => {
let mut layout = Layout::new("External image layout", 3);
layout.entities.push(image);
drawing.layouts.push(layout);
}
ImageSpace::Block => {
let mut block = Block::new("ExternalImageBlock");
block.entities.push(image);
drawing.blocks.insert(block.name.clone(), Arc::new(block));
}
}
Ok(())
}
fn insert_external_xref(app: &mut CadApp) -> Result<(), String> {
let state = app.session.state_mut().map_err(|error| error.to_string())?;
let drawing = Arc::make_mut(&mut state.doc);
let mut block = Block::new("ExternalDrawing");
block.xref_path = Some("synthetic-external-drawing.dxf".into());
drawing.blocks.insert(block.name.clone(), Arc::new(block));
Ok(())
}
fn assert_refused_before_encoding(app: &mut CadApp, command: &str) -> Result<(), String> {
// Refresh the public document snapshot after the synthetic fixture was installed.
logic(app);
let before = before(app)?;
let error = app.run(command, Value::Null).err().ok_or("external references unexpectedly admitted a provider capture")?;
assert_eq!(error, EXTERNAL_REFERENCE_ERROR);
assert!(writes().is_empty(), "the app must refuse external references before calling its real encoder");
assert_document_unchanged(app, &before)?;
assert!(!app.file_providers.busy());
assert!(!app.file_providers.pending_for(before.document.uid));
assert!(app.file_providers.take_events().is_empty(), "no provider chooser, write or ACK may be published");
assert_eq!(app.file_providers.snapshot(), before.provider);
assert_eq!(app.status.as_ref().map(|(text, _)| text.as_str()), Some(EXTERNAL_REFERENCE_ERROR));
assert_eq!(app.session.log.len(), before.log_len + 1);
assert_eq!(app.session.log.last(), Some(&error));
Ok(())
}
#[test]
fn provider_save_and_save_as_refuse_external_images_in_model_layout_and_blocks() -> Result<(), String> {
for space in [ImageSpace::Model, ImageSpace::Layout, ImageSpace::Block] {
for command in ["qsave", "ui.saveas"] {
let (services, picked) = picker(None);
let mut app = app_with_real_formats(services)?;
connect(&mut app)?;
insert_external_image(&mut app, space)?;
assert_refused_before_encoding(&mut app, command)?;
assert!(picked.borrow().is_empty(), "{space:?}/{command} must not fall back to a local picker");
}
}
Ok(())
}
#[test]
fn provider_save_and_save_as_refuse_external_xrefs_before_encoding_or_admission() -> Result<(), String> {
for command in ["qsave", "ui.saveas"] {
let (services, picked) = picker(None);
let mut app = app_with_real_formats(services)?;
connect(&mut app)?;
insert_external_xref(&mut app)?;
assert_refused_before_encoding(&mut app, command)?;
assert!(picked.borrow().is_empty());
}
Ok(())
}
#[test]
fn provider_open_refuses_external_images_and_xrefs_before_native_path_loading() -> Result<(), String> {
for image_space in [Some(ImageSpace::Model), Some(ImageSpace::Layout), Some(ImageSpace::Block), None] {
let mut incoming = app_with_real_formats(Services::default())?;
if let Some(space) = image_space {
insert_external_image(&mut incoming, space)?;
} else {
insert_external_xref(&mut incoming)?;
}
let bytes =
cadcraft_io::write(incoming.session.doc().map_err(|error| error.to_string())?, "External.dxf").map_err(|error| error.to_string())?;
let mut app = app_with_real_formats(Services::default())?;
connect(&mut app)?;
let before = before(&app)?;
let value = app.run("ui.provider.open", json!({"resource":"existing-provider-resource"}))?;
let request = value["requestId"].as_str().ok_or("provider Open omitted its request ID")?;
only_event(&app, "openRequested", request)?;
app.file_providers.open(request.into(), "External.dxf".into(), bytes)?;
logic(&mut app);
assert_document_unchanged(&app, &before)?;
assert!(app.file_providers.bound_document("existing-provider-resource").is_none());
let terminal = only_event(&app, "openFailed", request)?;
assert_eq!(terminal.metadata["resourceId"], "existing-provider-resource");
assert_eq!(
terminal.metadata["error"],
"DXF references external images or drawings; open a self-contained drawing with the file provider (external files are not loaded)"
);
assert!(!app.file_providers.busy());
assert!(app.file_providers.request_open("existing-provider-resource").is_ok(), "a refused Open must release its owner for retry");
}
Ok(())
}
fn only_event(app: &CadApp, event_type: &str, request: &str) -> Result<Event, String> {
let events = app.file_providers.take_events();
assert_eq!(events.len(), 1, "expected exactly one {event_type}");
let event = events.into_iter().next().ok_or("missing provider event")?;
assert_eq!(event.metadata["type"], event_type);
assert_eq!(event.metadata["requestId"], request);
Ok(event)
}
/// Check actual native decoder output rather than accepting arbitrary nonempty writer bytes.
fn assert_native_line(bytes: &[u8], name: &str) -> Result<(), String> {
let drawing = real_read(bytes, name)?;
assert_eq!(drawing.model.len(), 1);
let entity = drawing.model.iter().next().ok_or("native format lost the synthetic line")?;
assert_eq!(entity.kind, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 20.0, 0.0) }));
Ok(())
}
fn provider_positive_control(command: &str, intent: &str) -> Result<(), String> {
let (services, picked) = picker(None);
let mut app = app_with_real_formats(services)?;
connect(&mut app)?;
let before = before(&app)?;
let value = app.run(command, Value::Null)?;
assert_eq!(value["pending"], "fileProvider");
let request = value["requestId"].as_str().ok_or("save command did not return its capture ID")?;
let dialog = only_event(&app, "saveDialog", request)?;
assert_eq!(dialog.metadata["documentId"], before.document.uid.to_string());
assert_eq!(dialog.metadata["revision"], before.document.revision.to_string());
assert_eq!(dialog.metadata["intent"], intent);
let encoded_name = dialog.metadata["filename"].as_str().ok_or("save dialog lost its native filename")?;
assert_eq!(encoded_name, format!("{}.dxf", before.document.title));
assert_eq!(writes(), vec![encoded_name.to_string()]);
assert!(dialog.bytes.is_none());
assert_document_unchanged(&app, &before)?;
app.file_providers.resolve_dialog(request, "provider", "SelfContained.dxf")?;
let save = only_event(&app, "save", request)?;
assert_eq!(save.metadata["destination"], "provider");
assert_eq!(save.metadata["documentId"], before.document.uid.to_string());
assert_eq!(save.metadata["revision"], before.document.revision.to_string());
assert_eq!(save.metadata["filename"], "SelfContained.dxf");
assert_native_line(save.bytes.as_deref().ok_or("provider write omitted its real DXF bytes")?, "SelfContained.dxf")?;
assert_document_unchanged(&app, &before)?;
assert_eq!(app.file_providers.snapshot()["resources"], before.provider["resources"]);
app.file_providers.result(request.into(), "saved".into(), "self-contained-resource".into())?;
assert_document_unchanged(&app, &before)?;
logic(&mut app);
assert_provider_ack(&app, &before, request)?;
assert!(picked.borrow().is_empty());
assert_eq!(writes().len(), 1);
Ok(())
}
fn assert_provider_ack(app: &CadApp, before: &Before, request: &str) -> Result<(), String> {
let state = app.session.state().map_err(|error| error.to_string())?;
assert_eq!((state.uid, state.revision), (before.document.uid, before.document.revision));
assert!(Arc::ptr_eq(&state.doc, &before.document.doc));
assert!(Arc::ptr_eq(&state.saved, &before.document.doc));
assert!(!state.is_dirty());
assert_eq!(state.path, before.document.path);
assert_eq!(app.ui.recent_files, before.recents);
assert_eq!(app.file_providers.bound_document("self-contained-resource"), Some(state.uid));
let terminal = only_event(app, "saved", request)?;
assert_eq!(terminal.metadata["documentId"], state.uid.to_string());
assert_eq!(terminal.metadata["revision"], before.document.revision.to_string());
assert_eq!(terminal.metadata["resourceId"], "self-contained-resource");
assert!(terminal.bytes.is_none());
assert!(!app.file_providers.busy());
assert_eq!(app.file_providers.snapshot()["resources"][0]["name"], "SelfContained.dxf");
Ok(())
}
#[test]
fn self_contained_provider_save_and_save_as_encode_real_dxf_and_wait_for_app_ack() -> Result<(), String> {
for (command, intent) in [("qsave", "save"), ("ui.saveas", "saveAs")] {
provider_positive_control(command, intent)?;
}
Ok(())
}
fn assert_local_save(app: &CadApp, path: &str, value: &Value) -> Result<(), String> {
let bytes = std::fs::read(path).map_err(|error| error.to_string())?;
assert_eq!(value["path"], path);
assert_eq!(value["bytes"].as_u64(), Some(bytes.len() as u64));
assert_native_line(&bytes, path)?;
let state = app.session.state().map_err(|error| error.to_string())?;
assert_eq!(state.path.as_deref(), Some(path));
assert!(Arc::ptr_eq(&state.doc, &state.saved));
assert!(!state.is_dirty());
assert_eq!(writes(), vec![path.to_string()]);
assert!(!app.file_providers.busy());
assert!(!app.file_providers.pending_for(state.uid));
assert!(app.file_providers.take_events().is_empty(), "a local file must not create a provider chooser, write or ACK");
Ok(())
}
#[test]
#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))]
fn provider_connected_explicit_dwg_save_as_uses_the_real_local_format_and_writer() -> Result<(), String> {
// The DWG writer and reader only handle this fixture's own synthetic drawing.
cadcraft_io::dwg_worker::allow_in_process();
let directory = TempDir::new("provider-explicit-local-dwg");
let path = directory.path_str("Explicit local drawing.dwg");
let (services, picked) = picker(None);
let mut app = app_with_real_formats(services)?;
connect(&mut app)?;
let before = before(&app)?;
let value = app.run("saveas", json!({"path":path,"version":2018}))?;
assert_local_save(&app, &path, &value)?;
let bytes = std::fs::read(&path).map_err(|error| error.to_string())?;
assert!(bytes.starts_with(b"AC1032"), "the actual local file must be a 2018 DWG, not renamed DXF");
assert!(picked.borrow().is_empty(), "a programmatic explicit path must not open either chooser");
assert_eq!(app.file_providers.snapshot(), before.provider);
assert_eq!(app.ui.recent_files, before.recents);
assert_eq!(app.session.state().map_err(|error| error.to_string())?.uid, before.document.uid);
Ok(())
}
#[test]
fn provider_save_as_preserves_explicit_format_validation_and_the_local_dwg_picker() -> Result<(), String> {
let (services, picked) = picker(None);
let mut app = app_with_real_formats(services)?;
connect(&mut app)?;
let before = before(&app)?;
assert!(app.run("ui.saveas", json!({"format":"unknown"})).is_err());
assert!(app.run("ui.saveas", json!({"format":42})).is_err());
assert!(picked.borrow().is_empty());
app.run("ui.saveas", json!({"format":"dwg"}))?;
assert_eq!(*picked.borrow(), vec![format!("{}.dwg", before.document.title)]);
assert!(writes().is_empty());
assert!(app.file_providers.take_events().is_empty());
assert_eq!(app.file_providers.snapshot(), before.provider);
assert_document_unchanged(&app, &before)
}
#[test]
fn disabled_provider_save_as_keeps_the_ordinary_picker_and_real_local_dxf_writer() -> Result<(), String> {
let directory = TempDir::new("provider-disabled-local-picker");
let path = directory.path_str("Picked local drawing.dxf");
let (services, picked) = picker(Some(path.clone()));
let mut app = app_with_real_formats(services)?;
assert!(!app.file_providers.connected() && !app.file_providers.enabled());
let before = before(&app)?;
let value = app.run("ui.saveas", Value::Null)?;
assert_local_save(&app, &path, &value)?;
assert_eq!(*picked.borrow(), vec![format!("{}.dxf", before.document.title)]);
assert_eq!(app.file_providers.snapshot(), before.provider);
assert_eq!(app.ui.recent_files, before.recents);
assert!(!app.file_providers.connected() && !app.file_providers.enabled());
Ok(())
}
+69
View File
@@ -136,6 +136,75 @@ fn start_page_lists_recent_files_and_opens_one_on_click() {
assert_eq!(app.ui.recent_files, [plan, section]);
}
/// The same native Start page with the storage capability absent and connected. Optional PNGs
/// use the existing offscreen renderer; no app window, backend, or provider filesystem is made.
#[test]
fn provider_recents_render_separately_from_device_history() {
let directory = std::env::var_os("CRAFT_PROVIDER_UI_FIXTURES").map(std::path::PathBuf::from);
if let Some(path) = &directory {
std::fs::create_dir_all(path).unwrap();
}
for (enabled, provider_count) in [(false, 0), (true, 1), (true, 100)] {
let (_dir, plan, _) = drawings("provider-home");
let mut app = CadApp::new(Session::empty(), Services::default());
app.ui.recent_files = vec![plan];
if enabled {
let host = &app.file_providers;
host.set_session("fixture-session-0123456789abcdef".into()).unwrap();
let connection = host.connect("fixture".into(), "External storage".into(), "fixture-account".into()).unwrap();
host.set_resources(
&connection,
(0..provider_count)
.map(|index| cadcraft_ui_egui::file_providers::Resource {
id: format!("provider-drawing-{index}"),
name: if index == 0 { "Provider drawing.dxf".into() } else { format!("Provider drawing {index}.dxf") },
updated_at: String::new(),
})
.collect(),
)
.unwrap();
}
let mut builder = Harness::builder().with_size(vec2(1280.0, 900.0));
if directory.is_some() {
builder = builder.wgpu();
}
let mut ready = false;
let mut h = builder.build_ui_state(
move |ui, app: &mut CadApp| {
if !ready {
ready = true;
return;
}
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.input_mut().max_texture_side = Some(8192);
h.run_steps(6);
let mut found = Vec::new();
for shape in &h.output().shapes {
texts(&shape.shape, &mut found);
}
assert!(found.iter().any(|(text, _)| text == "plan.dxf"), "{found:?}");
assert_eq!(found.iter().any(|(text, _)| text == "Provider drawing.dxf"), enabled, "{found:?}");
assert_eq!(found.iter().any(|(text, _)| text == "Recent files — External storage"), enabled, "{found:?}");
assert_eq!(found.iter().any(|(text, _)| text == "Recent files on this device"), enabled, "{found:?}");
let mut visible = Vec::new();
for shape in &h.output().shapes {
let mut labels = Vec::new();
texts(&shape.shape, &mut labels);
visible.extend(labels.into_iter().filter(|(_, rect)| shape.clip_rect.contains_rect(*rect)));
}
assert_eq!(visible.iter().any(|(text, _)| text == "Recent files on this device"), enabled, "{visible:?}");
assert!(visible.iter().any(|(text, _)| text == "plan.dxf"), "device history remains visible even when provider files overflow: {visible:?}");
if let Some(path) = directory.as_ref().filter(|_| provider_count <= 1) {
let state = if enabled { "on" } else { "off" };
h.render().unwrap().save(path.join(format!("cadcraft-provider-recents-{state}.png"))).unwrap();
}
}
}
#[test]
fn a_recent_file_that_no_longer_exists_is_dropped_when_opening_it_fails() {
let (_dir, plan, _section) = drawings("missing");
+2 -2
View File
@@ -1,10 +1,10 @@
# Parity checklist
> **Generated:** 2026-11-27 by `cargo xtask parity`. Do not edit by hand.
> **Generated:** 2026-12-01 by `cargo xtask parity`. Do not edit by hand.
Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment.
**Menu breadth: 306 / 491 items (62%)** · 482 registered commands.
**Menu breadth: 306 / 491 items (62%)** · 488 registered commands.
| Menu | Items | Covered | % |
|---|---|---|---|
+185
View File
@@ -0,0 +1,185 @@
# Optional external file providers (web)
The web editor can delegate native project persistence to one **trusted same-origin host**.
The capability is **disabled by default**. Merely loading the editor exposes a protocol object;
it does not enable storage, render provider Recents, change ordinary local saves, or contact a server.
A host must explicitly call registerProvider. No server, account system, login, VM, domain,
filesystem mount or cloud vendor is built into this feature.
## Contract
window.cadcraftFileProviders has protocolVersion 1 and app cadcraft. Events are dispatched on window
as cadcraft-file-provider CustomEvents; detail contains bounded metadata and, on save,
a Uint8Array named bytes. The host subscribes before registering, and can discover an already-ready
editor through the protocol object. The capability is independent of the optional control API.
The application command `ui.provider.open` accepts `{"resource":"resource-id"}` and returns
the queued provider request ID. Home and File-menu provider Recents both dispatch through
`CadApp::run`; rejected reads remain in the status and command history instead of a one-frame
inline label. This command uses the current account's resource list and never opens a local path.
| Method | Arguments / result |
| --- | --- |
| registerProvider | (providerId, label, namespace) -> connectionId. Repeating the exact identity is idempotent. |
| unregisterProvider | No arguments. Refused while an operation is unresolved; clears account resources and bindings. |
| setEnabled | (boolean). Suspends new provider choices/Recents without discarding pending work. |
| setResources | (connectionId, resources). Replace this account's native project list. |
| requestOpen | (resourceId) -> requestId. IDs must occur in the current connection's resource list. |
| openResource | (requestId, filename, Uint8Array). Replies only to a live, single-use open request. |
| cancelOpen | (requestId, error). Empty error means cancellation. |
| resolveSaveDialog | (requestId, destination, filename). destination is provider, device or cancel. |
| saveResult | (requestId, status, resourceId). status is saved, download, failed or cancel. |
| snapshot | Returns provider/namespace/connectionId, enabled, resources, documents and pending state. |
The namespace must identify the authenticated account, not its display name. A new connection ID
and per-page cryptographic request nonce prevent old account/page callbacks from matching new work.
This is correlation and separation of identities, **not authentication**. The host and its backend
must authenticate users, authorize every list/read/write, and scope durable storage by account.
Do not trust a filename, user-supplied account ID, browser page or request ID as an authorization check.
Only the hosting page's own script environment can use this capability; no postMessage listener,
foreign-origin message channel or filesystem authority is added.
Every script executing in the editor page, including third-party analytics, can call registerProvider
and receive saved drawings through provider events. Load only scripts you trust with drawing contents.
The host/backend remains responsible for authenticating users and authorizing each account-scoped operation.
A resource is an object with id, name and optional updatedAt strings. IDs are opaque and never used as
paths. The list is limited to 100 unique resources. Names must be native .dxf filenames, at most
255 UTF-8 bytes, with no path separators or control characters. IDs/namespaces are at most 160 ASCII
characters (letters, numbers, dash, underscore, dot, colon). Labels are at most 100 UTF-8 bytes.
Native captures/read responses are limited to 80 MiB; retained transfer bytes and pending work are bounded.
The WASM adapter checks string/array lengths before copying host input and accepts only Uint8Array bytes.
## Save and Save As
With the provider enabled, interactive Save and Save As capture a native DXF and emit saveDialog.
A Save As requested with `format: "dwg"` opens the ordinary local file picker.
The event carries requestId, documentId, revision, intent and suggested filename. The host presents
its own choice of **provider / device / cancel**, then calls resolveSaveDialog. The editor owns the
captured state while the choice is open, so changing tabs or editing cannot silently change the target.
No save happens merely because a dialog was opened or a byte capture was produced.
Choosing provider emits save with the immutable native bytes, filename, intent, documentId, revision,
providerId, namespace, connectionId and requestId. Save includes a previously bound resourceId;
Save As requests a distinct resource. The provider must finish its durable write before returning
saveResult(requestId, saved, resourceId). An ACK cannot nominate a document or revision, cannot be
replayed, and cannot bind a resource already owned by another open document. Failed/cancelled writes
keep edits unsaved. Later edits remain dirty when an older capture succeeds. There is no pretend local
path for an external resource.
Choosing device emits save with destination device and the capture. The host hands the bytes to the device using the
browser's ordinary download mechanism, then returns download as the result. This is a terminal transfer
result, **not durable provider confirmation**, and does not clear the document's saved checkpoint.
Save Copy, Export and programmatic commands keep their existing local behavior. With the capability
disabled or unregistered, the original browser/native save flow remains in use.
Provider Save/Save As captures one native DXF. DXF stores external image/drawing references as paths, not their bytes. To prevent an incomplete upload being marked saved, this bridge refuses provider capture when the modeled drawing contains external images or xrefs; bind/remove those references first. Provider Open checks the decoded drawing for those same modeled references before running the native Open command, so provider bytes cannot trigger its automatic image/xref filesystem loaders. A refusal leaves existing documents unchanged and reports the correlated openFailed terminal. Ordinary local Open keeps its existing native behavior.
Single-file transfers inherit the existing [DXF codec limits](file-format-parity.md). Font files, including SHX/bigfonts, and other dependencies are not collected or packaged. The bridge does not certify arbitrary foreign DXF as lossless or scan unmodeled records for dependencies. It adds no linked-file negotiation, resource-set checkpoints, attachment bundle or atomic multi-file save. The host receives the one DXF produced by the native writer and remains responsible for its durable storage.
Use the existing local Copy/Export commands for interchange formats. The host must preserve the native
extension; changing a suffix cannot turn native bytes into PDF, SVG or another interchange format.
Native capture uses the existing IoHooks / write_as DXF encoder. The existing ?host=parent and data-host="page" host modes are preserved. The optional provider capability is installed only when neither mode connects, so two hosts do not compete for Save. DWG and interchange outputs remain in the original local flow.
Normal close/revert actions wait or refuse while provider work is unresolved. The browser can still
force-close/reload a tab; the host should provide an unsaved-work warning and must not acknowledge a
write it cannot recover. This bridge does not add automatic saving, cross-client conflict resolution,
offline persistence, autosave recovery or an inactivity/login implementation.
## Open and Recents
The existing Home screen and File > Open Recent display a separate provider section while enabled.
Local Recents retain their own storage and behavior. Publish only the current account's native files
with setResources; the editor never scans a VM or guesses a path from a name.
A click emits openRequested with requestId and resourceId. After authorization, the provider fetches
bytes and responds with openResource using that request ID. The editor parses the native project before
emitting opened or openFailed. Selecting an already-bound open resource focuses its existing document
without replacing unsaved edits. Unknown, duplicate or cancelled request replies are rejected.
The host handles failed fetches using cancelOpen rather than leaving the operation pending forever.
Completion events are saved, downloaded, saveFailed, saveCancelled, opened, openFailed and openCancelled.
Events associated with an account include providerId, namespace and connectionId. Storage keys should
use the provider/account/resource identities, never display names, and the backend should use versioning
or conditional writes if it allows concurrent clients.
## Recoverable publication failures
The byte publisher calls an explicit catch-enabled `Uint8Array.from` import. Recoverable JavaScript
copy/allocation errors become returned errors, are logged, and do not bypass later events in the
batch. This is not recovery from fatal memory exhaustion, WASM traps or process termination; DOM
listener exceptions swallowed by the browser are not assumed to propagate from dispatchEvent.
A failed `save` or `saveDialog` moves only its still-owned capture into a bounded failure inbox.
It retains every captured document alias in finishing-saves ownership until the actual CAD
application consumes the failed Action and queues its correlated `saveFailed` terminal. Retained
bytes are discarded. No saved checkpoint, binding or durable acknowledgement is manufactured.
Public action/result admission checks are unchanged. At most 16 previously admitted captures can
await failure consumption separately, including when the ordinary queue is full. Repaint is requested through
the installed editor context. Accepted synchronous results/choices remain authoritative.
A failed `openRequested` retires only an unanswered read and retains its correlated `openFailed`
terminal across event-queue capacity limits. An already queued open response survives a later
dispatch error. Fresh choices/reads can retry after failure consumption; IDs are never reused.
Busy/account ownership includes all seven completion event types while queued or in a taken
publication batch. Batch protection is acquired atomically and released independently for nested
publishers. Hosts must defer unregisterProvider until the publication batch returns and all outstanding
operations and terminal deliveries finish. Independent save/open admission rules are unchanged.
The publisher still performs two bounded drains in order.
## Validation
Regression fixtures cover the default-off gate, single-use/late replies, account reconnection, resource
scope and alias rejection, cancellation, immutable captures, switching tabs, edits after capture and
conservative device results. The source includes the WASM adapter and native encoder/decoder integration.
Run the required repository CI and the actual Window fixture on the complete candidate. This document does not claim those checks
have been executed merely because fixtures are present.
New source regressions cover full ordinary action queues, a bounded failure inbox, captured aliases,
failed chooser/read publication, accepted reentrant callbacks, current/nested terminal ownership
and recovery through a full event queue. The native application fixture uses the real DXF codec and
CAD failure consumer without altering process-global format hooks, preserving another active drawing
and later edits. The WASM fixture uses the exported window API, production publisher, actual CadApp
logic and native DXF encoder/decoder. Rust closures produce real JS RangeErrors for byte and metadata
dispatch failures; catch-enabled calls restore exact property descriptors before assertions. It
observes continuation, correlated failure terminals, a nonempty DXF retry and opening that payload
under a distinct resource, without marking later edits saved.
The native provider_format_boundaries integration binary covers the real DXF Save/Save As refusal,
self-contained capture and ACK, ordinary explicit DWG and disabled-provider local save behavior. Its
provider_open_refuses_external_images_and_xrefs_before_native_path_loading fixture exercises provider
Open refusals for model/layout/block images and xrefs without adding a document or binding.
The actual Window fixture is in
[browser_tests.rs](../apps/cadcraft-web/src/file_providers/browser_tests.rs). With a real browser and
the wasm-bindgen-test browser runner configured, run the existing WASM main harness:
```sh
cargo test --locked --offline -j1 -p cadcraft-web --bin cadcraft-web --target wasm32-unknown-unknown file_providers::browser_tests:: -- --nocapture
```
Simulated user Save/Save As uses the existing Null parameter form. JSON object parameters continue
to mean explicit programmatic operations and never acquire dialogs.
These are authored fixtures, not execution receipts. Real browser/runner execution remains required;
native tests or WASM compilation alone do not establish the window assertions. The fixture does not
run a rendered WebRunner, prove backend durability or simulate true out-of-memory failure. The web
test dependency is wasm32-only; the UI's existing workspace IO crate is a test-only dependency for
real drawing-codec fixtures. The existing locked graph is retained; its candidate must be reviewed
before checks.
Contributor credit: @alejocapo04.
## Native UI evidence
The existing recent-files test harness covers the real Start page with the optional provider absent
and connected, retaining the separate device history in both states. It uses synthetic drawing names
and metadata, with no storage or authentication backend. The native label assertions also run without
a GPU when the output variable is unset.
```sh
CRAFT_PROVIDER_UI_FIXTURES=/absolute/output cargo test --locked -p cadcraft-ui-egui --test recent_files provider_recents_render_separately_from_device_history -- --exact --test-threads=1
```
This saves `cadcraft-provider-recents-off.png` and `cadcraft-provider-recents-on.png` using
egui_kittest's existing offscreen renderer. Keep the generated review artifacts outside Git.
+374
View File
@@ -0,0 +1,374 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under the name "LEGAL", and included in all Covered Software
distributed in Source Code Form. Except to the extent prohibited by
statute or regulation, such description must be sufficiently detailed
for a recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
@@ -0,0 +1,40 @@
# Third-Party Notices
## ACadSharp
The DWG reader and writer include code ported and adapted from ACadSharp. The repository
history's initial DWG support commit identifies the source classes explicitly, including
`DwgStreamReaderBase`, `DwgLZ77AC21Decompressor`, `DwgFileHeaderWriterAC18`, and
`DwgObjectWriter`. Their current Rust implementations are in `src/io/dwg`.
Copyright (c) 2021 Albert Domenech
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## DWG Format References
DWG field layouts and version behavior are based on the Open Design Alliance (ODA) DWG
specification and reverse engineering, including comparison with drawings produced by CAD
applications. LibreDWG is used as a secondary cross-check for selected field names and
layouts. The Reed-Solomon tests cite numeric reference values from LibreDWG's
`src/reedsolomon.c` to validate the Rust implementation; those values are test data, not
translated routines. The repository history and source review found no LibreDWG routines
ported into the implementation. The source comments identify the specific cross-checks.
+4 -1
View File
@@ -23,5 +23,8 @@ fn dwg_test_dependency_matches_the_shared_bridge_targets() {
tests["target"], "cfg(not(any(target_arch = \"wasm32\", all(target_os = \"freebsd\", target_arch = \"aarch64\"))))",
"--all-targets must not add acadrust where the shared DWG bridge excludes it"
);
assert_eq!(tests["req"], "^0.6.6", "tests inspect output from the decoder version used by craft-dwg");
assert_eq!(
tests["source"], "git+https://github.com/storytold/acadrust.git?rev=5d5c482b3fcb3dc77e8281474461760f32959436",
"tests inspect output from the decoder craft-dwg uses: the storytold/acadrust fork at storytold/v0.6.6"
);
}