Compare commits

..
Author SHA1 Message Date
FredApps 4f0abbefdf Merge main into stack/e5
Conflicts: crates/engine/src/session/cmdline.rs (lisp_answer keeps main's 3D point Z handling),
crates/ui-egui/src/i18n.rs (Hebrew registered next to Dutch and pt-PT; the legacy iw tag still
selects he through the new region-aware locale matching), crates/ui-egui/src/options.rs and
docs/localization.md (both language lists).
2026-12-03 05:31:06 +01:00
FredApps 0f3d445d1f Merge pull request #3652 from storytold/dependabot/cargo/cargo-dependencies-7b0fc36391
chore(deps): bump the cargo-dependencies group across 1 directory with 13 updates
2026-12-03 05:25:22 +01:00
FredApps 616a7c0b52 Merge pull request #1243 from marcoarnulfo/fix/trim-fillet-chamfer-xline-ray
TRIM, FILLET and CHAMFER on rays and xlines: a finite piece becomes a line, an unbounded one a ray
2026-12-03 05:15:20 +01:00
FredAppsandyohanesyuen 1ba557615e Merge main into the ray and xline editing fix
The TRIM, EXTEND, FILLET and CHAMFER changes for rays and xlines now live in
the split modules (cmd/modify/trim.rs, cmd/modify/fillet.rs,
cmd/modify2/trimext.rs, cmd/trimextend.rs). The tests move to the integration
suite (tests/it) and the parity rows are carried over.

Based on the conflict resolution and the added tests in
marcoarnulfo/cadcraft#1 by yohanesyuen.

Co-authored-by: yohanesyuen <4329125+yohanesyuen@users.noreply.github.com>
2026-12-03 05:00:42 +01:00
FredApps 01d5fae93f Merge pull request #2791 from salehnemari-max/ar-cadcraft-complete
ar: complete the Arabic catalog
2026-12-03 04:57:50 +01:00
FredApps c974978fce Merge pull request #3742 from Elvis33LE/ci/event-driven-cache-prune
ci: add event-driven cache-prune workflow
2026-12-03 04:56:07 +01:00
FredApps 77973774d0 Merge pull request #2405 from Dievartis/feature/command-suggestions-navigation
Add Shift+Arrow keyboard navigation for command suggestions
2026-12-03 04:49:09 +01:00
FredApps 7a8ba5545e native_menu: pass the menu event handler as an Arc for muda 0.22
muda 0.22 takes Option<Arc<dyn Fn(MenuEvent) + Send + Sync>> in
MenuEvent::set_event_handler. Wrap the existing closure in Arc::new;
event delivery and the repaint wakeup are unchanged.
2026-12-03 10:48:24 +07:00
FredApps 27b3e8727d Merge pull request #1511 from aldozar/feat/snap-z
Object snaps give points their Z; LINE and POINT keep it (OSNAPZ)
2026-12-03 04:47:17 +01:00
FredApps 456926ff70 Merge pull request #1233 from midasmatterhorn/fix/properties-set-hatch-data-loss
engine: keep a hatch's custom .pat definition when properties.set changes it
2026-12-03 04:46:42 +01:00
FredApps 6295b6093f Merge pull request #1097 from codyvogt/fix/dynblock-visibility-grip-position
Dynamic blocks: a visibility or lookup grip carried by an action goes with it
2026-12-03 04:45:53 +01:00
FredApps 15b2085dfe Merge pull request #3171 from Torentje/feat/i18n-18-languages-parity
feat(i18n): register Dutch (nl) and European Portuguese (pt-PT) interface languages
2026-12-03 04:45:08 +01:00
FredApps f894be9117 Merge pull request #768 from SBaksa/ui-font-scripts
Interface fonts for the scripts of the names shown, on top of install_fonts (follow-up to #732)
2026-12-03 04:44:31 +01:00
FredApps 7843840bf0 Merge pull request #3741 from V1dalTheAbidal/pr/typed-window-rubber-band
Typed W, C and BOX draw their selection rectangle after the first corner (#3667)
2026-12-03 04:43:56 +01:00
midasmatterhorn adac927d7d Merge main into fix/properties-set-hatch-data-loss 2026-12-03 04:35:48 +03:00
Tanish Manku db08e0b293 Landing fix: #3763's tab-key test sends Control on macOS 2026-12-02 14:47:13 -07:00
Tanish Manku 46845744a9 Merge #3763 2026-12-02 14:47:13 -07:00
Tanish Manku 60ac9ac001 Merge #3748 2026-12-02 14:47:12 -07:00
Tanish Manku bc6277da45 Merge #3749 2026-12-02 14:47:12 -07:00
Tanish Manku 96c348ff8e Merge #3750 2026-12-02 14:47:12 -07:00
Tanish Manku 336126a95c Merge #3757 2026-12-02 14:47:11 -07:00
Tanish Manku 2d351ff5a7 Merge #3726 2026-12-02 14:47:11 -07:00
Tanish Manku 2a281c8d4c Merge #3728 2026-12-02 14:47:05 -07:00
Tanish Manku 82f8b17348 Merge #3737 2026-12-02 14:47:05 -07:00
Tanish Manku ce7b234161 Merge #3738 2026-12-02 14:47:05 -07:00
Tanish Manku 40f2274065 Merge #3725 2026-12-02 14:47:04 -07:00
Tanish Manku 8a483b4804 Merge #3724 2026-12-02 14:47:04 -07:00
Tanish Manku 8d0c97e57e Merge #3713 2026-12-02 14:47:04 -07:00
Tanish Manku 6f7a827f41 Merge #3448 2026-12-02 14:47:04 -07:00
Tanish Manku 53d515a0d3 Merge #3296 2026-12-02 14:47:03 -07:00
Tanish Manku 51ea12b976 Merge #3263 2026-12-02 14:47:03 -07:00
Tanish Manku d45a216319 Merge #2688 2026-12-02 14:47:03 -07:00
Tanish Manku deb156e09b Merge #3284 2026-12-02 14:47:03 -07:00
Tanish Manku 51d89dea17 Merge #3567 2026-12-02 14:47:02 -07:00
Tanish Manku c09ab353f0 Merge #3669 2026-12-02 14:47:02 -07:00
Elvis33LE d0747f768a ci: ensure trailing newline in cache-prune workflow 2026-12-02 21:48:42 +01:00
lforgiariniandClaude Sonnet 5.5 7cdd052b83 fix(ui): Ctrl+Tab leaves a running command alone with one drawing open; Ctrl, not Cmd, on macOS
With fewer than two drawings the shortcut no longer goes through Session::start, which cancelled
the running command although nothing was switched. On macOS the shortcut is Ctrl+Tab, as
Cmd+Tab switches applications there.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 20:46:23 +01: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
lforgiariniandClaude Sonnet 5.5 b87838fbef feat(ui): Ctrl+Tab and Ctrl+Shift+Tab move to the next and the previous open drawing
Adds the commands document.next and document.prev (Window menu), which switch to the
neighbouring open drawing and wrap round at either end, ending a command left running in
the drawing it started in, as document.switch does. From the Start tab the keys return to
the current drawing.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 17:31:14 +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 <153173854+FredApps@users.noreply.github.com>
2026-12-02 16:18:48 +01:00
V1dalTheAbidal a9ba2b5210 Releasing held DSTYLE strings looks only at the last ones held (#3721) 2026-12-02 17:17:01 +02:00
V1dalTheAbidal f4b2112da9 A click on the drawing comes after an expression typed at a prompt (#3666) 2026-12-02 16:57:35 +02:00
V1dalTheAbidal f243082d64 A loose DSTYLE string kept beside a removed list stays inside its own braces (#3721) 2026-12-02 16:57:34 +02:00
Elvis33LE ccdbb4207a ci(cache-prune): pin action SHA and allowlist same-repo main push 2026-12-02 14:22:08 +01:00
V1dalTheAbidal bc37092d35 A dragged window, an array edit and a named object come after an expression typed at a prompt (#3666) 2026-12-02 14:22:17 +02:00
V1dalTheAbidal 8f82887924 Removing a leader's DSTYLE list keeps the groups that become adjacent (#3721) 2026-12-02 14:22:16 +02:00
dependabot[bot] d643981cea chore(deps): bump the cargo-dependencies group across 1 directory with 13 updates
Bumps the cargo-dependencies group with 13 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [clap](https://github.com/clap-rs/clap) | `4.6.7` | `4.6.10` |
| [clap_complete](https://github.com/clap-rs/clap) | `4.6.11` | `4.6.12` |
| [clap_mangen](https://github.com/clap-rs/clap) | `0.3.3` | `0.3.4` |
| [log](https://github.com/rust-lang/log) | `0.4.34` | `0.4.35` |
| [skrifa](https://github.com/googlefonts/fontations) | `0.48.0` | `0.50.0` |
| [harfrust](https://github.com/harfbuzz/harfrust) | `0.14.0` | `0.16.2` |
| [encoding_rs](https://github.com/hsivonen/encoding_rs) | `0.8.42` | `0.8.44` |
| [rfd](https://github.com/PolyMeilex/rfd) | `0.17.2` | `0.18.0` |
| [rstar](https://github.com/georust/rstar) | `0.13.0` | `0.14.0` |
| [naga](https://github.com/gfx-rs/wgpu) | `30.0.1` | `30.0.2` |
| [ron](https://github.com/ron-rs/ron) | `0.12.2` | `0.12.3` |
| [pollster](https://github.com/zesterer/pollster) | `1.0.1` | `1.0.3` |
| [muda](https://github.com/tauri-apps/muda) | `0.21.2` | `0.22.0` |



Updates `clap` from 4.6.7 to 4.6.10
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/main/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.6.7...clap_complete-v4.6.10)

Updates `clap_complete` from 4.6.11 to 4.6.12
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/main/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.6.11...clap_complete-v4.6.12)

Updates `clap_mangen` from 0.3.3 to 0.3.4
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/main/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_mangen-v0.3.3...clap_mangen-v0.3.4)

Updates `log` from 0.4.34 to 0.4.35
- [Release notes](https://github.com/rust-lang/log/releases)
- [Changelog](https://github.com/rust-lang/log/blob/main/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/log/compare/0.4.34...v0.4.35)

Updates `skrifa` from 0.48.0 to 0.50.0
- [Changelog](https://github.com/googlefonts/fontations/blob/main/docs/RELEASE.md)
- [Commits](https://github.com/googlefonts/fontations/compare/skrifa-v0.48.0...skrifa-v0.50.0)

Updates `harfrust` from 0.14.0 to 0.16.2
- [Release notes](https://github.com/harfbuzz/harfrust/releases)
- [Changelog](https://github.com/harfbuzz/harfrust/blob/main/CHANGELOG.md)
- [Commits](https://github.com/harfbuzz/harfrust/compare/0.14.0...0.16.2)

Updates `encoding_rs` from 0.8.42 to 0.8.44
- [Commits](https://github.com/hsivonen/encoding_rs/compare/v0.8.42...v0.8.44)

Updates `rfd` from 0.17.2 to 0.18.0
- [Release notes](https://github.com/PolyMeilex/rfd/releases)
- [Changelog](https://github.com/PolyMeilex/rfd/blob/master/CHANGELOG.md)
- [Commits](https://github.com/PolyMeilex/rfd/compare/0.17.2...0.18.0)

Updates `rstar` from 0.13.0 to 0.14.0
- [Commits](https://github.com/georust/rstar/compare/v0.13.0...v0.14.0)

Updates `naga` from 30.0.1 to 30.0.2
- [Release notes](https://github.com/gfx-rs/wgpu/releases)
- [Changelog](https://github.com/gfx-rs/wgpu/blob/trunk/CHANGELOG.md)
- [Commits](https://github.com/gfx-rs/wgpu/compare/naga-v30.0.1...naga-v30.0.2)

Updates `ron` from 0.12.2 to 0.12.3
- [Release notes](https://github.com/ron-rs/ron/releases)
- [Changelog](https://github.com/ron-rs/ron/blob/master/CHANGELOG.md)
- [Commits](https://github.com/ron-rs/ron/compare/v0.12.2...v0.12.3)

Updates `pollster` from 1.0.1 to 1.0.3
- [Changelog](https://github.com/zesterer/pollster/blob/master/CHANGELOG.md)
- [Commits](https://github.com/zesterer/pollster/commits)

Updates `muda` from 0.21.2 to 0.22.0
- [Release notes](https://github.com/tauri-apps/muda/releases)
- [Changelog](https://github.com/tauri-apps/muda/blob/dev/CHANGELOG.md)
- [Commits](https://github.com/tauri-apps/muda/compare/muda-v0.21.2...muda-v0.22)

---
updated-dependencies:
- dependency-name: clap
  dependency-version: 4.6.10
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: clap_complete
  dependency-version: 4.6.12
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: clap_mangen
  dependency-version: 0.3.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: encoding_rs
  dependency-version: 0.8.44
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: harfrust
  dependency-version: 0.16.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
- dependency-name: log
  dependency-version: 0.4.35
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: muda
  dependency-version: 0.22.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
- dependency-name: naga
  dependency-version: 30.0.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: pollster
  dependency-version: 1.0.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: rfd
  dependency-version: 0.18.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
- dependency-name: ron
  dependency-version: 0.12.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cargo-dependencies
- dependency-name: rstar
  dependency-version: 0.14.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
- dependency-name: skrifa
  dependency-version: 0.50.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cargo-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-12-02 11:11:24 +00: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
V1dalTheAbidal 0c18fdd8f8 What takes a command's place comes after an expression typed at its prompt (#3666) 2026-12-02 12:30:43 +02: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
V1dalTheAbidal 9ddc83e676 A new LEADER or QLEADER takes the drawing's dimension overrides, as a new dimension does (#3721) 2026-12-02 11:49:41 +02: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
2ez4gcxandClaude Opus 5.5 8e4bf3cd9f Window selection holds text by what it draws, turned or not (#3731)
A window or window polygon tested a TEXT, ATTDEF or MTEXT by the
document's box for it, an estimate from its number of characters (and
lines). On the side a justification or attachment point leaves open,
that box reaches past what the fonts draw, so a window that held all of
a text, turned or not, could miss it: a right-justified label turned by
90 degrees hung its box below the window's bottom edge.

A window still takes an object whose box it holds. A text whose box it
doesn't hold but reaches into is now also taken when the window holds
the strokes the text draws, placed as the renderer places them
(annotative scale, upright text, ATTDEF tag, mirrored and slanted text).
A window polygon does the same. Only text along the selection's edge is
shaped, so selection costs what it did. Crossing windows and polygons,
fences and picks are unchanged.

Fixes #3731.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 14:05:55 +07:00
HagaiBA 26c9cef4d5 i18n(he): use action noun for Creates a user parameter 2026-12-02 07:43:52 +02:00
Dievartis 931c2c799d Merge upstream main and integrate command suggestion navigation 2026-12-02 06:23:58 +01:00
FredApps 0a43052c1f Merge main and keep both dimension text visibility checks 2026-12-02 05:45:27 +01:00
FredApps 7c09b2bc14 Merge main and keep the DXF reader regression tests 2026-12-02 05:43:38 +01:00
FredApps 79ba6cf891 Merge main and keep the MIRROR preview at the erase prompt 2026-12-02 04:29:03 +01:00
V1dalTheAbidal f8578a4020 A typed W, C or BOX draws its rectangle to the snapped second corner (#3667)
At "Specify opposite corner" the running object snaps hold the cursor, and
a click gives the held point as the second corner. The rectangle was drawn
to the pointer itself, so it could differ from the selected area by the
snap distance, and a BOX could be drawn as a window while the click made a
crossing. A typed rectangle is now drawn to the cursor as the click uses
it. The implied window keeps the pointer, the point its click selects with.
2026-12-02 03:41:44 +02:00
V1dalTheAbidal ed7b601123 A leader's DSTYLE list is found after a loose name string, removed in one pass and refused as raw xdata (#3721) 2026-12-02 03:35:35 +02:00
V1dalTheAbidal fb07eaab7e An expression typed at a prompt keeps its own value and its command's undo step (#3666)
A routine that ended in a later frame left its value behind, and the next
expression the frames carried on handed it to the prompt as its own: a
routine now starts with no value. A snapped click that came while the
frames worked out a point lent that point its viewport origin: the
expression's value now answers its prompt before the click's origin is in
place. The command an expression was typed in, when Esc or a failed
expression ended it, recorded what it had drawn in the expression's
routine, which dropped it: such a command keeps its own undo step, with
frames and without.
2026-12-02 02:26:07 +02:00
V1dalTheAbidal 865285ca46 getangle and getorient read text given as an input as the prompt reads it typed (#3398)
A string in inputs went straight to the angle parser, so empty text and
coordinates were refused and the call took the next input. Empty or blank
text is now Enter (initget bit 1 still decides), and coordinates are a
point in the current UCS in every form the prompt takes (1,1, @1,1, 1<45,
*1,1), the relative ones from the last point. Numbers, unit-bearing text
and keywords are read as before.
2026-12-02 02:25:58 +02:00
kc8a e37f18166d trim/extend: gate Shift through person_input source check 2026-12-01 21:50:55 +00:00
kc8a 6cf44e32ff trim/extend: ignore the live Shift for script and LISP input 2026-12-01 21:21:35 +00:00
030f8c5c88 Cancel the counting pass too, and test the cancel through the rebuild (#3480)
build_mesh_until asks whether it is cancelled before each 64 primitives, while
it counts them as well as while it converts them. rebuild::run goes through
run_until, so a test cancels a build at each of its checks and gets nothing
back, not a list without its mesh.

The tests, run_until and the check while counting are from 2ez4gcx's commit
1b7e064b.

Co-Authored-By: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 08:23:51 +13:00
V1dalTheAbidal c6402fa9a5 Esc stops an AutoLISP expression typed at a prompt (#3666)
An expression typed at a command's prompt ran to its end inside one call
on the interface thread, so no frame was drawn and Esc was not read until
it was over. In the window it now runs a slice per frame, as a routine at
Command: does, and Esc stops it. Every other input first waits for its
value, as before. Hosts without frames (the CLI, MCP, scripts) are
unchanged.
2026-12-01 21:20:19 +02:00
Elvis33LE 7364032102 ci: add event-driven cache-prune workflow 2026-12-01 20:01:00 +01:00
V1dalTheAbidal 9e8b027f7b A LEADER reads, draws and writes its dimension style overrides (#3721)
A leader's overrides of its dimension style (the DSTYLE list in its ACAD
xdata) were kept as raw xdata and not used, so an overridden arrow size,
scale, arrowhead or line colour did not show. They are now read into the
leader, used when it is drawn, and written back as one DSTYLE list; the
rest of the leader's ACAD xdata is kept as before.
2026-12-01 20:09:30 +02:00
The old Dutch Guy 2d52623dd6 feat(i18n): register Dutch (nl) and European Portuguese (pt-PT) interface languages 2026-12-01 19:09:04 +01:00
V1dalTheAbidal 8028efba49 getangle and getorient return radians for answers given as inputs (#3398)
An answer given up front to the lisp command (inputs) was handed to
getangle and getorient as their value, so 45 came back as 45. They now
read such an answer as the same answer at their prompt: a number or text
in the angular units, a point as a picked point, null as Enter. Answers
typed at the prompt already came back in radians.
2026-12-01 17:29:46 +02:00
Saleh Hassan AlnemariandClaude Opus 5.5 76a1ece890 Merge main into ar-cadcraft-complete
The Arabic catalog conflicted at the end of ar.tsv, where both sides
added rows. Kept this branch's Arabic rows for Find and Replace, Edit
Text and Ctrl+Enter (main had them as English placeholders), and the 27
block-library rows main added. No key appears twice; the ui-egui i18n
tests pass, including the Stretch/Trim/Point test from #2898.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LMLkQogmJDoeteHcBk22Rj
2026-12-01 18:11:51 +03:00
Aldo ZarateandClaude Opus 5.5 04dc8bc2b0 Merge upstream/main into feat/snap-z
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 09:07:42 -06:00
V1dalTheAbidal e9fa62f141 Typed W, C and BOX draw their selection rectangle after the first corner (#3667)
The drawing area drew a selection rectangle only for the implied window a
click on empty space opens, so a W, C or BOX typed at "Select objects"
showed nothing between its two corners. The rectangle is now drawn from
the typed mode's first corner to the cursor with the same code: W as a
window, C as a crossing, BOX as a window to the right and a crossing to
the left, with the same area fill settings.
2026-12-01 16:38:47 +02:00
V1dalTheAbidal 8ca0152d62 A true colour keeps its colour through a colour-dependent plot style table (#3639)
An object with a true colour was printed in the colour of the plot style
of its nearest index colour, so a true white solid hatch came out black
through a table whose colour 7 pen is black. The colour of such a style
no longer replaces a true colour, the object's own or its layer's: it is
an answer for index colours. The other fields of the nearest index
colour's style, grey scale and screening too, apply as before.
2026-12-01 16:08:39 +02:00
moandClaude Fable 5.2 4b2dd11f64 MTEXT background mask: a stroke that runs across a gutter is behind the mask
Each point of the text grew the column nearest to it, so a stroke that
starts in one column and ends in the next (text too wide for its column)
was masked at its two ends and bare in between, where the single quad had
covered it. The column a stroke comes from now grows to the stroke's far
end as well.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 13:23:30 +00:00
moandClaude Fable 5.2 114a3fe4e7 An ATTRIB's layer is compared with the block definition the reader keeps
Of several BLOCK records of one name the last replaces the others when
blocks are placed, and the lookup of a tag's definition took the first
record's. An attribute could then be pinned to its reference's layer by a
definition the drawing no longer has.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 13:21:36 +00:00
Codex f760e79be9 Run the layer-name font regression through normal frame hooks 2026-12-01 08:10:53 -05:00
moandClaude Fable 5.2 6d0da01e75 Text extents hold a text's underline and overline
The fonts draw an underline a fifth of the drawn height below the baseline
and an overline a fifth of it above the top of the line. The box of a TEXT,
ATTRIB or ATTDEF ran from the baseline to the height, so both lines were
outside the extents and outside what a click on the text hits. The box now
reaches them when the value turns them on for a character it draws, at
every justification and for the range of heights Aligned text can be drawn
at. Text without them keeps its box.

Follow-up to #3695.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 12:53:03 +00:00
moandClaude Opus 5.5 b837e9c1e4 LISP: textbox (part of #3676)
`(textbox elist)` returns the smallest box around a TEXT as the renderer shapes it, relative to
the insertion point and unrotated: the drawn glyphs' box, so its first corner is the insertion
point unless letters reach below the baseline. Groups the list leaves out take the current
text style, its height (or TEXTSIZE), width factor and obliquing. A list that is not a TEXT
gives nil.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 12:36:53 +00:00
moandClaude Sonnet 5.5 54afe41115 An ATTRIB keeps its own layer when it is its reference's, and a layer only it names is added on read
Follow-up to #3613.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 12:30:58 +00:00
moandClaude Sonnet 5.5 4741c4a737 MTEXT background mask: one quad per column, gutters stay bare
The mask of #3240 was one quad over the layout's combined box, so a
multi-column MTEXT got its gutters painted over. Draw one quad per
column from the layout's column_bounds, each grown by the text drawn
past its column and by the border offset factor as the single quad was,
and turned by the rotation about the insertion point. All quads go into
one primitive, so the mask kind and draw order are as before. Each
stroke point grows its nearest column by binary search over the column
starts, so hostile column counts stay O(points log columns).

With one column the box is the combined box and every stroke grows it,
so the output is the same six vertices as before.

Follow-up to #3240.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 12:17:34 +00:00
code-compliant de4f74d43d test(lisp): relative link targets, and a case only the folder check can pass 2026-12-01 17:39:55 +08:00
code-compliant 14603dcf9d fix(lisp): keep the case fallback inside the file access rules and follow linked files
The case-insensitive fallback listed a folder without asking the file access rules, so under
automation roots it opened a folder the exact read had refused (for a network path, contacting
its host). It now checks the folder before listing it, and each matching name before following it.

A support file that is a link was not found, because DirEntry::metadata does not follow links.
The match now counts the file a link leads to.

The precedence check in the test needs two names that differ only by case, so it now runs only
where the temporary folder tells them apart.
2026-12-01 17:30:35 +08:00
Yuri GanugiandClaude Opus 5.5 ad63f0144f Plot styles: one Plot style table row in Properties, and a failed folder rename keeps one file
The Properties palette's Plot style table row for a layout and for Model
is now one row that names the sheet it sets. With `main`'s recent
changes to `properties_section`, the two rows took the function over
clippy's cognitive complexity limit (31/30) in the merge CI checks.

A folder rename that writes the new file but can't remove the old one
now takes the new file back and reports the error, so the table isn't
held twice and the rename can be tried again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 09:35:41 +01:00
HagaiBA 911e4dd3be docs(i18n): add Hebrew catalog provenance, clean-room header, and prune dead keys 2026-12-01 10:34:50 +02:00
cdwilson127andClaude Opus 5.5 a6889461be Stop a cancelled background mesh build part way through (#3480)
The regen worker asked whether its build had been cancelled before and after converting the display
list to vertex data, but not during it, so a build that a newer view had replaced still converted
every primitive of a large drawing.

gpu::build_mesh_until asks before it allocates and every few thousand primitives, and the worker
passes its cancel flag. build_mesh is the same conversion for the callers that have nothing to
cancel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 20:16:55 +13:00
code-compliant b163dd3245 Merge remote-tracking branch 'origin/main' into fix/load-finds-case-variant 2026-12-01 14:45:15 +08:00
Yuri GanugiandClaude Opus 5.5 10f42e323f Plot styles: a plot that changes nothing leaves no undo step; New copies the entry chosen
PLOT, EXPORTPDF and `pagesetup {layout: "Model"}` now read first
whether the table would change Model's table or bring in a folder copy,
and touch the drawing only then. Before, every Model plot to a path made
an empty undo step, because the Print dialog always sends Model's table.

A PNG or SVG plot with `"path": null` returns image data, so it is a
preview: it no longer keeps the table.

STYLESMANAGER `new` takes `fromWhere: folder | drawing`, saying where
`from` is when the drawing and the folder both hold that name. The
Plot Style Manager's New... sends the place of the selected entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 07:33:32 +01:00
Yuri GanugiandClaude Opus 5.5 75ea55d956 Plot styles: keep a plot's table only once its output is written, and name the manager's controls
PLOT and EXPORTPDF now take a folder table into the drawing, or set
Model's table, only after the file is written or delivered. A refused
path or a failed write leaves the drawing and its undo history as they
were.

The Plot Style Manager's table picker and the New window's "Start from"
are labelled by their visible labels. Each cell of the style grid
(Grayscale, Screening, Linetype, Lineweight) is named by its column and
its style. Before this, AccessKit showed 766 of them with no name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 22:20:00 +01:00
paco-velasco e9f1699bea Merge remote-tracking branch 'origin/main' into fix/dim-defpoints-on-main 2026-11-30 21:22:58 +01:00
HagaiBA ba2887bad0 fix(ui): validate Hebrew glyphs in fallback font and share cached face 2026-11-30 16:25:41 +02:00
paco-velascoandClaude Fable 5.2 400c5889ab Merge main into fix/dim-defpoints-ignore-pdmode
Ctx keeps both new fields: block (from #3560) and dim_block.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-30 09:14:00 +01:00
Yuri GanugiandClaude Opus 5.5 2f22fdca41 Plot styles: fixes from review of the folder and rename
- A folder table renamed only by case is no longer lost on a disk that
  ignores case: the old file is deleted only when the folder lists both
  names, otherwise it is removed and written again under the new spelling.
  A failed delete of the old file is now reported.
- Each read remembers which file holds each table, so a table held by a
  file without its kind's ending (outside.json) can be edited and deleted.
- Renaming the drawing's table also moves Model's page setup.
- A PDF of Model alone, plotted from a layout tab, records Model's table.
- A table name is at most 255 characters with its ending.
- The folder reads its first 1000 files by name and warns about the rest.
- The manager's description draft belongs to one entry (name and place).

The test folder now ignores case, as macOS and Windows disks do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:12:26 +01:00
HagaiBA bf77ffdbba i18n(he): narrow RTL claim, decouple picker test from host fonts, and verify BiDi shaping 2026-11-30 10:05:24 +02:00
Yuri GanugiandClaude Opus 5.5 98a5f5c352 Plot styles: open_folder returns a thiserror enum, not a String
ast-grep's string-error rule refuses Result<(), String> in
apps/cadcraft/src/main.rs. open_folder now returns OpenFolderError
(creating the folder, or starting the file manager), and
Services::open_folder carries it as Box<dyn std::error::Error>, since
ui-egui has no thiserror. The messages are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 07:50:00 +01:00
Yuri GanugiandClaude Opus 5.5 74f2f29958 Plot styles: a folder of tables every drawing can use, copied into each drawing that uses them
Plot style tables can be kept in <settings>/plotstyles (one
<name>.ctb.json / <name>.stb.json file per table), which every drawing
lists. Lookup is drawing, then folder, then built-in. A layout or Model
that chooses a folder table takes a copy into the drawing, and saving to
DWG/DXF copies in any folder table a page setup names, so a drawing plots
the same without the folder. Model remembers its plot style table in its
page setup. STYLESMANAGER gains `where`, `rename` and `reload`; the Plot
Style Manager gains New, Rename, Delete, Open folder and Use for Model.

Fixes #1901. Same idea as #1912 by Nicholas Gower, who handed the issue
over; the code is written independently.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 06:36:08 +01:00
Codex 1b40e9ca4e Merge main and isolate the name-font cache regression test 2026-11-30 00:08:17 -05:00
FredApps 566e137483 test(engine): preserve LINE elevations on close and undo 2026-11-30 03:49:17 +01:00
Cody Vogt 81ca3d0cc5 Merge remote-tracking branch 'upstream/main' into fix/dynblock-visibility-grip-position 2026-11-29 08:21:27 -06:00
HagaiBA 24f1290377 i18n(he): align commit wording with FigCraft and keep logical >> arrow order 2026-11-29 07:29:48 +02:00
HagaiBA 8cbc4e4ef7 i18n(he): align CADCraft catalog with craft-i18n and refine action-noun / gender-neutral wording 2026-11-28 08:16:27 +02:00
Aldo ZarateandClaude Opus 5.5 71671af789 Merge upstream/main into feat/snap-z
Conflicts: typed Z ported onto main's UCS point parsing (parse_point3_in, parse_typed_point3; LISP points too), snap sources kept through main's ranked snap list, the new skip/dimension/proxy block paths and M2P/filter changes; both changelog rows kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 18:31:46 -06:00
HagaiBA 900bac863d fix(ui-egui): discover installed Hebrew fonts via fontdb and load for language picker 2026-11-27 00:10:45 +02:00
HagaiBA 9b9b9d1efc Merge remote-tracking branch 'origin/main' into feat/hebrew-ui-and-rtl
# Conflicts:
#	crates/ui-egui/src/i18n.rs
#	crates/ui-egui/src/i18n/tests.rs
#	crates/ui-egui/src/options.rs
#	crates/ui-egui/src/theme.rs
2026-11-26 17:13:24 +02:00
paco-velascoandClaude Fable 5.2 1ed527ec16 Dimensions: definition points stay dots under a point style (PDMODE)
A dimension read from a file draws with its block, whose POINT objects are
the dimension's definition points. They went through the drawing's point
style, so with PDMODE 3 every dimension showed large crosses at its origins.
They now draw as dots; the drawing's own points keep the point style.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-26 14:32:26 +01:00
SnotacusNexus a8cc7e4a5c test(io): cover the plane's y axis and the alignment point in a tilted text
The two tilted-TEXT fixtures both left group 50 and group 11 out, so plan_frame's
ay * sin term and the alignment-point mapping were never exercised.

tilted_text_turns_by_the_plane_axes_and_maps_its_alignment_point adds a
right-justified text at 45 degrees: under extrusion (0.6,0,0.8) the turn runs
along (-0.8,1)/sqrt(2) in plan, i.e. (-0.624695, 0.780869) normalized, and group
11 (2100,-800,600) is (1000,2100,0) in the WCS, the same frame as the insertion
point.

Checked that the test has teeth: dropping the ay * sin term fails it, and not
mapping the alignment point fails it, while the other two fixtures keep passing
in both cases.
2026-11-26 02:02:17 -05:00
SnotacusNexus 7edd1168f6 fix(io): a TEXT in a tilted plane is placed where the drawing has it
A TEXT's insertion point (group 10), alignment point (group 11) and rotation
(group 50) are coordinates and angles in the plane its extrusion (group 210)
names. The reader kept them as WCS values unless the extrusion was mirrored,
so a text in a truly tilted plane was drawn at its OCS point: in a drawing near
UTM coordinates that is millions of units away, and extents and fitted plots
took it in, shrinking the drawing to a dot.

Text cannot hold a tilted plane, so read it as seen from above, as #2584 does
for HATCH and LWPOLYLINE and #2763 does for 2D POLYLINE: map the points through
the arbitrary axis frame and turn the text by the plane's x axis, then spend the
extrusion. An extrusion within 1e-3 of the Z axis is noise, not a tilt.

Only the Z-up plane is handled. A mirrored plane (z < 0) is already taken apart
by text_from's mirror_text, which maps the anchors through the same frame and
swaps the justification to keep the readable footprint: projecting those points
again moved them twice (insert (1024,-280,1968) instead of
(-280,2000,-960) for group 10 (2000,-800,600) under (0.6,0,-0.8)). Its swapped
footprint needs the turn derived from the original OCS angle, so that case is
left as it is on main and belongs to a separate change.

Tests: tilted_text_is_placed_as_seen_from_above (fails on main),
mirrored_tilted_text_anchors_are_mapped_once (passes before and after; fails on
the earlier revision of this branch), plus the plain and noisy-extrusion
controls. No docs edit: the parity rows are the maintainers' batch.
2026-11-26 01:49:18 -05:00
Cody VogtandClaude Opus 5.5 2d9b9d1512 Dynamic blocks: a visibility or lookup grip carried by an action goes with it
A visibility or lookup parameter in a stretch, move, rotate, flip, scale or
polar stretch action's selection is carried along like the others, and
AutoCAD records where it went in the reference's value record (its state or
value, and its position). The record's position is now read
(`Value::Text::at`), carried by the actions with the state kept, written
back, and the grip is drawn there instead of where the dynamic block has it;
a state change leaves it where it is. A moved base point takes it back with
the other parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 17:45:08 -06:00
code-compliant 3504edbcdb fix(lisp): (load) finds a support file named in another case
A module written on Windows names its include in one case and ships the file
in another. Windows resolved that for free; a case-sensitive file system does
not, so (load "uppercase") failed with LOAD failed: "uppercase" when the
support folder held UpperCase.lsp.

Try the exact candidates first, so existing behaviour is unchanged, then retry
the name's case only. The support-folder rule and the name guard from #1927 are
unchanged: the case retry only changes the last component of a name that already
passed the guard.

Adds a test that fails without the fix.
2026-11-25 00:49:47 +08:00
HagaiBA 87fc77ee7d style(ui-egui): format i18n.rs with rustfmt 2026-11-19 15:11:30 +02:00
HagaiBA 013fddd927 fix(ui-egui): load embedded Hebrew Regular face in all languages and cap-validate system Hebrew font 2026-11-19 15:11:13 +02:00
HagaiBA af412d767c i18n(he): add Hebrew UI translation, fonts, and RTL layout support 2026-11-19 10:14:28 +02:00
jayzed80 6139f12b3f Selection: a dimension's block text on a frozen or off layer is not picked (#3218)
in_text read the box of a dimension block's text without asking whether the
text is drawn, so a pick where the text would be found the dimension while
its layer was frozen for the whole drawing or turned off. It now leaves out a
block object whose own flag or layer the renderer does not draw, layer 0
inside a block taking the dimension's layer as the renderer resolves it.
2026-11-18 01:22:29 +00:00
midasmatterhorn 1cae514a0d engine: keep a hatch's line families when the pattern registry lost them 2026-11-14 17:04:17 +03:00
Saleh AlnemariandClaude Opus 5.5 2604fa0326 Merge main into ar-cadcraft-complete; apply review suggestions
Resolves the ar.tsv conflict with main: keeps the translated Find and
Replace rows and adds main's three new rows, translating "Ctrl+Enter to
apply" and "Edit Text".

Applies thegr8dooma's review suggestions:
- Clear Recent Files / Open Recent now name the list, not the files.
- DXF rows: masculine verb with "تنسيق DXF" to agree with "قبله".
- Mils, Limits, Save Anyway, the save-changes question, "doesn't look
  whole", "authoring elements", and the US Survey units (مسحي, so they
  no longer use the word for Area).
- "Save changes to block" uses the same question form for consistency.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NQSx2Pokw4gVqdEQCAzh8r
2026-11-12 02:19:15 +00:00
SBaksa e05636a26a UI fonts: look for an unfound script's font again when the font folders change, not every 30 s (review) 2026-11-07 08:41:38 +11:00
SBaksa 452cac8f0c UI fonts: retry unfound fonts after a delay, repaint when the loader ends (review) 2026-11-07 07:44:56 +11:00
SBaksa 7623ee2e91 Merge remote-tracking branch 'origin/main' into ui-font-scripts 2026-11-07 02:21:08 +11:00
SBaksa f036f6ce07 WIP row 80: font review fixes (uncompiled) 2026-11-07 02:21:04 +11:00
SBaksa d06393f33a Merge remote-tracking branch 'origin/main' into ui-font-scripts 2026-11-07 00:01:44 +11:00
Saleh Hassan AlnemariandClaude Opus 5.5 27fb887f38 ar: complete the Arabic catalog (93 missing rows, Find and Replace dialog)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NQSx2MfhTCZcmeLrffc2ko
2026-11-04 20:45:46 +03:00
Aldo ZarateandClaude Opus 5.5 906395b4d2 Merge upstream/main into feat/snap-z
cmd.rs keeps main's new image module and this branch's crate-visible inquiry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 18:23:43 -06:00
SBaksa 4a3243e70a Merge remote-tracking branch 'origin/main' into ui-font-scripts 2026-11-03 19:59:07 +11:00
SBaksa a41ab8e249 Merge remote-tracking branch 'origin/main' into ui-font-scripts
# Conflicts:
#	docs/parity-checklist.md
2026-11-03 19:57:52 +11:00
austin62jakeandClaude Opus 5.5 cc560bde49 fix(engine): MIRROR keeps the mirrored copy on screen at "Erase source objects?"
After the second point of the mirror line, the preview and the GPU drag
mirror the selection in the picked line instead of disappearing, as
AutoCAD shows the result before you choose. The rubber band to the
cursor goes, since no point is being picked any more.

Fixes #2667

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:47:21 -06:00
Aldo ZarateandClaude Opus 5.5 b10856b14e Merge upstream/main into feat/snap-z
Session keeps LASTPOINT's Z and main's AREA, PERIMETER and DISTANCE; LASTPOINT
still reports its Z.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:48:05 -06:00
midasmatterhorn 687e30afa2 engine: keep a hatch's custom .pat definition when properties.set changes it 2026-11-01 05:34:05 +03:00
Aldo ZarateandClaude Opus 5.5 629d56689f Snaps inside block references and on ellipses take their Z
A snap on an object inside a block reference took the reference's
insertion Z. Each snap now remembers the object in the block it came
from and how the references on the way place it (insertion Z, Z scale,
block base), and takes that object's Z there. A reference in a tilted
plane keeps its own Z. Ellipses give their centre's Z.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 18:52:09 -06:00
SBaksa a6665d4040 Merge remote-tracking branch 'origin/main' into ui-font-scripts 2026-11-01 10:25:32 +11:00
SBaksa d93c513d2a Parity checklist: regenerate after interface fonts merge 2026-11-01 09:13:41 +11:00
SBaksa 170ebd3ee4 Merge main into interface script fonts
Keep per-script name fallbacks and cached language fonts alongside the new Vietnamese interface support. Check that its primary face retains diacritic coverage when installing name scripts.
2026-11-01 09:01:55 +11:00
SBaksa d61ad720d7 Parity checklist: regenerated after merging main 2026-10-30 13:52:38 +11:00
SBaksa df3b0a865c Merge remote-tracking branch 'origin/main' into ui-font-scripts
# Conflicts:
#	docs/parity-checklist.md
2026-10-30 13:49:27 +11:00
Aldo Zarate eb719cd766 Merge remote-tracking branch 'upstream/main' into feat/snap-z
# Conflicts:
#	docs/ui-parity.md
2026-10-29 19:26:00 -06:00
Aldo ZarateandClaude Opus 5.5 3523324084 Name the commands that read a typed Z in ui-parity
LINE and POINT read a typed Z as well as 3DPOLY now, and a point picked
with an object snap carries the Z of the object it snapped to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 10:51:01 -06:00
Aldo ZarateandClaude Opus 5.5 fc99200d73 Take a snapped point's Z from the object it snapped to
The Z of a snapped point came from a fresh pick at the snapped XY, so a
snap whose point lies off the object missed it: CEN of a circle at
z = 5, picked near its center, gave ELEVATION instead of 5. With two
objects under an intersection, the pick returned whichever was on top.

A snap hit now records the entity its candidate came from, and the
point takes that entity's Z at the snapped point. An intersection takes
the first of its two objects (in drawing order). Where a snap has no
source, the pick at the point is still used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 10:51:01 -06:00
Aldo ZarateandClaude Opus 5.5 bbfcd27d6c Keep the next point's Z after a deferred LINE start
A LINE started with a deferred tangent or perpendicular drew its first
segment flat: typing `10,10,5` after `tan` on a circle ended the line at
z = 0, while the same point typed after a plain start kept z = 5. The
deferred start still lies on the curve at z = 0, but the point that
resolves it now keeps its typed or snapped Z, and the next segment
starts from there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 10:48:36 -06:00
Aldo Zarate a3243c96be Merge remote-tracking branch 'upstream/main' into feat/snap-z 2026-10-29 10:47:17 -06:00
Dievartis d23c4726de Fix autocomplete suggestion execution and add keyboard tests 2026-10-29 08:45:01 +01:00
Dievartis f60b174711 Fix command suggestion navigation review findings 2026-10-29 07:55:39 +01:00
Dievartis 4e58f46423 Fix keyboard navigation for command suggestions 2026-10-28 15:01:17 +01:00
Dievartis 5daebac3b5 Add Shift+Arrow navigation for command suggestions 2026-10-28 14:05:05 +01:00
SBaksa ea87dafb99 Parity checklist: regenerated after merging main 2026-10-28 19:29:23 +11:00
SBaksa 53b8a64871 Interface fonts: rescan names after an in-place edit, keep one language's fonts, read the CJK font for Hangul only when a name needs it
doc_mut now bumps the drawing's revision: a drawing nothing else holds is edited in place, so the
name-script cache (keyed by the drawing pointer) missed the edit. The language-font cache keeps the
last language only, so trying several interface languages doesn't hold a copy of the large font
files for each. cjk_covers_hangul reads the whole CJK collection the first time; it is now asked
only when a name needs Hangul.
2026-10-28 18:18:05 +11:00
SBaksa cf9a63c92f Merge remote-tracking branch 'origin/main' into ui-font-scripts-local 2026-10-27 17:53:58 +11:00
SBaksa d8c2c4cb4c Merge remote-tracking branch 'fork/ui-font-scripts' into ui-font-scripts-local
# Conflicts:
#	crates/ui-egui/src/lib.rs
#	crates/ui-egui/src/theme.rs
2026-10-27 17:53:57 +11:00
SBaksa 939fec385c Interface fonts: read a face's bytes through egui 0.37's shared font data 2026-10-27 16:54:23 +11:00
Claude 36c14239cc Interface fonts: read the primary face's bytes through egui's shared font data 2026-10-27 01:51:12 +00:00
Aldo Zarate 7eaf0c3104 Merge remote-tracking branch 'upstream/main' into feat/snap-z
# Conflicts:
#	crates/engine/src/cmd/draw.rs
#	crates/engine/src/cmd/draw2.rs
#	crates/engine/src/lib.rs
2026-10-26 19:40:52 -06:00
Claude 77bc4dba9e Merge remote-tracking branch 'upstream/main' into ui-font-scripts
# Conflicts:
#	crates/ui-egui/src/lib.rs
#	crates/ui-egui/src/theme.rs
2026-10-27 01:09:19 +00:00
SBaksa f2c849273c Merge remote-tracking branch 'origin/main' into ui-font-scripts-local
# Conflicts:
#	crates/ui-egui/src/lib.rs
#	crates/ui-egui/src/theme.rs
2026-10-27 11:32:45 +11:00
Aldo ZarateandClaude Opus 5.5 26fe7656af A point from a LISP expression keeps its Z at point prompts
A LISP expression answering a point prompt passed only X and Y on, so `(list 1 2 7)` at LINE
gave a point at z = 0. It now keeps the third number as the point's Z, as a typed `x,y,z` does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 07:20:43 -06:00
Aldo ZarateandClaude Opus 5.5 0056d148fe Merge upstream/main into feat/snap-z
Keeps main's MEASUREINIT with the 3D LASTPOINT, and both changelog rows; the snap Z test moves
into tests/it (one test binary per crate, #1989).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 00:06:13 -06:00
SBaksa ca87d3acd1 Interface fonts: reuse the language's fonts when a name's script changes
install_fonts_for keeps the fonts read for each interface language
(cached_language_fonts; a clone shares their Arcs), so installing again
for a name's script, or when its face arrives, no longer reads the UI and
CJK font files on the UI thread again.
2026-10-21 03:42:02 +11:00
SBaksa cc50a8c3c5 Interface fonts for the scripts of the names shown, on top of install_fonts
Rebuilt on main's theme::install_fonts (#861, #513), which loads CJK faces
for every interface language and Korean or Arabic for those interfaces.
Names the interface shows (drawing titles and their layers, layouts and
blocks) can still need a script the language's fonts don't cover: a
Korean layer name in an English interface, a Thai, Devanagari, Arabic or
Hebrew drawing name.

install_fonts_for(ctx, language, names) adds a face for each such script,
found the way drawing text finds one (ttf::fallback_for). Faces are looked
for off the UI thread and kept for the process; fonts_generation() changes
when they're ready and the app installs again. The app scans the names
again only when a drawing changes, opens or closes. install_fonts keeps
its behaviour (no names).
2026-10-20 17:18:45 +11:00
SBaksa 1811abc66b Merge remote-tracking branch 'origin/main' into ui-font-scripts-local
# Conflicts:
#	contributors/people.toml
#	crates/ui-egui/src/lib.rs
#	crates/ui-egui/src/theme.rs
2026-10-20 15:57:15 +11:00
Aldo ZarateandClaude Opus 5.5 5b26e817d8 A one-off snap under M2P gives its point the snapped Z
A snap typed for an M2P point (M2P, NOD, then the point) snapped the X and Y but kept the earlier
Z, so the midpoint lay at the wrong level. It now takes the Z of what it snapped to, as a snapped
pick does (OSNAPZ-aware). The Z a point modifier gives is also dropped once the point is used,
so the next plain point starts at z = 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 17:43:03 -06:00
Aldo ZarateandClaude Opus 5.5 15b99d94ba M2P is midway in Z too
The midpoint between two snapped points kept the second point's Z. The M2P frame now keeps the
first point's Z and gives the midpoint the average of both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 17:25:44 -06:00
Aldo ZarateandClaude Opus 5.5 50a7e7a3da Merge upstream/main into feat/snap-z
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 16:29:58 -06:00
Aldo ZarateandClaude Opus 5.5 324e3f4e97 Merge upstream/main into feat/snap-z
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 01:04:12 -06:00
Aldo ZarateandClaude Opus 5.5 d28ba1ce33 Object snaps give points their Z; LINE and POINT keep it (OSNAPZ)
Points reach commands in 2D, so a line drawn between a survey point and
a contour lay at z = 0 whatever their levels. An object snap now gives
the point the Z of what it snapped to (the object a pick finds there, as
ID reads it), through Session::point_z, as AutoCAD does with OSNAPZ 0;
OSNAPZ 1 uses the current elevation. A point picked through a layout
viewport, or without a snap, stays at z = 0.

LINE and POINT build their points with point_z, so they keep a typed Z
as well as a snapped one (3DPOLY already did).

Stacked on #1431 (Session::point_z) and #1509 (z_at).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:15:24 -06:00
Aldo Zarate f6124ce296 Merge branch 'feat/inquiry-z' into feat/snap-z 2026-10-17 08:08:39 -06:00
Aldo ZarateandClaude Opus 5.5 f197952a9c ID, DIST and LIST report Z
ID always printed Z = 0, DIST's Delta Z and angle from the XY plane were
0, and LIST printed Z = 0 for lines, circles, arcs and polyline vertices,
though the drawing kept every Z: a topographic drawing's levels could not
be read in CADCraft.

Points reach these commands in 2D, so the Z is that of what is drawn at
the point, as AutoCAD reports a snapped point's: the object a pick finds
there (a point, a 3D line or 3D polyline interpolated, a polyline's
elevation, down Z for a mirrored one, a circle, arc, text, block or the
plane of a 3D face), else the current elevation (ELEVATION). A Z given
with a JSON point wins. DIST gives the 3D distance, Delta Z and the angle
from the XY plane; LIST the Z of lines, circles, arcs and text, a line's
3D length and deltas, and a polyline's elevation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 07:54:52 -06:00
Gert Pellin fbee9d6f5e Docs: typed points keep their Z, and so do 3DPOLY's typed vertices (#1409, #1410) 2026-10-16 10:36:57 +02:00
Gert Pellin 246f13b5a7 Command line: a typed point keeps its Z, and 3DPOLY draws with it (#1409, #1410)
parse_point_with parsed the third number of x,y,z and dropped it, so no
typed Z reached a command, and the interactive 3DPOLY lifted every
point to z = 0.

parse_point3_with keeps Z (absolute x,y,z; relative @dx,dy,dz adds to
the last point's Z, @dx,dy keeps it, as in AutoCAD); parse_point_with
keeps its Vec2 signature for its callers. The session gives commands
the Z of the point being entered (Session::point_z, 0 for a pick) and
remembers LASTPOINT's Z. Poly3dM stores Vec3, so typed vertices keep
their Z and a vertex straight above the last one is no longer dropped
as a repeat.
2026-10-16 10:29:58 +02:00
Marco Arnulfo fd11cc7c6a Rays and xlines: cut points measured from the base, not from 1e8 away
An xline was cut as the segment base - dir*1e8 .. base + dir*1e8, so every cut point came
out of (-1e8) + 2e8*t, about 1e-8 off even near the origin. A ray left by TRIM then started
just before its edge, and a second TRIM saw that edge as a cut and left a ~2e-9 line behind.

TRIM now cuts an xline as two half-lines from its base, and FILLET and CHAMFER take the
half-line towards the picked side, so the corner is found from the base.
2026-10-14 18:35:49 +02:00
Marco Arnulfo 2ca02bf87d EXTEND on rays: the base moves back to the nearest edge (fixes #1236) 2026-10-14 18:11:58 +02:00
Marco Arnulfo ab61236574 TRIM, FILLET and CHAMFER on rays and xlines: a finite piece becomes a line, an unbounded one a ray (fixes #1235) 2026-10-14 18:11:58 +02:00
SBaksa 17b5b06a78 Interface fonts for every script a shown name needs, loaded off the UI thread
Builds on #732. The interface loaded one CJK font, read on the UI thread
whenever a drawing name needed it and read again each time a drawing
needing it opened after none did; Korean names and names elsewhere (layers,
layouts, blocks) still showed boxes.

install_fonts now takes the scripts interface text needs (Chinese/Japanese,
Hangul, Thai, Devanagari, Arabic, Hebrew), from the interface language and
the names of drawings, layers, layouts and blocks; the names are scanned
again only when a drawing changes, opens or closes. Chinese prefers
cjk_font() as before; other scripts, and Chinese without it, take the
installed font drawing text would use (ttf::fallback_for). Faces are found
off the UI thread and kept for the process, so a script shown again never
re-reads a file, and egui shares the cached font data instead of a copy per
install. Scripts the UI font already has load nothing.
2026-10-12 22:50:58 +11:00
NetterSilver 876f6ccef9 Add my contributor entry 2026-10-12 10:45:22 +02:00
NetterSilver 9ae49fe1df Load the CJK font while an open drawing's name needs it (#658)
The CJK interface font was only loaded for the Chinese interface, so a
drawing named in Chinese, Japanese or Korean showed boxes in its tab and
title with any other interface language. The font is now also loaded
while an open drawing's title has CJK characters, and dropped again when
none does.
2026-10-12 10:37:59 +02:00
176 changed files with 15306 additions and 1244 deletions
+34
View File
@@ -0,0 +1,34 @@
name: Cache prune
# Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache
# budget, where GitHub evicts entries a run still needs. Each main CI attempt's `cache warm` leg
# saves a new rolling entry; this deletes the entry it replaced once the attempt ends. It runs once
# after every attempt, re-runs of failed jobs and canceled runs included (craft-common-actions
# actions/cache-prune).
on:
workflow_run:
workflows: [CI]
types: [completed]
branches: [main]
permissions:
contents: read
jobs:
cache-prune:
name: cache prune
# A fork's pull request from a branch named main also matches `branches`.
if: github.event.workflow_run.event == 'push' && github.event.workflow_run.head_branch == 'main' && github.event.workflow_run.head_repository.full_name == github.repository
timeout-minutes: 10
runs-on: ubuntu-24.04
permissions:
actions: write
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
# A failed pass warns; the next run's prune deletes what it missed.
- name: Prune replaced cache entries
uses: storytold/craft-common-actions/actions/cache-prune@b2726eb1defb6eccdfad920cc6988e1e3ec1c3c9 # main
continue-on-error: true
+8 -1
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`. |
@@ -84,13 +90,14 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/sv.tsv` | Erik Holmbom (@holmbom) with Claude Code (AI-assisted) | Original Swedish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the running app reviewed by a native speaker |
| `crates/ui-egui/src/i18n/it.tsv` | Emanuele Bottelli (AI-assisted); terminology corrections: Andrea Brandi (@starise) with OpenAI Codex (AI-assisted) | Original Italian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; targeted Chamfer terminology review by a native speaker |
| `crates/ui-egui/src/i18n/ko.tsv` | @huk082 (AI-assisted) | Original Korean translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; no font assets added |
| `crates/ui-egui/src/i18n/ar.tsv` | @hasan-sdaif | Original Arabic translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/ar.tsv` | @hasan-sdaif; missing rows and the Find and Replace dialog: Saleh Hassan Alnemari (@salehnemari-max) with Claude Code (AI-assisted) | Original Arabic translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the added rows reviewed line by line by the translator, a native speaker |
| `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted); 870 later rows: @HolyZephyros (AI-assisted) | Original Turkish translations of CADCraft English strings (original catalog by @ogzhnklvz; 870 later rows written from CADCraft's English strings in #3291) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app for the original catalog was reviewed by a native speaker; the 870 rows added in #3291 have not yet been reviewed by a native speaker |
| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted); 46 later rows: @V1dalTheAbidal with Claude Code (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the 46 later rows were read by their contributor, a native Greek speaker; independent native proofreading of the whole file pending |
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the craft-i18n#401 phase 1 changes reviewed by a native Vietnamese speaker; older rows not yet proofread in full |
| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) |
| `crates/ui-egui/src/i18n/ta.tsv` | @newsbaba24x7 (AI-assisted) | Original Tamil translations of CADCraft English strings, shared with storytold/craft-i18n `locales/ta/` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings; the 1,289 rows from craft-i18n reviewed there for language and terminology by native speakers, and the whole Tamil interface reviewed in the running app by native speakers Radhika and Mohan Raj (2026-11-14); no font assets added (Tamil comes from an installed font or the craft-fonts face) |
| `crates/ui-egui/src/i18n/he.tsv` | Hagai Baram (@hrb9), AI-assisted; shared `craft-i18n#42` rows include contributions by @nocturney with ChatGPT (AI-assisted) | Original Hebrew translations of CADCraft English strings (1,444 rows shared with [storytold/craft-i18n#42](https://github.com/storytold/craft-i18n/pull/42) at `fdff86e3`, `locales/he/common.tsv` and `locales/he/cadcraft.tsv`, plus 443 additional CADCraft UI strings) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | Clean-room translations written from the plain meaning of CADCraft's English strings; no proprietary localization resources copied; terminology and the running app reviewed by @hrb9 (a native Hebrew speaker), while independent line-by-line proofreading by a second native speaker remains pending; no font assets added (Hebrew uses an installed system font or the optional `craft-fonts` face) |
## PDF import
Generated
+219 -85
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"
@@ -445,7 +468,7 @@ checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
]
[[package]]
@@ -480,7 +503,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
]
[[package]]
@@ -705,7 +728,7 @@ checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
]
[[package]]
@@ -744,10 +767,10 @@ dependencies = [
"fmv-macos-events",
"hidapi",
"log",
"muda",
"muda 0.22.0",
"objc2-app-kit 0.3.2",
"pollster 1.0.1",
"rfd",
"pollster",
"rfd 0.18.0",
"ron",
"serde",
"serde_json",
@@ -838,9 +861,9 @@ dependencies = [
"craft-font-catalog",
"craft-shx",
"encoding_rs",
"harfrust 0.14.0",
"harfrust 0.16.2",
"icu_segmenter",
"skrifa 0.48.0",
"skrifa 0.50.0",
"unicode-bidi",
]
@@ -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",
@@ -888,11 +911,9 @@ dependencies = [
"craft-jsonrpc",
"craft-mcp",
"getrandom 0.4.3",
"hmac",
"libc",
"log",
"serde_json",
"sha2",
"tiny-skia",
]
@@ -961,6 +982,7 @@ dependencies = [
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-bindgen-test",
"web-sys",
]
@@ -1024,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"
@@ -1113,9 +1141,9 @@ dependencies = [
[[package]]
name = "clap"
version = "4.6.7"
version = "4.6.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3"
dependencies = [
"clap_builder",
"clap_derive",
@@ -1123,9 +1151,9 @@ dependencies = [
[[package]]
name = "clap_builder"
version = "4.6.7"
version = "4.6.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590"
dependencies = [
"anstream",
"anstyle",
@@ -1135,23 +1163,23 @@ dependencies = [
[[package]]
name = "clap_complete"
version = "4.6.11"
version = "4.6.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f"
checksum = "6a35200383f20018d41c14d1ab19c1727c697f544492143f7d93aa39f0187848"
dependencies = [
"clap",
]
[[package]]
name = "clap_derive"
version = "4.6.7"
version = "4.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
]
[[package]]
@@ -1162,9 +1190,9 @@ checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
[[package]]
name = "clap_mangen"
version = "0.3.3"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "211d617eaa4b735c96c9e0228fcbdb5120ef623f2b8cb67ffb84c3e02dbc28a4"
checksum = "a3b6a8907b1723f211693e27b9af5899b86a9512ef5b08bd4a15b6bceb30da6d"
dependencies = [
"clap",
"roff",
@@ -1429,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",
]
@@ -1633,7 +1661,7 @@ dependencies = [
"js-sys",
"log",
"objc2-app-kit 0.3.2",
"rfd",
"rfd 0.17.2",
"serde",
"serde_json",
"wasm-bindgen",
@@ -1957,7 +1985,7 @@ dependencies = [
"craft-settings",
"craft-win32",
"egui",
"muda",
"muda 0.21.2",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
@@ -2077,7 +2105,6 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
"subtle",
]
[[package]]
@@ -2127,7 +2154,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
]
[[package]]
@@ -2253,7 +2280,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"parking_lot",
"percent-encoding",
"pollster 1.0.1",
"pollster",
"profiling",
"raw-window-handle",
"ron",
@@ -2374,7 +2401,7 @@ dependencies = [
"kittest",
"log",
"open",
"pollster 1.0.1",
"pollster",
"serde",
"tempfile",
"toml",
@@ -2410,9 +2437,9 @@ checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d"
[[package]]
name = "encoding_rs"
version = "0.8.42"
version = "0.8.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679"
checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5"
dependencies = [
"cfg-if",
"core_detect",
@@ -2445,7 +2472,7 @@ checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
]
[[package]]
@@ -2725,7 +2752,7 @@ checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
]
[[package]]
@@ -2776,7 +2803,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
]
[[package]]
@@ -3080,14 +3107,15 @@ dependencies = [
[[package]]
name = "harfrust"
version = "0.14.0"
version = "0.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86aa776d6d32b072119e1f1650f4db843ff4382a4aaa6a2c9c4e35703cd377cb"
checksum = "d29463af2039b1bd7ccf60cb9f11fafbfe14b18ab6fb1790dab57aba456e155f"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"read-fonts 0.45.1",
"read-fonts 0.47.0",
"smallvec",
"yoke",
]
[[package]]
@@ -3202,9 +3230,9 @@ dependencies = [
[[package]]
name = "heapless"
version = "0.8.0"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad"
checksum = "411fdef4df93751117bd9ef8caa0e7f99c65dafec5bd84313eb8e2fdd75e32f2"
dependencies = [
"hash32",
"stable_deref_trait",
@@ -3243,15 +3271,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest",
]
[[package]]
name = "http"
version = "1.5.0"
@@ -4016,9 +4035,9 @@ dependencies = [
[[package]]
name = "log"
version = "0.4.34"
version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "lyon_geom"
@@ -4076,6 +4095,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"
@@ -4130,6 +4159,24 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "muda"
version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a775675be5389020a44c56efbdf3bbea8b97f47dfdd325e6c5c5213797a7e0aa"
dependencies = [
"crossbeam-channel",
"dpi",
"keyboard-types",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"png",
"thiserror 2.0.21",
"windows-sys 0.61.2",
]
[[package]]
name = "multiversion"
version = "0.8.1"
@@ -4160,9 +4207,9 @@ checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
[[package]]
name = "naga"
version = "30.0.1"
version = "30.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130"
checksum = "fd0dd362bf26c0ffdd143df6da66a25d287e196eff482f117771010b207ad163"
dependencies = [
"arrayvec",
"bit-set",
@@ -4275,6 +4322,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"
@@ -4373,6 +4429,7 @@ dependencies = [
"objc2-core-video",
"objc2-foundation 0.3.2",
"objc2-quartz-core 0.3.2",
"objc2-uniform-type-identifiers 0.3.2",
]
[[package]]
@@ -4749,7 +4806,7 @@ dependencies = [
"objc2-link-presentation",
"objc2-quartz-core 0.2.2",
"objc2-symbols",
"objc2-uniform-type-identifiers",
"objc2-uniform-type-identifiers 0.2.2",
"objc2-user-notifications",
]
@@ -4776,6 +4833,16 @@ dependencies = [
"objc2-foundation 0.2.2",
]
[[package]]
name = "objc2-uniform-type-identifiers"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7902ac02859fc1f7045f8b598c63f1ae0cc7efeaa06a9bc9f3d9a3c955974fa4"
dependencies = [
"objc2 0.6.5",
"objc2-foundation 0.3.2",
]
[[package]]
name = "objc2-user-notifications"
version = "0.2.2"
@@ -4810,6 +4877,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"
@@ -5167,15 +5240,9 @@ dependencies = [
[[package]]
name = "pollster"
version = "0.4.0"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"
[[package]]
name = "pollster"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336"
checksum = "7e9b9cf600136f5b976fbc5727d58c26e1ecab8ee23088d44ef1c7af793550ab"
[[package]]
name = "polycool"
@@ -5426,14 +5493,15 @@ dependencies = [
[[package]]
name = "read-fonts"
version = "0.45.1"
version = "0.47.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4edc8db0d972de88e53a085b1f01fb3fbdae7bb0cb7a0ce2b2f8285a412fe3ef"
checksum = "a39d2f8f681030a7bcbbcf3e8568775ac2393afd51401a2e2133ee89e3953897"
dependencies = [
"bytemuck",
"foldhash 0.2.0",
"font-types 0.12.7",
"once_cell",
"smallvec",
"yoke",
]
@@ -5540,7 +5608,31 @@ dependencies = [
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"percent-encoding",
"pollster 0.4.0",
"raw-window-handle",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"windows-sys 0.61.2",
]
[[package]]
name = "rfd"
version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4b9d4857b10297ffb0f64cae711e983a7aeaee561848d56d429d3858bd8ed93"
dependencies = [
"block2 0.6.2",
"dispatch2",
"js-sys",
"libc",
"log",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"objc2-uniform-type-identifiers 0.3.2",
"percent-encoding",
"pollster",
"raw-window-handle",
"wasm-bindgen",
"wasm-bindgen-futures",
@@ -5582,12 +5674,11 @@ checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189"
[[package]]
name = "ron"
version = "0.12.2"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81116b9531d61eabc41aeb228e4b6b2435bcca3233b98cf3b3077d4e6e9debb3"
checksum = "97b3fe97c18ff24299ea56f802c5693eb34266fb0bc8317f4e101debc8a3ceaf"
dependencies = [
"bitflags 2.13.2",
"once_cell",
"serde",
"serde_derive",
"typeid",
@@ -5605,12 +5696,13 @@ dependencies = [
[[package]]
name = "rstar"
version = "0.13.0"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5912b862fa5ffb462607bfd1e35036c458c537921f508c8235a83d5f3987edfe"
checksum = "d95c33d01e9acee7be3363f99e9ef88b1a587186e81e03843fbe39d77d9a0c1f"
dependencies = [
"heapless",
"num-traits",
"ordered-float",
"smallvec",
]
@@ -5849,7 +5941,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
]
[[package]]
@@ -5873,7 +5965,7 @@ checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
]
[[package]]
@@ -5987,12 +6079,15 @@ dependencies = [
[[package]]
name = "skrifa"
version = "0.48.0"
version = "0.50.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5213b4825bac3587046330052d61bfac7bd3bd0d203c758d7c2ef726fcea034"
checksum = "e85ba678a6023a063d0a78c8770f1c166674ef46af13523d05eff67430f79dfe"
dependencies = [
"bytemuck",
"read-fonts 0.45.1",
"once_cell",
"read-fonts 0.47.0",
"smallvec",
"yoke",
]
[[package]]
@@ -6179,9 +6274,9 @@ dependencies = [
[[package]]
name = "syn"
version = "3.0.9"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
@@ -6196,7 +6291,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
]
[[package]]
@@ -6305,7 +6400,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
]
[[package]]
@@ -6823,7 +6918,7 @@ dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
"wasm-bindgen-shared",
]
@@ -6836,6 +6931,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.10",
]
[[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"
@@ -7722,7 +7856,7 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
"synstructure",
]
@@ -7794,7 +7928,7 @@ dependencies = [
"proc-macro-crate",
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
"zbus_names",
"zvariant",
"zvariant_utils",
@@ -7869,7 +8003,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
"synstructure",
]
@@ -7913,7 +8047,7 @@ checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
]
[[package]]
@@ -8001,7 +8135,7 @@ dependencies = [
"proc-macro-crate",
"proc-macro2",
"quote",
"syn 3.0.9",
"syn 3.0.10",
"zvariant_utils",
]
@@ -8014,6 +8148,6 @@ dependencies = [
"proc-macro2",
"quote",
"serde",
"syn 3.0.9",
"syn 3.0.10",
"winnow",
]
+4 -3
View File
@@ -61,10 +61,10 @@ rayon = "1"
# rendering / formats
tiny-skia = { version = "0.12", default-features = false, features = ["std", "simd", "png-format"] }
lyon_tessellation = "1.0.22"
skrifa = "0.48"
skrifa = "0.50"
# Text shaping (OpenType GSUB/GPOS, HarfBuzz port on read-fonts; egui's epaint is still on 0.12,
# so the graph has both) and the Unicode Bidirectional Algorithm for right-to-left drawing text.
harfrust = "0.14"
harfrust = "0.16"
unicode-bidi = "0.3.18"
# Line-break opportunities between Thai words for MTEXT word wrap (Thai writes no spaces between
# words): UAX #14 with ICU4X's compiled-in LSTM word model (not its dictionaries).
@@ -85,13 +85,14 @@ 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).
web-time = "1.1"
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
rfd = "0.17"
rfd = "0.18"
arboard = { version = "3.6", default-features = false }
[workspace.lints.rust]
+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.
+1 -1
View File
@@ -124,7 +124,7 @@ numbers):
| Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF |
| Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit |
| Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror |
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski), Georgian (ქართული) and Tamil (தமிழ், with an installed Tamil font), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski), Georgian (ქართული), Tamil (தமிழ், with an installed Tamil font), Dutch (Nederlands) and European Portuguese (Português (Portugal)) (catalogs in `storytold/craft-i18n`; fall back to English until embedded), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
| Automation | MCP server, JSON control channel, `cadcraft-cli` (info, convert, run, commands, mcp) |
## Quick start
+2 -2
View File
@@ -16,7 +16,7 @@ CADCraft treats these as untrusted, and a way past these defences is a vulnerabi
- **Drawing files.** Opening a DXF, DWG or other file must not run code, write outside the paths the user chose, or crash the app. Panics are bugs too, but memory exhaustion or a decoder abort on a crafted file is the more serious case.
- **AutoLISP in a drawing's folder.** A drawing must not run code that the user didn't choose to load.
- **The control channel.** It listens on loopback only and needs the session token from an owner-only file on every request. Another local account reaching it without that token is a vulnerability. The MCP bridge sends requests only to a server that proves it holds the token, so a program listening on the port in the app's place gets none.
- **The control channel.** It listens on loopback only and needs the session token from an owner-only file on every request. Another local account reaching it without that token is a vulnerability.
- **Temporary and autosave files.** Autosave files are unsaved drawings: another account must not be able to read them or redirect a write through them.
- **Updates.** A release must not be replaceable by someone other than the project.
@@ -25,7 +25,7 @@ CADCraft treats these as untrusted, and a way past these defences is a vulnerabi
These are known and being worked on, so they don't need a report:
- Agents connected through MCP or the control channel can read and write any path the user can. There are no workspace roots yet.
- A local process without the token can hold the control channel's 16 connections for up to 10 seconds at a time, with at most 64 KiB of request line each, so it can keep an agent from reaching the app while it keeps reconnecting. It can't make the app run anything.
- A local process can make the control channel buffer up to 512 MiB before its token is checked. The total is capped, so this can slow the app but not exhaust memory without limit.
- The DWG worker process has no memory limit of its own yet, so a crafted file can use a lot of memory before it stops. It ends that one open or save, not the app.
- The web build has no autosave yet.
-10
View File
@@ -60,19 +60,10 @@ fn no_connect_still_serves_headless() {
fn connect_with_address_routes_to_that_endpoint() {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback");
let addr = listener.local_addr().expect("local addr").to_string();
let port = listener.local_addr().expect("local addr").port();
// As the app does: write the session token, and prove holding it when the bridge says hello.
let token = cadcraft_mcp::control_token::issue(port).expect("issue token");
let server = std::thread::spawn(move || {
let (conn, _) = listener.accept().expect("accept");
let mut reader = BufReader::new(conn.try_clone().expect("clone"));
let mut line = String::new();
reader.read_line(&mut line).expect("read hello");
let hello: Value = serde_json::from_str(&line).expect("json hello");
assert_eq!(hello["method"], "hello", "the bridge says hello first: {line}");
let proof = cadcraft_mcp::control_token::server_proof(&token, hello["params"]["nonce"].as_str().unwrap_or_default());
writeln!(&conn, "{}", json!({"id": hello["id"], "ok": true, "result": {"proof": proof}})).expect("write proof");
line.clear();
reader.read_line(&mut line).expect("read request");
let req: Value = serde_json::from_str(&line).expect("json request");
let reply = json!({"id": req["id"], "ok": true, "result": {"fixture": "loopback"}});
@@ -84,7 +75,6 @@ fn connect_with_address_routes_to_that_endpoint() {
let out = mcp(&["--connect", &addr], &format!("{INIT}\n{call}\n"));
assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
let req = server.join().expect("server thread");
cadcraft_mcp::control_token::revoke(port);
assert_eq!(req["method"], "ui.inspect");
let r = replies(&out);
let instructions = r.iter().find(|v| v["id"] == 1).and_then(|v| v["result"]["instructions"].as_str()).unwrap_or_default();
+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)) {
+1 -1
View File
@@ -51,7 +51,7 @@ rfd = { workspace = true }
sys-locale = "0.3"
[target.'cfg(target_os = "macos")'.dependencies]
muda = { version = "0.21", default-features = false }
muda = { version = "0.22", default-features = false }
# Quit CADCraft as a close request of the main window, so the unsaved-changes question runs (#2157).
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: the system's Reduce motion
+6 -155
View File
@@ -5,19 +5,15 @@
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
//! closed, so nothing sent after it runs. Every resource a client can hold is bounded
//! ([`Limits`]): simultaneous connections, request line length (shorter until a request on the
//! connection has carried the token), queued requests, how long a connection may stay open before
//! it has shown the token, and how long a socket may sit idle or blocked on a write.
//!
//! A `hello` with a nonce is answered before the token check with a proof that the server holds
//! the token ([`cadcraft_mcp::control_token::server_proof`]), so a client can tell the app from
//! another program on the port before it sends anything else (#1925).
//! connection has carried the token), queued requests, and how long a socket may sit idle or
//! blocked on a write.
use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
use std::io::{BufRead, BufReader, ErrorKind, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{Receiver, SyncSender, TrySendError, sync_channel};
use std::time::{Duration, Instant};
use std::time::Duration;
use cadcraft_ui_egui::ControlRequest;
use serde_json::{Value, json};
@@ -37,9 +33,6 @@ struct Limits {
total_bytes: usize,
/// Requests waiting for the app at once; more are answered `busy`.
queue: usize,
/// How long a connection may stay open before a request on it has carried the right token; it
/// is closed then, so peers without the token can't hold the connection slots (#1925).
preauth_time: Duration,
/// How long a connection may go without sending a byte before it is closed.
idle_timeout: Duration,
/// How long a reply write may block before the connection is closed.
@@ -58,7 +51,6 @@ impl Default for Limits {
// Room for one maximal request plus smaller ones, not `max_clients` maximal ones.
total_bytes: 512 * 1024 * 1024,
queue: 64,
preauth_time: cadcraft_mcp::control_token::MAX_UNAUTHENTICATED_TIME,
idle_timeout: Duration::from_secs(600),
write_timeout: Duration::from_secs(30),
reply_timeout: Duration::from_secs(60),
@@ -346,47 +338,6 @@ fn is_http_request_line(text: &str) -> bool {
|| text.rsplit_once(' ').is_some_and(|(_, version)| version.starts_with("HTTP/"))
}
/// The method a client sends, before any request with the token, to have the server prove it holds
/// the token.
const HELLO: &str = "hello";
/// `hello`'s parameters.
#[derive(serde::Deserialize)]
struct HelloParams {
nonce: String,
}
/// The proof answering a `hello` with `params`, or the error that closes the connection.
fn hello_proof(params: Option<&serde_json::value::RawValue>, token: &str) -> Result<String, String> {
let nonce = params.and_then(|p| serde_json::from_str::<HelloParams>(p.get()).ok()).map(|p| p.nonce).unwrap_or_default();
if !cadcraft_mcp::control_token::valid_nonce(&nonce) {
let digits = &cadcraft_mcp::control_token::NONCE_DIGITS;
return Err(format!("`hello` needs a `nonce` of {} to {} hexadecimal digits; closing the connection", digits.start(), digits.end()));
}
Ok(cadcraft_mcp::control_token::server_proof(token, &nonce))
}
/// A connection's read side. Until `until` (the end of [`Limits::preauth_time`]), each read waits
/// at most until then, however the bytes trickle in; after it, reads fail as timed out.
struct Timed {
stream: TcpStream,
idle: Duration,
until: Option<Instant>,
}
impl Read for Timed {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if let Some(until) = self.until {
let left = until.saturating_duration_since(Instant::now());
if left.is_zero() {
return Err(std::io::Error::new(ErrorKind::TimedOut, "no request with the control token in time"));
}
self.stream.set_read_timeout(Some(left.min(self.idle)))?;
}
self.stream.read(buf)
}
}
/// Serve bounded JSON lines, authenticating each request before enqueueing it for the UI.
/// Invalid credentials close the connection; queue and reply limits report whether a request ran.
fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context, limits: Limits, token: &str, budget: Budget) {
@@ -395,8 +346,7 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
}
let Ok(read) = stream.try_clone() else { return };
let mut out = stream;
let until = Instant::now().checked_add(limits.preauth_time);
let mut reader = BufReader::new(Timed { stream: read, idle: limits.idle_timeout, until });
let mut reader = BufReader::new(read);
let mut buf = Vec::new();
let mut held = Held::new(budget);
// The token is checked only after the whole line is read, so until a request here has carried
@@ -418,17 +368,6 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
Ok(true) => match parse_line(&buf) {
Line::Blank => continue,
Line::Reject(e) => e,
// Answered without the token and without authenticating the connection: the proof
// shows the token is known here, not that the peer knows it.
Line::Request { id, method, params, .. } if method == HELLO => match hello_proof(params, token) {
Ok(proof) => {
if writeln!(out, "{}", json!({"id": id, "ok": true, "result": {"proof": proof}})).is_err() {
break;
}
continue;
}
Err(e) => e,
},
Line::Request { id, method, params, token: given } => {
// Authenticate the peer before dispatching: loopback TCP does not identify the
// OS user, so only a client holding the owner-only session token may drive the
@@ -441,14 +380,7 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
let _ = writeln!(out, "{r}");
break;
}
if !authenticated {
authenticated = true;
let timed = reader.get_mut();
timed.until = None;
if timed.stream.set_read_timeout(Some(limits.idle_timeout)).is_err() {
break;
}
}
authenticated = true;
// Absent `params` is `{}`; ones that cannot be decoded (an unpaired surrogate escape) are an
// error, not a request run with defaults.
let params = match params.map(|r| serde_json::from_str::<Value>(r.get())) {
@@ -812,87 +744,6 @@ mod tests {
assert_eq!((v["ok"].as_bool(), v["method"].as_str()), (Some(true), Some("ping")), "{line}");
}
/// A `hello` line with `nonce` and no token.
fn hello_line(nonce: &str) -> String {
json!({"id": "h", "method": "hello", "params": {"nonce": nonce}}).to_string() + "\n"
}
/// A `hello` is answered with a proof of the token before any token has been shown, and the
/// connection stays open for requests; the `hello` itself authenticates nothing.
#[test]
fn a_hello_is_answered_with_a_proof_of_the_token() {
let addr = serve_echo_with(preauth());
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut r = BufReader::new(c.try_clone().unwrap());
let nonce = cadcraft_mcp::control_token::new_nonce().unwrap();
c.write_all(hello_line(&nonce).as_bytes()).unwrap();
let mut line = String::new();
r.read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!(v["id"], "h", "{line}");
let proof = v["result"]["proof"].as_str().unwrap();
assert!(cadcraft_mcp::control_token::verify_server_proof(TEST_TOKEN, &nonce, proof), "{line}");
assert!(!line.contains(TEST_TOKEN), "the token itself is never sent");
// Still unauthenticated: a line past the preauth bound is refused…
let refused = exchange(addr, format!("{}{}", hello_line(&nonce), long_req_line(1, 2000)).as_bytes());
assert_eq!(refused.len(), 2, "{refused:?}");
assert!(refused[1]["error"].as_str().unwrap().contains("longer than 1000 bytes"), "{refused:?}");
// …and a request with the token after the hello goes through on the same connection.
c.write_all(req_line(2, "ping").as_bytes()).unwrap();
line.clear();
r.read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!((v["id"].as_i64(), v["method"].as_str()), (Some(2), Some("ping")), "{line}");
}
/// A `hello` without a usable nonce gets an error and the connection is closed.
#[test]
fn a_hello_without_a_usable_nonce_closes_the_connection() {
let addr = serve_echo();
for bad in [r#"{"method":"hello"}"#.to_string(), hello_line("abc").trim_end().to_string(), hello_line(&"z".repeat(64)).trim_end().to_string()]
{
let replies = exchange(addr, format!("{bad}\n{}", req_line(1, "ping")).as_bytes());
assert_eq!(replies.len(), 1, "{bad}: {replies:?}");
assert!(replies[0]["error"].as_str().unwrap().contains("`nonce`"), "{bad}: {replies:?}");
}
}
/// A connection that doesn't show the token within `preauth_time` is closed even while it keeps
/// sending (a byte at a time, or `hello`s), so peers without the token can't hold the slots;
/// one that has shown it stays open past that time.
#[test]
fn a_connection_that_never_shows_the_token_is_closed_in_time() {
let limits = Limits { preauth_time: Duration::from_millis(400), idle_timeout: Duration::from_secs(5), ..short() };
let addr = serve_echo_with(limits);
let nonce = cadcraft_mcp::control_token::new_nonce().unwrap();
for trickle in [b"{".to_vec(), hello_line(&nonce).into_bytes()] {
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let reader = std::thread::spawn({
let c = c.try_clone().unwrap();
move || BufReader::new(c).lines().count()
});
let t = std::time::Instant::now();
while c.write_all(&trickle).is_ok() && t.elapsed() < Duration::from_secs(4) && !reader.is_finished() {
std::thread::sleep(Duration::from_millis(50));
}
assert!(reader.is_finished() && t.elapsed() < Duration::from_secs(3), "still open after {:?}", t.elapsed());
let _ = reader.join();
}
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut r = BufReader::new(c.try_clone().unwrap());
let mut line = String::new();
c.write_all(req_line(1, "ping").as_bytes()).unwrap();
r.read_line(&mut line).unwrap();
std::thread::sleep(Duration::from_millis(700));
c.write_all(req_line(2, "pong").as_bytes()).unwrap();
line.clear();
r.read_line(&mut line).unwrap();
assert!(line.contains("pong"), "an authenticated connection outlives the preauth time: {line:?}");
}
#[test]
fn extra_connections_are_refused() {
let addr = serve_echo();
+23
View File
@@ -221,11 +221,34 @@ fn services() -> Services {
pick_pgp: Some(Box::new(|dir: Option<&str>| {
file_dialog(&Pick::Pgp(dir.unwrap_or_default().into())).pick_file().map(|p| p.to_string_lossy().to_string())
})),
open_folder: Some(Box::new(|dir: &str| open_folder(dir).map_err(Into::into))),
// Set in `main` once the Nightly session record exists.
at_exit: None,
}
}
/// Why [`open_folder`] could not show a folder.
#[derive(Debug, thiserror::Error)]
enum OpenFolderError {
#[error("{dir}: {source}")]
Create { dir: String, source: std::io::Error },
#[error("{program}: {source}")]
Launch { program: &'static str, source: std::io::Error },
}
/// Show `dir` in the system's file manager (Finder, Explorer or the desktop's own), creating it
/// first so a folder nothing was saved in yet still opens.
fn open_folder(dir: &str) -> Result<(), OpenFolderError> {
std::fs::create_dir_all(dir).map_err(|source| OpenFolderError::Create { dir: dir.to_string(), source })?;
#[cfg(target_os = "macos")]
let program = "open";
#[cfg(target_os = "windows")]
let program = "explorer";
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
let program = "xdg-open";
std::process::Command::new(program).arg(dir).spawn().map(|_| ()).map_err(|source| OpenFolderError::Launch { program, source })
}
/// The file types `pick` offers: (label, extensions). Shared by the blocking dialogs and the
/// macOS sheets.
fn filters(pick: &Pick) -> Vec<(&'static str, Vec<&'static str>)> {
+3 -3
View File
@@ -3,7 +3,7 @@
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::mpsc;
use std::sync::{Arc, mpsc};
use cadcraft_ui_egui::menus::{self, Entry};
use cadcraft_ui_egui::{CadApp, i18n};
@@ -44,10 +44,10 @@ impl NativeMenu {
// wake the app for it: the handler does, and the choice runs in the next frame.
let (sender, events) = mpsc::channel();
let wake = ctx.clone();
MenuEvent::set_event_handler(Some(move |event| {
MenuEvent::set_event_handler(Some(Arc::new(move |event| {
let _ = sender.send(event);
wake.request_repaint();
}));
})));
let menu = Menu::new();
let mut items = HashMap::new();
let language = app.language();
+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);
+85 -21
View File
@@ -104,6 +104,48 @@ enum Val {
Flip(Vec3, Vec3, bool),
/// A flip grip's state: its value record's last group 70.
State(bool),
/// Where a visibility or lookup parameter is, when an action carries it, with its state or
/// value (unchanged; its record holds both).
At(Vec3, String),
}
/// What an action carries of parameter `node`: the value this change has given it so far, else
/// its current one; of a visibility or lookup parameter, its position (its state or value stays).
/// None for a parameter whose state this change sets (it stays where it is).
fn carried(m: &DynamicBlock, values: &BTreeMap<i32, Value>, new: &BTreeMap<i32, Val>, node: i32) -> Option<Val> {
match new.get(&node) {
Some(Val::Text(_)) => None,
Some(v) => Some(v.clone()),
None => match current(m, values, node)? {
Val::Text(t) => located(m, values, node).map(|p| Val::At(p, t)),
v => Some(v),
},
}
}
/// Parameter value `v` with each of its points moved by `f` (a visibility or lookup parameter's
/// carried position too); `None` for a value without points (a state or a value alone).
fn moved(v: Val, f: impl Fn(Vec3) -> Vec3) -> Option<Val> {
Some(match v {
Val::Point(q) => Val::Point(f(q)),
Val::At(q, t) => Val::At(f(q), t),
Val::Points(b, e) => Val::Points(f(b), f(e)),
Val::Flip(b, e, s) => Val::Flip(f(b), f(e), s),
Val::Text(_) | Val::State(_) => return None,
})
}
/// Where a visibility or lookup parameter is on a reference: as its record has it, else as the
/// dynamic block has it.
fn located(m: &DynamicBlock, values: &BTreeMap<i32, Value>, node: i32) -> Option<Vec3> {
let home = m.parameters.iter().find(|p| p.node == node).and_then(|p| match &p.kind {
ParameterKind::Visibility { at, .. } | ParameterKind::Lookup { at, .. } => Some(*at),
_ => None,
})?;
Some(match values.get(&node) {
Some(Value::Text { at: Some(q), .. }) => *q,
_ => home,
})
}
/// A rotation parameter's angle (radians, 0 to 2π): its end's direction from its base, from the
@@ -173,7 +215,7 @@ fn current(m: &DynamicBlock, values: &BTreeMap<i32, Value>, node: i32) -> Option
let p = m.parameters.iter().find(|p| p.node == node)?;
let given = values.get(&node);
Some(match (&p.kind, given) {
(_, Some(Value::Text { value })) => Val::Text(value.clone()),
(_, Some(Value::Text { value, .. })) => Val::Text(value.clone()),
(_, Some(Value::Point { at })) => Val::Point(*at),
(_, Some(Value::Points { base, end })) => Val::Points(*base, *end),
(_, Some(Value::Flip { base, end, flipped })) => Val::Flip(*base, *end, *flipped),
@@ -954,7 +996,7 @@ impl ActionRun<'_> {
/// The value of parameter `node` so far: carried along by an action already, else the
/// reference's.
fn value_of(&self, node: i32) -> Option<Val> {
self.new.get(&node).cloned().or_else(|| current(self.m, self.values, node))
carried(self.m, self.values, &self.new, node)
}
/// Action `a`, when one of its connections follows a parameter the change sets.
@@ -1022,13 +1064,9 @@ impl ActionRun<'_> {
}
let back = |q: Vec3| q - rebase.to3(0.0);
for p in self.m.parameters.iter().filter(|p| !matches!(p.kind, ParameterKind::BasePoint { .. })) {
let moved = match self.value_of(p.node) {
Some(Val::Point(q)) => Val::Point(back(q)),
Some(Val::Points(b, e)) => Val::Points(back(b), back(e)),
Some(Val::Flip(b, e, f)) => Val::Flip(back(b), back(e), f),
_ => continue,
};
self.new.insert(p.node, moved);
// A visibility or lookup grip goes back too (its carried position).
let Some(now) = self.value_of(p.node).and_then(|v| moved(v, back)) else { continue };
self.new.insert(p.node, now);
}
rebase
}
@@ -1047,14 +1085,8 @@ impl ActionRun<'_> {
continue;
}
let Some(cur) = self.value_of(node) else { continue };
let p = |q: Vec3| t.apply(q.xy()).to3(q.z);
let moved = match cur {
Val::Point(q) => Val::Point(p(q)),
Val::Points(b, e) => Val::Points(p(b), p(e)),
Val::Flip(b, e, f) => Val::Flip(p(b), p(e), f),
other => other,
};
self.new.insert(node, moved);
let now = moved(cur.clone(), |q| t.apply(q.xy()).to3(q.z)).unwrap_or(cur);
self.new.insert(node, now);
} else if let Some(c) = self.copy_of(h) {
self.moves.entry(c).or_default().push(Op::Transform(t));
}
@@ -1082,7 +1114,8 @@ impl ActionRun<'_> {
}
let Some(cur) = self.value_of(node) else { continue };
let home = current(self.m, &BTreeMap::new(), node);
self.new.insert(node, turned_and_shifted(cur, home, frame, (turn, v)));
let at = located(self.m, &BTreeMap::new(), node);
self.new.insert(node, turned_and_shifted(cur, (home, at), frame, (turn, v)));
continue;
}
let Some(c) = self.copy_of(h) else { continue };
@@ -1148,7 +1181,8 @@ impl ActionRun<'_> {
}
let Some(cur) = self.value_of(node) else { continue };
let home = current(self.m, &BTreeMap::new(), node);
self.new.insert(node, shifted(cur, home, frame, v));
let at = located(self.m, &BTreeMap::new(), node);
self.new.insert(node, shifted(cur, (home, at), frame, v));
continue;
}
let Some(c) = self.copy_of(h) else { continue };
@@ -1204,7 +1238,7 @@ fn earlier_copies(src: &Block, src_tag: &HashMap<Handle, i64>, arrays: &HashMap<
/// A parameter value `cur` turned by `turn`, and carried by `v` where its points are in `frame`
/// (judged where the dynamic block has them, `home`), after a polar stretch.
fn turned_and_shifted(cur: Val, home: Option<Val>, frame: &[Vec2], (turn, v): (Mat3, Vec2)) -> Val {
fn turned_and_shifted(cur: Val, (home, located): (Option<Val>, Option<Vec3>), frame: &[Vec2], (turn, v): (Mat3, Vec2)) -> Val {
let carry = |p: Vec3, at: Vec3| {
let q = turn.apply(p.xy()).to3(p.z);
if in_frame(frame, at.xy()) { q + v.to3(0.0) } else { q }
@@ -1212,6 +1246,8 @@ fn turned_and_shifted(cur: Val, home: Option<Val>, frame: &[Vec2], (turn, v): (M
match (cur, home) {
(Val::Point(p), Some(Val::Point(h))) => Val::Point(carry(p, h)),
(Val::Point(p), _) => Val::Point(carry(p, p)),
// A carried visibility or lookup grip: in the frame where the dynamic block has it.
(Val::At(p, t), _) => Val::At(carry(p, located.unwrap_or(p)), t),
(Val::Points(b, e), Some(Val::Points(hb, he))) => Val::Points(carry(b, hb), carry(e, he)),
(Val::Points(b, e), _) => Val::Points(carry(b, b), carry(e, e)),
(Val::Flip(b, e, f), Some(Val::Flip(hb, he, _))) => Val::Flip(carry(b, hb), carry(e, he), f),
@@ -1222,11 +1258,12 @@ fn turned_and_shifted(cur: Val, home: Option<Val>, frame: &[Vec2], (turn, v): (M
/// Parameter value `cur` carried by `v`: the points in `frame` (empty: all of them), judged where
/// the dynamic block has them (`home`), move.
fn shifted(cur: Val, home: Option<Val>, frame: &[Vec2], v: Vec2) -> Val {
fn shifted(cur: Val, (home, located): (Option<Val>, Option<Vec3>), frame: &[Vec2], v: Vec2) -> Val {
let shift = |p: Vec3, at: Option<Vec3>| if frame.is_empty() || in_frame(frame, at.unwrap_or(p).xy()) { p + v.to3(0.0) } else { p };
match (cur, home) {
(Val::Point(p), Some(Val::Point(h))) => Val::Point(shift(p, Some(h))),
(Val::Point(p), _) => Val::Point(shift(p, None)),
(Val::At(p, t), _) => Val::At(shift(p, located), t),
(Val::Points(b, e), Some(Val::Points(hb, he))) => Val::Points(shift(b, Some(hb)), shift(e, Some(he))),
(Val::Points(b, e), _) => Val::Points(shift(b, None), shift(e, None)),
(Val::Flip(b, e, f), Some(Val::Flip(hb, he, _))) => Val::Flip(shift(b, Some(hb)), shift(e, Some(he)), f),
@@ -2030,6 +2067,10 @@ fn write_value(tags: &mut Vec<RawTag>, v: &Val) {
return;
}
Val::Point(p) => vec![*p],
Val::At(p, t) => {
write_value(tags, &Val::Text(t.clone()));
vec![*p]
}
Val::Points(b, e) | Val::Flip(b, e, _) => vec![*b, *e],
Val::State(f) => {
set_state(tags, *f);
@@ -2244,6 +2285,29 @@ mod tests {
assert_eq!(total, 23);
}
#[test]
fn a_carried_visibility_grip_moves_with_the_points() {
let up = |q: Vec3| q + Vec3::new(0.0, 1.0, 0.0);
let at = Val::At(Vec3::new(2.0, 0.0, 0.0), "Open".into());
assert_eq!(moved(at, up), Some(Val::At(Vec3::new(2.0, 1.0, 0.0), "Open".into())));
assert_eq!(moved(Val::Text("Open".into()), up), None);
assert_eq!(moved(Val::State(true), up), None);
}
#[test]
fn a_polar_stretch_carries_a_visibility_grip() {
let turn = Mat3::rotate_about(Vec2::ZERO, std::f64::consts::FRAC_PI_2);
let frame = [Vec2::new(1.0, -1.0), Vec2::new(3.0, 1.0)];
let at = |x: f64, y: f64| Val::At(Vec3::new(x, y, 0.0), "Open".into());
let near = |v: Val, x: f64, y: f64| matches!(v, Val::At(p, _) if (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9);
// In the frame where the dynamic block has it: turned, then moved.
let v = turned_and_shifted(at(2.0, 0.0), (None, Some(Vec3::new(2.0, 0.0, 0.0))), &frame, (turn, Vec2::new(0.0, 1.0)));
assert!(near(v, 0.0, 3.0));
// Outside it: only turned.
let v = turned_and_shifted(at(5.0, 0.0), (None, Some(Vec3::new(5.0, 0.0, 0.0))), &frame, (turn, Vec2::new(0.0, 1.0)));
assert!(near(v, 0.0, 5.0));
}
fn tagged(h: u64, tag_value: Option<&str>) -> Entity {
let mut e = Entity::new(Handle(h), EntityKind::Line(crate::Line { a: Vec3::ZERO, b: Vec3::ZERO }));
if let Some(v) = tag_value {
+6 -2
View File
@@ -172,7 +172,7 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
for p in &m.parameters {
if let ParameterKind::Visibility { states, .. } = &p.kind {
let current = match r.values.get(&p.node) {
Some(Value::Text { value }) => states.iter().find(|s| s.name.eq_ignore_ascii_case(value)),
Some(Value::Text { value, .. }) => states.iter().find(|s| s.name.eq_ignore_ascii_case(value)),
_ => states.first(),
};
if let Some(s) = current {
@@ -340,7 +340,11 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
ParameterKind::Visibility { at, label, .. } | ParameterKind::Lookup { at, label, .. } => {
let Some(list) = choices.get(&label.to_ascii_uppercase()).filter(|c| !c.is_empty()) else { continue };
if shown(p.node, grip(0)) {
let at = world(*at);
// Where the reference's record has it (an action may have carried it).
let at = match r.values.get(&p.node) {
Some(Value::Text { at: Some(q), .. }) => world(*q),
_ => world(*at),
};
out.push(DynGrip {
node: p.node,
part: GripPart::At,
+12 -6
View File
@@ -23,8 +23,13 @@ const MAX_VALUES: usize = 10_000;
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum Value {
/// A visibility state's name or a lookup value.
Text { value: String },
/// A visibility state's name or a lookup value, and where the parameter is when the record
/// says (an action may have carried it from where the dynamic block has it).
Text {
value: String,
#[serde(skip_serializing_if = "Option::is_none")]
at: Option<Vec3>,
},
/// A point parameter's position.
Point { at: Vec3 },
/// A two-point parameter's points.
@@ -93,17 +98,18 @@ fn entries(objects: &HashMap<Handle, &ForeignObject>, dict: Handle) -> Vec<(Stri
out
}
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30); a flip
/// A value XRECORD: its text (group 1) when it has one, with the parameter's position (a
/// visibility or lookup grip's, 10/20/30) when it has that too; else its points; a flip
/// parameter's also has its state, a group 70 after its points (the header's `70 25`, `70 104`
/// come before them).
fn value(o: &ForeignObject) -> Option<Value> {
if let Some(t) = o.tags.iter().find(|t| t.code == 1) {
return Some(Value::Text { value: t.value.clone() });
}
let num = |code: i32, i: usize| {
o.tags.iter().filter(|t| t.code == code).nth(i).and_then(|t| t.value.trim().parse::<f64>().ok()).filter(|v| v.is_finite())
};
let point = |i: usize| Some(Vec3::new(num(10, i)?, num(20, i)?, num(30, i).unwrap_or(0.0)));
if let Some(t) = o.tags.iter().find(|t| t.code == 1) {
return Some(Value::Text { value: t.value.clone(), at: point(0) });
}
let first_point = o.tags.iter().position(|t| t.code == 10).unwrap_or(o.tags.len());
let state = o.tags.get(first_point..).unwrap_or_default().iter().rev().find(|t| t.code == 70).map(|t| t.value.trim() == "1");
match (point(0), point(1)) {
+1 -1
View File
@@ -50,7 +50,7 @@ mod xdata;
pub use xdata::{
MAX_XDATA_APP_NAME, MAX_XDATA_CHUNK, MAX_XDATA_GROUPS, MAX_XDATA_STRING, RESERVED_XDATA_APPS, XdataError, check_xdata_app_name,
check_xdata_groups, is_model_xdata_app, is_reserved_xdata_app, is_xdata_group, set_xdata_app, xdata_apps, xdata_of,
check_xdata_groups, is_model_xdata, is_model_xdata_app, is_reserved_xdata_app, is_xdata_group, set_xdata_app, xdata_apps, xdata_of,
};
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal};
+5
View File
@@ -197,6 +197,11 @@ pub struct Leader {
pub spline: bool,
#[serde(default = "standard")]
pub style: String,
/// Per-leader style overrides (the `ACAD` DSTYLE xdata of a LEADER): DimStyle field names
/// (camelCase) → values, merged over the named style as a dimension's are. A leader draws
/// with its arrow size, overall scale, leader arrowhead and dimension line colour.
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
pub overrides: serde_json::Map<String, serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+48
View File
@@ -31,10 +31,34 @@ pub fn is_reserved_xdata_app(name: &str) -> bool {
/// than kept raw: the [`RESERVED_XDATA_APPS`] on any entity, and `ACAD` on a dimension, whose
/// `ACAD` run (`DSTYLE`) holds its dimension-style overrides. The reader models those too, so
/// raw groups set under such a name would be dropped on save; they are refused instead.
/// [`is_model_xdata`] also knows the one list of a leader's `ACAD` run that is modelled.
pub fn is_model_xdata_app(name: &str, kind: &super::EntityKind) -> bool {
is_reserved_xdata_app(name) || (name.trim().eq_ignore_ascii_case("ACAD") && matches!(kind, super::EntityKind::Dimension(_)))
}
/// The list in a dimension's or a leader's `ACAD` xdata that holds its dimension-style overrides.
const DSTYLE_LIST: &str = "DSTYLE";
/// Whether `groups` (one application's xdata, its `1001` left out) hold a list named `name`
/// (any case): a `1000 <name>` group followed by `1002 {`. A string that only reads `<name>`
/// starts no list.
fn has_xdata_list(groups: &[RawTag], name: &str) -> bool {
groups.windows(2).any(
|w| matches!(w, [n, open] if n.code == 1000 && n.value.trim().eq_ignore_ascii_case(name) && open.code == 1002 && open.value.trim() == "{"),
)
}
/// Whether `groups`, given as raw xdata of application `name` for an entity of `kind`, hold
/// what is written from the model: all data of an application [`is_model_xdata_app`] names,
/// and on a leader an `ACAD` run with a `DSTYLE` list. A leader's `DSTYLE` list is its
/// dimension-style overrides, read into the leader and written from it; raw groups with one
/// would be dropped on save or contradict the overrides, so they are refused instead. The rest
/// of a leader's `ACAD` data is kept raw and may be set.
pub fn is_model_xdata(name: &str, groups: &[RawTag], kind: &super::EntityKind) -> bool {
is_model_xdata_app(name, kind)
|| (name.trim().eq_ignore_ascii_case("ACAD") && matches!(kind, super::EntityKind::Leader(_)) && has_xdata_list(groups, DSTYLE_LIST))
}
/// Why an application name or a run of xdata groups was refused.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct XdataError(pub String);
@@ -214,6 +238,30 @@ mod tests {
RawTag { code, value: value.into() }
}
/// `ACAD` xdata is modelled as a DSTYLE list on a leader (a name followed by an opening
/// brace, anywhere in the run, any case), and not on another entity or under another name.
#[test]
fn a_leaders_dstyle_list_is_model_data_and_its_other_acad_data_is_not() {
use super::super::{EntityKind, Leader, Line};
use cadcraft_geom::Vec3;
let leader = EntityKind::Leader(Leader {
vertices: vec![Vec3::ZERO, Vec3::new(1.0, 0.0, 0.0)],
arrow: true,
spline: false,
style: "Standard".into(),
overrides: serde_json::Map::new(),
});
let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) });
let list = [t(1000, "MINE"), t(1000, " dstyle "), t(1002, "{"), t(1070, "41"), t(1040, "9.0"), t(1002, "}")];
let loose = [t(1000, "DSTYLE"), t(1070, "41"), t(1000, "OTHER"), t(1002, "{"), t(1002, "}")];
assert!(is_model_xdata("acad", &list, &leader));
assert!(!is_model_xdata("ACAD", &loose, &leader), "a string that only reads DSTYLE starts no list");
assert!(!is_model_xdata("ACAD", &[], &leader));
assert!(!is_model_xdata("ACME", &list, &leader), "another application's list is its own");
assert!(!is_model_xdata("ACAD", &list, &line));
assert!(is_model_xdata("CADCRAFT", &[], &leader) && is_model_xdata("CADCRAFT", &[], &line));
}
#[test]
fn apps_are_split_at_their_names() {
let x = vec![t(1001, "A"), t(1000, "one"), t(1070, "1"), t(1001, "b"), t(1000, "two")];
+49 -23
View File
@@ -242,15 +242,29 @@ pub fn ole_frame_accepts(m: &cadcraft_geom::Mat3) -> bool {
m.b.abs() < t && m.c.abs() < t && m.a > 0.0 && (m.a - m.d).abs() <= t
}
/// How many characters a single-line text value draws, as the fonts read it: a `%%` code is the
/// one character it stands for (`%%d`, `%%p`, `%%c`, `%%%`, `%%nnn`) or none (the underline and
/// overline toggles `%%u` and `%%o`), `\U+XXXX` is one character, and invisible formatting
/// characters (joiners, directional marks) take no room.
fn drawn_chars(value: &str) -> usize {
/// What a single-line text value draws, as the fonts read it.
#[derive(Clone, Copy, Default)]
struct Drawn {
/// How many characters take room.
chars: usize,
/// Whether any of them is underlined, and whether any is overlined.
underlined: bool,
overlined: bool,
}
/// What a single-line text value draws, as the fonts read it: a `%%` code is the one character
/// it stands for (`%%d`, `%%p`, `%%c`, `%%%`, `%%nnn`) or none (`%%u` and `%%o`, which turn the
/// underline and the overline on and off for the characters after them), `\U+XXXX` is one
/// character, and invisible formatting characters (joiners, directional marks) take no room.
fn drawn_text(value: &str) -> Drawn {
let invisible = |c: char| matches!(c, '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2060}'..='\u{2069}' | '\u{FEFF}' | '\u{061C}');
let chars: Vec<char> = value.chars().collect();
let (mut i, mut drawn) = (0usize, 0usize);
// The toggles as they stand, and what the characters drawn so far have had.
let (mut under, mut over) = (false, false);
let mut out = Drawn::default();
while let Some(&c) = chars.get(i) {
let before = drawn;
let escaped = (c == '\\' && matches!(chars.get(i + 1), Some('U' | 'u')) && chars.get(i + 2) == Some(&'+'))
.then(|| chars.get(i + 3..i + 7))
.flatten()
@@ -262,7 +276,8 @@ fn drawn_chars(value: &str) -> usize {
i += 7;
} else if c == '%' && chars.get(i + 1) == Some(&'%') {
match chars.get(i + 2).map_or(' ', char::to_ascii_lowercase) {
'u' | 'o' => i += 3,
'u' => (under, i) = (!under, i + 3),
'o' => (over, i) = (!over, i + 3),
'd' | 'p' | 'c' | '%' => (drawn, i) = (drawn + 1, i + 3),
digit if digit.is_ascii_digit() => {
let digits = chars.iter().skip(i + 2).take(3).take_while(|d| d.is_ascii_digit()).count();
@@ -275,15 +290,19 @@ fn drawn_chars(value: &str) -> usize {
drawn += usize::from(!invisible(c));
i += 1;
}
if drawn > before {
(out.underlined, out.overlined) = (out.underlined || under, out.overlined || over);
}
}
drawn
Drawn { chars: drawn, ..out }
}
/// Bounds of a single-line TEXT / ATTDEF / ATTRIB of `len` drawn characters, following its
/// Bounds of a single-line TEXT / ATTDEF / ATTRIB that draws `drawn`, following its
/// justification the same way the renderer places it (the stroke font is about 0.88 of the height
/// per character). Empty when nothing is drawn.
fn text_box(t: &crate::Text, len: usize) -> Bounds2 {
/// per character), its underline and overline included. Empty when nothing is drawn.
fn text_box(t: &crate::Text, drawn: Drawn) -> Bounds2 {
use crate::{HAlign, VAlign};
let len = drawn.chars;
if len == 0 {
return Bounds2::EMPTY;
}
@@ -340,15 +359,22 @@ fn text_box(t: &crate::Text, len: usize) -> Bounds2 {
HAlign::Center | HAlign::Middle => -w / 2.0,
HAlign::Right => -w,
};
// The box from its bottom to its top. Bottom justification lifts the line by a third of the
// height it is drawn at: the box starts where the shortest line would and ends where the
// tallest would.
let (y0, y1) = match (t.halign, t.valign) {
(HAlign::Middle, _) | (_, VAlign::Middle) => (-h / 2.0, h / 2.0),
(_, VAlign::Baseline) => (0.0, h),
(_, VAlign::Bottom) => (low / 3.0, h / 3.0 + h),
(_, VAlign::Top) => (-h, 0.0),
// Where the baseline of a line drawn `drawn_h` high lies. Bottom justification lifts the line
// by a third of the height it is drawn at.
let baseline = |drawn_h: f64| match (t.halign, t.valign) {
(HAlign::Middle, _) | (_, VAlign::Middle) => -drawn_h / 2.0,
(_, VAlign::Baseline) => 0.0,
(_, VAlign::Bottom) => drawn_h / 3.0,
(_, VAlign::Top) => -drawn_h,
};
// The fonts draw an underline a fifth of the drawn height below the baseline and an overline
// a fifth of it above the line's top.
let below = if drawn.underlined { 0.2 } else { 0.0 };
let above = if drawn.overlined { 1.2 } else { 1.0 };
// The box from its bottom to its top: it starts where the lowest of the shortest and the
// tallest possible line would and ends where the highest of the two would.
let [(b0, t0), (b1, t1)] = [low, h].map(|drawn_h| (baseline(drawn_h) - below * drawn_h, baseline(drawn_h) + above * drawn_h));
let (y0, y1) = (b0.min(b1), t0.max(t1));
let local = [Vec2::new(dx, y0), Vec2::new(dx + w, y0), Vec2::new(dx + w, y1), Vec2::new(dx, y1)];
// Backwards and upside-down text is mirrored about the point it is placed by.
let (mx, my) = (if t.backwards { -1.0 } else { 1.0 }, if t.upside_down { -1.0 } else { 1.0 });
@@ -484,7 +510,7 @@ fn constant_box(a: &crate::Attrib, upright: bool) -> Bounds2 {
let turn = |r: f64| if upright { 0.0 } else { r };
match a.multiline_text() {
Some(m) if !blank(&m.contents) => mtext_box(&crate::MText { rotation: turn(m.rotation), ..m }),
None if !blank(&a.text.value) => text_box(&crate::Text { rotation: turn(a.text.rotation), ..a.text.clone() }, drawn_chars(&a.text.value)),
None if !blank(&a.text.value) => text_box(&crate::Text { rotation: turn(a.text.rotation), ..a.text.clone() }, drawn_text(&a.text.value)),
_ => Bounds2::EMPTY,
}
}
@@ -675,10 +701,10 @@ fn bounds_in<'a>(
EntityKind::Text(t) if blank(&t.value) => Bounds2::EMPTY,
EntityKind::MText(t) if blank(&t.contents) => Bounds2::EMPTY,
// Text that matches the layout's orientation is drawn upright (#2498).
EntityKind::Text(t) if e.common.matches_layout_orientation() => text_box(&crate::Text { rotation: 0.0, ..t.clone() }, drawn_chars(&t.value)),
EntityKind::Text(t) if e.common.matches_layout_orientation() => text_box(&crate::Text { rotation: 0.0, ..t.clone() }, drawn_text(&t.value)),
EntityKind::MText(t) if e.common.matches_layout_orientation() => mtext_box(&crate::MText { rotation: 0.0, ..t.clone() }),
EntityKind::Text(t) => text_box(t, drawn_chars(&t.value)),
EntityKind::AttDef(a) => text_box(&a.text, drawn_chars(&a.tag)),
EntityKind::Text(t) => text_box(t, drawn_text(&t.value)),
EntityKind::AttDef(a) => text_box(&a.text, drawn_text(&a.tag)),
EntityKind::MText(t) => mtext_box(t),
EntityKind::Insert(ins) => {
if depth >= MAX_BLOCK_DEPTH {
@@ -727,7 +753,7 @@ fn bounds_in<'a>(
if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts, frozen) {
b = b.union(&match a.multiline_text() {
Some(m) => mtext_box(&m),
None => text_box(&a.text, drawn_chars(&a.text.value)),
None => text_box(&a.text, drawn_text(&a.text.value)),
});
}
}
+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;
+50 -11
View File
@@ -186,7 +186,11 @@ impl PlotStyle {
/// The printed colour of an object drawn in `rgb`: the style's colour (else `rgb`), turned
/// grey when asked, then screened toward white.
pub fn apply_color(&self, rgb: Rgb) -> Rgb {
let c = self.color.unwrap_or(rgb);
self.shade(self.color.unwrap_or(rgb))
}
/// `c` turned grey when the style asks for it, then screened toward white: what the style
/// does to a colour it does not replace.
pub fn shade(&self, c: Rgb) -> Rgb {
let c = if self.grayscale {
let g = (c.luma().clamp(0.0, 1.0) * 255.0).round() as u8;
Rgb(g, g, g)
@@ -372,30 +376,65 @@ impl PlotStyleTable {
}
}
/// The tables of the user's plot style folder, as the host last read them (see
/// [`set_plot_style_folder`]). Empty until a host reads a folder.
static FOLDER: std::sync::RwLock<Option<std::sync::Arc<Vec<PlotStyleTable>>>> = std::sync::RwLock::new(None);
/// Replace the tables of the user's plot style folder that every drawing can use. The host reads
/// the folder (this crate does no file I/O) and calls this again after each change.
pub fn set_plot_style_folder(tables: Vec<PlotStyleTable>) {
if let Ok(mut f) = FOLDER.write() {
*f = Some(std::sync::Arc::new(tables));
}
}
/// The tables of the user's plot style folder (empty when the host has read none).
pub fn plot_style_folder() -> std::sync::Arc<Vec<PlotStyleTable>> {
FOLDER.read().ok().and_then(|f| f.clone()).unwrap_or_default()
}
/// The folder's table called `name` (case-insensitive).
pub fn plot_style_folder_table(name: &str) -> Option<PlotStyleTable> {
let n = name.trim();
plot_style_folder().iter().find(|t| t.name.eq_ignore_ascii_case(n)).cloned()
}
/// Whether a page setup's table name means "no plot style table".
pub fn no_plot_style_table(name: &str) -> bool {
let n = name.trim();
n.is_empty() || n.eq_ignore_ascii_case("none")
}
/// The plot style table a page setup names, if it is one we know: the drawing's own tables
/// first, then the built-in ones. `None` for no table (empty or "None") and for tables we don't
/// have.
/// The plot style table a page setup names, if it is one we know: the drawing's own tables first
/// (a folder table a layout chose is copied into the drawing, and the drawing then plots with its
/// copy whatever happens to the file), then the user's plot style folder, then the built-in ones. `None` for no table (empty or "None") and for tables we don't have.
pub fn plot_style_table(d: &crate::Drawing, name: &str) -> Option<PlotStyleTable> {
if no_plot_style_table(name) {
return None;
}
let n = name.trim();
d.plot_style_tables.iter().find(|t| t.name.eq_ignore_ascii_case(n)).cloned().or_else(|| PlotStyleTable::builtin(n))
d.plot_style_tables
.iter()
.find(|t| t.name.eq_ignore_ascii_case(n))
.cloned()
.or_else(|| plot_style_folder_table(n))
.or_else(|| PlotStyleTable::builtin(n))
}
/// The names of every table a drawing can use: its own, then the built-in ones it doesn't
/// shadow.
/// The names of every table a drawing can use: the drawing's own, the folder's, then the built-in
/// ones, each name once.
pub fn plot_style_table_names(d: &crate::Drawing) -> Vec<String> {
let mut v: Vec<String> = d.plot_style_tables.iter().map(|t| t.name.clone()).collect();
for b in BUILTIN_PLOT_STYLE_TABLES {
if !v.iter().any(|n| n.eq_ignore_ascii_case(b)) {
v.push((*b).to_string());
let mut v: Vec<String> = Vec::new();
let folder = plot_style_folder();
let all = d
.plot_style_tables
.iter()
.map(|t| t.name.as_str())
.chain(folder.iter().map(|t| t.name.as_str()))
.chain(BUILTIN_PLOT_STYLE_TABLES.iter().copied());
for n in all {
if !v.iter().any(|x| x.eq_ignore_ascii_case(n)) {
v.push(n.to_string());
}
}
v
+1 -1
View File
@@ -24,7 +24,7 @@ serde_json = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
# R-tree spatial index for picking, window selection and object snaps (MIT OR Apache-2.0).
rstar = { version = "0.13", default-features = false }
rstar = { version = "0.14", default-features = false }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
+2 -1
View File
@@ -21,7 +21,7 @@ mod griphot;
pub(crate) mod groups;
pub(crate) mod hatch;
mod image;
mod inquiry;
pub(crate) mod inquiry;
pub mod interface;
mod layer;
mod layout;
@@ -35,6 +35,7 @@ mod modify2;
mod mtext_opts;
mod overkill;
mod pline_opts;
pub mod plotstyle_folder;
pub mod plotters;
mod props;
pub use blocks::library::{clear_library_cache, list_library, read_library_file};
+3
View File
@@ -305,6 +305,9 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
arrow,
spline,
style: style(s),
// The drawing's DIM* overrides, as a new dimension takes them: the arrowhead is then drawn
// with the DIMASZ the hook line above was sized from, and they are saved with the leader.
overrides: s.doc().map(|d| d.dim_overrides()).unwrap_or_default(),
}))?;
let annotation = match ann {
Annotation::Text(lines) => {
+2 -1
View File
@@ -6,7 +6,7 @@ use cadcraft_doc::{Drawing, Entity, EntityKind};
use serde_json::{Value, json};
use super::attribs::{attdefs, synced, update_reference_entities};
use super::purge::{override_arrows, used_blocks};
use super::purge::{leader_override_arrows, override_arrows, used_blocks};
use super::references_block;
use crate::cmd::curves::KW;
use crate::cmd::machines::{SelOutcome, SelectPhase};
@@ -96,6 +96,7 @@ fn referenced(d: &Drawing, name: &str) -> bool {
match &e.kind {
EntityKind::Insert(i) => vec![i.block.clone()],
EntityKind::Dimension(dm) => dm.block.iter().cloned().chain(override_arrows(dm)).collect(),
EntityKind::Leader(l) => leader_override_arrows(l).collect(),
EntityKind::MLeader(m) => m.block.iter().map(|b| b.block.clone()).collect(),
_ => Vec::new(),
}
+3
View File
@@ -230,6 +230,9 @@ impl Session {
/// UI's click on a dynamic grip). A list grip (visibility, lookup) or a flip grip has no
/// drag: the UI offers the choices, or flips, with `blocks.reference.set`.
pub fn start_dyn_grip(&mut self, handle: Handle, node: i32, part: GripPart) -> Result<()> {
// The value of an expression the frames are working out answers its prompt before the
// command it was typed in is cancelled for the grip.
self.lisp_settle_answer();
if self.running.is_some() {
self.cancel();
}
+25 -15
View File
@@ -14,7 +14,7 @@ use serde_json::{Value, json};
use super::super::file::io;
use super::super::modify::explode_kind;
use super::purge::{Kind, candidates, is_arrow_override, override_arrows, override_name, scan_reads_everything};
use super::purge::{Kind, candidates, is_arrow_override, leader_override_arrows, override_arrows, override_name, scan_reads_everything};
use super::{referenced_block, references_block, valid_block_name};
use crate::cmd::{bad, str_param};
use crate::{EngineError, Result, Session};
@@ -200,8 +200,10 @@ fn reachable(d: &Drawing, roots: Vec<String>) -> BTreeSet<String> {
let Some(b) = d.block(&n) else { continue };
for e in b.entities.iter() {
todo.extend(referenced_block(e));
if let EntityKind::Dimension(dm) = &e.kind {
todo.extend(override_arrows(dm));
match &e.kind {
EntityKind::Dimension(dm) => todo.extend(override_arrows(dm)),
EntityKind::Leader(l) => todo.extend(leader_override_arrows(l)),
_ => {}
}
}
}
@@ -214,8 +216,10 @@ fn needed_blocks(src: &Drawing) -> BTreeSet<String> {
let mut roots: Vec<String> = Vec::new();
for e in src.model.iter() {
roots.extend(referenced_block(e));
if let EntityKind::Dimension(dm) = &e.kind {
roots.extend(override_arrows(dm));
match &e.kind {
EntityKind::Dimension(dm) => roots.extend(override_arrows(dm)),
EntityKind::Leader(l) => roots.extend(leader_override_arrows(l)),
_ => {}
}
}
for st in &src.dim_styles {
@@ -319,6 +323,20 @@ fn rename_style_arrows(d: &mut Drawing, own: &BTreeSet<String>, renames: &Rename
}
}
/// Point the arrowhead blocks a dimension's or a leader's `overrides` name at their renamed
/// blocks. Only a block that was renamed changes the value: a number naming a block that kept
/// its name stays as it was given.
fn rename_override_arrows(overrides: &mut serde_json::Map<String, Value>, renames: &Renames) {
for (key, value) in overrides.iter_mut() {
if is_arrow_override(key)
&& let Some(b) = override_name(value)
&& let Some(n) = renames.get(&b).filter(|n| **n != b)
{
*value = json!(n);
}
}
}
/// A copy of a source entity for this drawing: a fresh handle, block references renamed, and
/// links to other source objects (associative dimension points) dropped.
fn adopt(d: &mut Drawing, src: &Drawing, e: &Entity, renames: &Renames) -> Entity {
@@ -346,17 +364,9 @@ fn adopt(d: &mut Drawing, src: &Drawing, e: &Entity, renames: &Renames) -> Entit
if let Some(n) = dm.block.as_ref().and_then(|b| renames.get(b)) {
dm.block = Some(n.clone());
}
for (key, value) in dm.overrides.iter_mut() {
// Only a block that was renamed changes the value: a number naming a block that
// kept its name stays as it was given.
if is_arrow_override(key)
&& let Some(b) = override_name(value)
&& let Some(n) = renames.get(&b).filter(|n| **n != b)
{
*value = json!(n);
}
}
rename_override_arrows(&mut dm.overrides, renames);
}
EntityKind::Leader(l) => rename_override_arrows(&mut l.overrides, renames),
EntityKind::MLeader(m) => {
if let Some(b) = &mut m.block
&& let Some(n) = renames.get(&b.block)
+15 -2
View File
@@ -147,11 +147,22 @@ pub(in crate::cmd) fn override_name(v: &Value) -> Option<String> {
/// The arrowhead block names a dimension's overrides set.
pub(in crate::cmd) fn override_arrows(dm: &cadcraft_doc::Dimension) -> impl Iterator<Item = String> + '_ {
dm.overrides.iter().filter(|(k, _)| is_arrow_override(k)).filter_map(|(_, v)| override_name(v)).filter(|n| !n.is_empty())
arrows_in(&dm.overrides)
}
/// The arrowhead block names a leader's overrides set (its DIMLDRBLK), as [`override_arrows`]
/// gives a dimension's.
pub(in crate::cmd) fn leader_override_arrows(l: &cadcraft_doc::Leader) -> impl Iterator<Item = String> + '_ {
arrows_in(&l.overrides)
}
/// The arrowhead block names a set of dimension style overrides names.
fn arrows_in(overrides: &serde_json::Map<String, Value>) -> impl Iterator<Item = String> + '_ {
overrides.iter().filter(|(k, _)| is_arrow_override(k)).filter_map(|(_, v)| override_name(v)).filter(|n| !n.is_empty())
}
/// Upper-case names of blocks reachable from model space, the layouts and dimensions, and the
/// arrowhead blocks dimension styles and dimension overrides name.
/// arrowhead blocks dimension styles and dimension or leader overrides name.
pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
let mut used = HashSet::new();
let mut frontier: Vec<String> = Vec::new();
@@ -170,6 +181,7 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
frontier.extend(dm.block.clone());
frontier.extend(override_arrows(dm));
}
EntityKind::Leader(l) => frontier.extend(leader_override_arrows(l)),
EntityKind::MLeader(m) => frontier.extend(m.block.as_ref().map(|b| b.block.clone())),
// A dimension kept as read draws, and is saved with, the block it names (#3438).
EntityKind::Unknown(u) => frontier.extend(u.dimension_block().map(str::to_string)),
@@ -189,6 +201,7 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
frontier.extend(dm.block.clone());
frontier.extend(override_arrows(dm));
}
EntityKind::Leader(l) => frontier.extend(leader_override_arrows(l)),
EntityKind::MLeader(m) => frontier.extend(m.block.as_ref().map(|b| b.block.clone())),
EntityKind::Unknown(u) => frontier.extend(u.dimension_block().map(str::to_string)),
_ => {}
+22 -6
View File
@@ -70,9 +70,16 @@ pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
// ---------------- interactive ----------------
/// A LINE between two 3D points.
fn line3(a: cadcraft_geom::Vec3, b: cadcraft_geom::Vec3) -> EntityKind {
EntityKind::Line(cadcraft_doc::Line { a, b })
}
#[derive(Default)]
pub(super) struct LineM {
pts: Vec<Vec2>,
/// The Z of each of `pts` ([`Session::point_z`]: typed, or from an object snap).
zs: Vec<f64>,
handles: Vec<cadcraft_doc::Handle>,
/// A first point picked as a deferred tangent/perpendicular, resolved by the next point.
first: Option<snap::Deferred>,
@@ -85,8 +92,11 @@ impl LineM {
let what = if first.mode == snap::mode::TAN { "tangent" } else { "perpendicular" };
return Err(crate::EngineError::Other(format!("No {what} line through that point; pick another point.")));
};
self.handles.push(s.add_entity(line(a, b))?);
// The deferred start lies on the curve at z = 0; the other end keeps its own Z.
let z = s.point_z();
self.handles.push(s.add_entity(line3(a.to3(0.0), b.to3(z)))?);
self.pts = vec![a, b];
self.zs = vec![0.0, z];
self.first = None;
s.last_point = b;
Ok(Step::Continue)
@@ -119,6 +129,7 @@ impl Interactive for LineM {
let e = t + Vec2::new(ang.cos(), ang.sin()) * dist;
self.handles.push(s.add_entity(line(t, e))?);
self.pts = vec![t, e];
self.zs = vec![0.0, 0.0];
s.last_point = e;
self.first = None;
return Ok(Step::Continue);
@@ -143,13 +154,15 @@ impl Interactive for LineM {
None => Ok(Step::Continue),
},
Input::Point(p) => {
if let Some(last) = self.pts.last().copied() {
if last.near(p, 1e-12) {
let z = s.point_z();
if let (Some(last), Some(lz)) = (self.pts.last().copied(), self.zs.last().copied()) {
if last.near(p, 1e-12) && (lz - z).abs() < 1e-12 {
return Ok(Step::Continue);
}
self.handles.push(s.add_entity(line(last, p))?);
self.handles.push(s.add_entity(line3(last.to3(lz), p.to3(z)))?);
}
self.pts.push(p);
self.zs.push(z);
Ok(Step::Continue)
}
Input::Keyword(k) if k == "Undo" => {
@@ -160,11 +173,14 @@ impl Interactive for LineM {
s.doc_mut()?.remove_entity(h);
}
self.pts.pop();
self.zs.pop();
Ok(Step::Continue)
}
Input::Keyword(k) if k == "Close" => {
if let (Some(a), Some(b)) = (self.pts.last().copied(), self.pts.first().copied()) {
s.add_entity(line(a, b))?;
if let (Some(a), Some(b), Some(za), Some(zb)) =
(self.pts.last().copied(), self.pts.first().copied(), self.zs.last().copied(), self.zs.first().copied())
{
s.add_entity(line3(a.to3(za), b.to3(zb)))?;
}
Ok(Step::Done)
}
+1 -1
View File
@@ -66,7 +66,7 @@ impl Interactive for PointM {
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Point(p) => {
s.add_entity(EntityKind::Point(Point { p: v3(p), angle: 0.0 }))?;
s.add_entity(EntityKind::Point(Point { p: p.to3(s.point_z()), angle: 0.0 }))?;
Ok(if self.multiple { Step::Continue } else { Step::Done })
}
Input::Enter => Ok(Step::Done),
+9 -7
View File
@@ -1,6 +1,6 @@
use super::{
Accept, EntityKind, Handle, Helix, HelixConstrain, Input, Interactive, MAX_GEN, Polyline3d, Prompt, Result, Session, Spline, Step, Value, Vec2,
Vec3, added, bad, bool_or, circle, curves, f64_or, f64_req, line, number, other, point_req, points_param, v3,
Vec3, added, bad, bool_or, circle, curves, f64_or, f64_req, line, number, other, point_req, points_param,
};
// =====================================================================================
@@ -26,13 +26,14 @@ pub(super) fn run_3dpoly(s: &mut Session, p: &Value) -> Result<Value> {
#[derive(Default)]
pub(super) struct Poly3dM {
pts: Vec<Vec2>,
/// The vertices: a typed point keeps its Z ([`Session::point_z`]), a picked one is at z = 0.
pts: Vec<Vec3>,
handle: Option<Handle>,
}
impl Poly3dM {
fn sync(&mut self, s: &mut Session, closed: bool) -> Result<()> {
let k = EntityKind::Polyline3d(Polyline3d { points: self.pts.iter().map(|p| v3(*p)).collect(), closed });
let k = EntityKind::Polyline3d(Polyline3d { points: self.pts.clone(), closed });
match (self.handle, self.pts.len() >= 2) {
(Some(h), true) => s.doc_mut()?.modify_entity(h, |e| e.kind = k)?,
(None, true) => self.handle = Some(s.add_entity(k)?),
@@ -53,14 +54,15 @@ impl Interactive for Poly3dM {
fn prompt(&self, _s: &Session) -> Prompt {
match self.pts.len() {
0 => Prompt::new("Specify start point of polyline", Accept::POINT),
1 | 2 => Prompt::new("Specify endpoint of line", Accept::POINT).kw(&["Undo"]).base_opt(self.pts.last().copied()),
_ => Prompt::new("Specify endpoint of line", Accept::POINT).kw(&["Close", "Undo"]).base_opt(self.pts.last().copied()),
1 | 2 => Prompt::new("Specify endpoint of line", Accept::POINT).kw(&["Undo"]).base_opt(self.pts.last().map(|p| p.xy())),
_ => Prompt::new("Specify endpoint of line", Accept::POINT).kw(&["Close", "Undo"]).base_opt(self.pts.last().map(|p| p.xy())),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Point(p) => {
if self.pts.last().is_none_or(|l| !l.near(p, 1e-12)) && self.pts.len() < MAX_GEN {
let p = p.to3(s.point_z());
if self.pts.last().is_none_or(|l| (*l - p).len() > 1e-12) && self.pts.len() < MAX_GEN {
self.pts.push(p);
self.sync(s, false)?;
}
@@ -80,7 +82,7 @@ impl Interactive for Poly3dM {
}
}
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
self.pts.last().map(|l| vec![line(*l, c)]).unwrap_or_default()
self.pts.last().map(|l| vec![line(l.xy(), c)]).unwrap_or_default()
}
}
+35 -1
View File
@@ -1,5 +1,5 @@
use cadcraft_doc::EntityKind;
use cadcraft_geom::{Arc, Vec2};
use cadcraft_geom::{Arc, Vec2, Vec3};
use serde_json::json;
use crate::{Input, Session};
@@ -1466,6 +1466,40 @@ fn poly3d_json_and_command_line() {
assert_eq!(s.state().unwrap().undo.len(), 2);
}
#[test]
fn poly3d_typed_points_keep_their_z() {
// A typed third number reaches the polyline (#1409, #1410): absolute `x,y,z`, relative
// `@dx,dy,dz`, and `@dx,dy`, which keeps the last point's Z, as in AutoCAD.
let mut s = Session::new();
s.cmdline("3dpoly 0,0,0 10,0,5 @0,10,-2 @5,0 #1,2,3").unwrap();
// A picked point lies on the XY plane.
s.input(Input::Point(Vec2::new(20.0, 20.0))).unwrap();
s.input(Input::Enter).unwrap();
assert!(s.running.is_none());
let EntityKind::Polyline3d(p) = last(&s) else { panic!("{:?}", last(&s)) };
let got: Vec<[f64; 3]> = p.points.iter().map(|v| [v.x, v.y, v.z]).collect();
assert_eq!(got, vec![[0.0, 0.0, 0.0], [10.0, 0.0, 5.0], [10.0, 10.0, 3.0], [15.0, 10.0, 3.0], [1.0, 2.0, 3.0], [20.0, 20.0, 0.0]]);
// LASTPOINT carries the Z of a typed point.
s.cmdline("3dpoly 0,0,0 4,5,6").unwrap();
assert_eq!(crate::sysvars::get(&s, "LASTPOINT"), Some(json!([4.0, 5.0, 6.0])));
s.input(Input::Enter).unwrap();
}
#[test]
fn poly3d_flat_and_vertical_segments() {
// Two numbers still give z = 0.
let mut s = Session::new();
s.cmdline("3dpoly 0,0 1,0 1,1 ").unwrap();
assert!(matches!(last(&s), EntityKind::Polyline3d(p) if p.points.len() == 3 && p.points.iter().all(|v| v.z == 0.0)));
// A point straight above the last one is a new vertex, not a repeat.
s.cmdline("3dpoly 0,0,0 0,0,5 ").unwrap();
assert!(matches!(last(&s), EntityKind::Polyline3d(p) if p.points.len() == 2 && p.points[1].z == 5.0));
// Undo drops the Z with its point.
s.cmdline("3dpoly 0,0,1 1,0,2 u 0,1,3 ").unwrap();
let EntityKind::Polyline3d(p) = last(&s) else { panic!("{:?}", last(&s)) };
assert_eq!(p.points, vec![Vec3::new(0.0, 0.0, 1.0), Vec3::new(0.0, 1.0, 3.0)]);
}
#[test]
fn mline_json_and_command_line() {
// Element offsets from the vertex path, sorted.
+3
View File
@@ -73,7 +73,10 @@ pub fn specs() -> Vec<CommandSpec> {
/// A programmatic undo/redo (`engine.execute`, MCP, control channel, scripts) first ends a running
/// command the way Esc does, exactly as `Session::start` does for Cmd+Z, the menu or the command
/// line. Otherwise it would swap the drawing under the command and pop the previous command's step.
/// As there, the value of an expression the frames are working out answers its prompt first: the
/// command it ends is the step to take back.
fn end_running_command(s: &mut Session) {
s.lisp_settle_answer();
if s.running.is_some() {
s.cancel();
}
+58
View File
@@ -382,6 +382,18 @@ pub fn specs() -> Vec<CommandSpec> {
)
.noundo(),
CommandSpec::new("document.switch", "Switch Drawing", run_switch).params("{index}").enabled(always).noundo(),
CommandSpec::new("document.next", "Next Drawing", |s, _| run_cycle(s, true))
.menu(&["Window", "Next Drawing"])
.key(if cfg!(target_os = "macos") { "Ctrl+Tab" } else { "Cmd+Tab" })
.params("{} → {index}: the open drawing after this one, the first after the last")
.enabled(always)
.noundo(),
CommandSpec::new("document.prev", "Previous Drawing", |s, _| run_cycle(s, false))
.menu(&["Window", "Previous Drawing"])
.key(if cfg!(target_os = "macos") { "Ctrl+Shift+Tab" } else { "Cmd+Shift+Tab" })
.params("{} → {index}: the open drawing before this one, the last before the first")
.enabled(always)
.noundo(),
CommandSpec::new("document.bytes", "Drawing as bytes", run_bytes)
.params("{format?: dxf, version?: 2000…2018, binary?: bool, portableFonts?: bool} → {data: base64, warnings?: what an image draws short of the drawing}")
.noundo(),
@@ -669,6 +681,14 @@ fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(usi
if s.doc()?.refedit.is_some() {
return Err(bad(cmd, "A block reference is being edited in place: finish with REFCLOSE (Save or Discard) before saving."));
}
// A saved drawing carries the folder's plot style tables its layouts use.
if is_drawing_file(path) {
let st = s.state_mut()?;
let mut d = st.drawing().clone();
if super::layout::keep_used_folder_copies(std::sync::Arc::make_mut(&mut d)) {
*st.drawing_arc_mut() = d;
}
}
let (bytes, notes) = write_bytes(s, cmd, path, opts)?;
let n = commit_save(s, path, &bytes, store)?;
if is_drawing_file(path) {
@@ -1028,6 +1048,17 @@ fn run_switch(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// `document.next` and `document.prev`: switch to the neighbouring open drawing, wrapping round at either end. With one drawing open nothing changes.
fn run_cycle(s: &mut Session, forward: bool) -> Result<Value> {
let count = s.docs.len();
if count < 2 {
return Ok(json!({ "index": s.active }));
}
let i = if forward { (s.active + 1) % count } else { (s.active + count - 1) % count };
run_switch(s, &json!({ "index": i }))?;
Ok(json!({ "index": i }))
}
fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
let fmt = str_param(p, "format").unwrap_or("dxf");
let opts = save_options("document.bytes", p)?;
@@ -1498,6 +1529,33 @@ mod tests {
s.execute("close", &json!({"index": 2})).unwrap();
assert_eq!(active_title(&s), "Drawing2");
}
#[test]
fn next_and_previous_drawing_wrap_round_and_end_the_running_command() {
let mut s = Session::new();
s.execute("new", &json!({})).unwrap();
s.execute("new", &json!({})).unwrap();
assert_eq!((s.docs.len(), s.active), (3, 2));
assert_eq!(s.execute("document.next", &json!({})).unwrap()["index"], 0, "after the last comes the first");
assert_eq!(s.active, 0);
assert_eq!(s.execute("document.prev", &json!({})).unwrap()["index"], 2, "before the first comes the last");
s.execute("document.prev", &json!({})).unwrap();
assert_eq!(s.active, 1);
s.cmdline("line").unwrap();
assert!(s.running.is_some());
s.execute("document.next", &json!({})).unwrap();
assert!(s.running.is_none(), "a command left running belongs to the drawing it started in");
assert_eq!(s.active, 2);
}
#[test]
fn next_drawing_with_one_drawing_open_changes_nothing() {
let mut s = Session::new();
assert_eq!(s.docs.len(), 1);
assert_eq!(s.execute("document.next", &json!({})).unwrap()["index"], 0);
assert_eq!(s.execute("document.prev", &json!({})).unwrap()["index"], 0);
assert_eq!(s.docs.len(), 1);
}
}
#[cfg(test)]
+3
View File
@@ -520,6 +520,9 @@ impl Session {
/// view being edited does not show are left out (the first grip left is the base grip), and it
/// is an error when none is left.
pub fn start_grip_edit(&mut self, hot: &[(Handle, usize)]) -> Result<()> {
// The value of an expression the frames are working out answers its prompt before the
// command it was typed in is cancelled for the grips.
self.lisp_settle_answer();
if self.running.is_some() {
self.cancel();
}
+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> = {
+2 -1
View File
@@ -281,7 +281,7 @@ pub(crate) fn z_at(s: &Session, p: Vec2) -> f64 {
}
/// The Z of `e` at the point of it nearest `p` (seen from above), when it has one there.
fn entity_z(e: &Entity, p: Vec2) -> Option<f64> {
pub(crate) fn entity_z(e: &Entity, p: Vec2) -> Option<f64> {
let on_segment = |a: Vec3, b: Vec3| {
let d = b.xy() - a.xy();
let l2 = d.dot(d);
@@ -308,6 +308,7 @@ fn entity_z(e: &Entity, p: Vec2) -> Option<f64> {
// Read in world coordinates already.
EntityKind::Circle(c) => Some(c.center.z),
EntityKind::Arc(a) => Some(a.center.z),
EntityKind::Ellipse(el) => Some(el.center.z),
EntityKind::Text(t) | EntityKind::AttDef(cadcraft_doc::Attrib { text: t, .. }) => Some(t.insert.z),
EntityKind::MText(t) => Some(t.insert.z),
EntityKind::Insert(i) => Some(i.insert.z),
+49 -10
View File
@@ -15,6 +15,7 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
use viewports::MviewM;
mod plotstyle;
pub(crate) use plotstyle::keep_used_folder_copies;
mod prompts;
mod viewports;
@@ -82,18 +83,18 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("pagesetup", "Page Setup Manager...", run_pagesetup)
.menu(&["File", "Page Setup Manager..."])
.params(
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|\"B4 (JIS)\"|\"Japanese Postcard\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|\"B4 (JIS)\"|\"Japanese Postcard\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}; layout \"Model\" keeps only plotStyleTable",
),
// PLOT and EXPORTPDF are undoable for what a plot keeps in the drawing (a folder table's
// copy, Model's table); a plot that changes nothing leaves no undo step.
CommandSpec::new("plot", "Print...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "plot")?, "plot"))
.menu(&["File", "Print..."])
.key("Cmd+P")
.alias(&["print"])
.params("{path? (else returns base64 `data`), layout?: current|\"Model\", device?: \"CADCraft PDF\"|\"CADCraft PNG\"|\"CADCraft SVG\" | a plotter from PLOTTERMANAGER | \"None\" (default: a layout's page setup device; Model, or \"None\": no device, PDF; a device sets the output format and the papers), paper?: the device's paper (default: a layout keeps its page setup's; Model takes the device's default), landscape?, fit?: bool, scale?: number | \"1:50\", center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?: bool, plotTransparency?: bool (default: the page setup's; PLOTTRANSPARENCYOVERRIDE 0/2 overrides it), plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]]} (typed or from the menu: the Plot dialog)")
.noundo(),
.params("{path? (else returns base64 `data`), layout?: current|\"Model\", device?: \"CADCraft PDF\"|\"CADCraft PNG\"|\"CADCraft SVG\" | a plotter from PLOTTERMANAGER | \"None\" (default: a layout's page setup device; Model, or \"None\": no device, PDF; a device sets the output format and the papers), paper?: the device's paper (default: a layout keeps its page setup's; Model takes the device's default), landscape?, fit?: bool, scale?: number | \"1:50\", center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?: bool, plotTransparency?: bool (default: the page setup's; PLOTTRANSPARENCYOVERRIDE 0/2 overrides it), plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]]} (typed or from the menu: the Plot dialog)"),
CommandSpec::new("exportpdf", "Export to PDF...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "exportpdf")?, "exportpdf"))
.menu(&["File", "Export to PDF..."])
.params("{path? (else returns base64 `data`), layout?, device? (its papers; the output stays PDF), paper?, landscape?, fit?, scale?, center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?, plotTransparency?, plotArea?, window?} (as PLOT)")
.noundo(),
.params("{path? (else returns base64 `data`), layout?, device? (its papers; the output stays PDF), paper?, landscape?, fit?, scale?, center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?, plotTransparency?, plotArea?, window?} (as PLOT)"),
CommandSpec::new("mspace", "Model Space (in viewport)", run_mspace)
.alias(&["ms"])
.params("{handle?: viewport, at?: [x,y] paper point inside a viewport} (default: the last active or first viewport)")
@@ -812,13 +813,27 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
"plotTransparency",
];
let changes = keys.iter().any(|k| p.get(k).is_some());
// Model keeps only its plot style table (the rest of its plot settings are chosen per plot).
if str_param(p, "layout").is_some_and(|n| n.eq_ignore_ascii_case("model")) {
if let Some(k) = keys.iter().find(|k| **k != "plotStyleTable" && p.get(**k).is_some()) {
return Err(bad(cmd, format!("Model keeps only `plotStyleTable`; `{k}` is chosen for each plot")));
}
if let Some(v) = str_param(p, "plotStyleTable")
&& plotstyle::table_choice_changes(s.doc()?, v, true)
&& plotstyle::set_model_table(s.doc_mut()?, v)
{
s.touch();
}
let table = s.doc()?.model_page.as_ref().map(|m| m.plot_style_table.clone()).unwrap_or_default();
return Ok(json!({ "layout": "Model", "page": { "plotStyleTable": table } }));
}
let name = match str_param(p, "layout") {
Some(n) => Some(layout_name(cmd, s.doc()?, n)?),
None => s.space().layout().map(str::to_string),
};
let Some(name) = name else {
if changes {
return Err(bad(cmd, "pass `layout` (model-space page setups are not stored yet)"));
return Err(bad(cmd, "pass `layout` (Model keeps only its `plotStyleTable`, with `layout: \"Model\"`)"));
}
// Report every layout's page setup.
let d = s.doc()?;
@@ -927,6 +942,8 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
}
if let Some(v) = str_param(p, "plotStyleTable") {
page.plot_style_table = v.chars().take(260).collect();
// A table from the user's plot style folder travels with the drawing.
plotstyle::keep_folder_copy(s.doc_mut()?, &page.plot_style_table);
}
if let Some(v) = p.get("displayPlotStyles").and_then(Value::as_bool) {
page.show_plot_styles = v;
@@ -1057,7 +1074,7 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
};
let pages = sheets.as_ref().map_or(1, Vec::len);
let format = opts.get("output").and_then(Value::as_str).map(str::to_ascii_lowercase).unwrap_or_else(|| "pdf".into());
match str_param(p, "path") {
let r = match str_param(p, "path") {
Some(_path) => {
#[cfg(not(target_arch = "wasm32"))]
{
@@ -1070,22 +1087,44 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
let mut r = json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_new_folder(s, &mut r, folder);
super::file::report_notes(s, &mut r, notes);
Ok(r)
r
}
#[cfg(target_arch = "wasm32")]
{
super::exchange::deliver_file(cmd, _path, &bytes, super::file::deliver())?;
let mut r = json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_notes(s, &mut r, notes);
Ok(r)
r
}
}
None => {
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_notes(s, &mut r, notes);
Ok(r)
r
}
};
// A table from the user's plot style folder that a plot used travels with the drawing, as
// one chosen in a page setup does, and Model, which has no page setup dialog of its own,
// remembers the table it last plotted with. A preview (an image with no file) changes nothing,
// and so does a plot whose output was refused or failed: this runs only once it is written.
if let Some(table) = str_param(p, "plotStyleTable")
&& (str_param(p, "path").is_some() || !is_image)
{
// Model is the sheet plotted when `layouts` names it alone, whatever tab is showing.
let model = match sheets.as_deref() {
Some(names) => matches!(names, [only] if only.eq_ignore_ascii_case("model")),
None => matches!(space, Space::Model),
};
// Checked first: `doc_mut` copies the drawing, which records an undo step even for no change.
if plotstyle::table_choice_changes(s.doc()?, table, model) {
let d = s.doc_mut()?;
let changed = if model { plotstyle::set_model_table(d, table) } else { plotstyle::keep_folder_copy(d, table) };
if changed {
s.touch();
}
}
}
Ok(r)
}
/// The model-space rectangle a plot of `plotArea` covers: `extents` (default) plots everything,
+296 -40
View File
@@ -1,9 +1,16 @@
//! Plot styles: PLOTSTYLE (an object's or the current named plot style) and STYLESMANAGER (the
//! plot style tables: list, view, create, edit, delete, load and save in our own file format).
//! plot style tables: list, view, create, edit, rename, delete, load and save in our own file
//! format).
//!
//! Tables the drawing keeps live in `Drawing::plot_style_tables` and are saved with it; they
//! shadow built-in tables of the same name. Editing a built-in table stores an edited copy in
//! the drawing.
//! A table lives in the user's plot style folder ([`super::super::plotstyle_folder`]), which
//! every drawing can use, or in the drawing (`Drawing::plot_style_tables`, saved with it). The
//! drawing's table wins over a folder's of the same name, and both over a built-in one. A page
//! setup (a layout's or Model's) or a plot that uses a folder table takes a copy of it into the
//! drawing, which from then on plots with its copy whatever happens to the file. Editing a
//! built-in table stores an edited copy in the drawing.
//!
//! Changes to the folder's files are written at once: UNDO takes back the drawing's copy, not the
//! file.
use cadcraft_doc::{Drawing, PlotStyle, PlotStyleKind, PlotStyleTable};
use serde_json::{Value, json};
@@ -21,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("stylesmanager", "Plot Style Manager...", run_stylesmanager)
.menu(&["File", "Plot Styles..."])
.params(
"{action?: list (default)|get|new|set|delete|load|save, name?: table (\"x.ctb\"/\"x.stb\"), kind?: colorDependent|named (new), from?: table to copy (new), description?, style?: {name, color?: \"#rrggbb\"|null, grayscale?, screening?: 0-100, linetype?: name|null, lineweight?: mm|null, end?, join?, fill?, description?} (set), removeStyle?: name (set, named tables), path? (load/save; save without one returns `text`), text? (load)}",
"{action?: list (default)|get|new|set|rename|delete|load|save|reload, name?: table (\"x.ctb\"/\"x.stb\"), where?: folder|drawing (new, load: default drawing; get, set, rename, delete: default the drawing's table, else the folder's), kind?: colorDependent|named (new), from?: table to copy (new), fromWhere?: folder|drawing (new: where `from` is; default the drawing's table, else the folder's, else built-in), description?, style?: {name, color?: \"#rrggbb\"|null, grayscale?, screening?: 0-100, linetype?: name|null, lineweight?: mm|null, end?, join?, fill?, description?} (set), removeStyle?: name (set, named tables), to?: new name (rename), path? (load/save; save without one returns `text`), text? (load)} (folder tables are files in the settings folder's `plotstyles` folder; list reports it in `folder`)",
),
]
}
@@ -93,18 +100,165 @@ fn run_plotstyle(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- STYLESMANAGER ----------
fn in_drawing(d: &Drawing, name: &str) -> bool {
d.plot_style_tables.iter().any(|x| x.name.eq_ignore_ascii_case(name.trim()))
}
fn in_folder(name: &str) -> bool {
cadcraft_doc::plot_style_folder_table(name).is_some()
}
fn table_summary(d: &Drawing, t: &PlotStyleTable) -> Value {
let in_drawing = d.plot_style_tables.iter().any(|x| x.name.eq_ignore_ascii_case(&t.name));
let drawing = in_drawing(d, &t.name);
let folder = in_folder(&t.name);
json!({
"name": t.name,
"description": t.description,
"kind": if t.is_color_dependent() { "colorDependent" } else { "named" },
"styles": t.styles.len(),
"inDrawing": in_drawing,
"builtin": PlotStyleTable::builtin(&t.name).is_some() && !in_drawing,
"source": if drawing { "drawing" } else if folder { "folder" } else { "builtin" },
"inFolder": folder,
"inDrawing": drawing,
"builtin": PlotStyleTable::builtin(&t.name).is_some() && !drawing && !folder,
})
}
/// Where a table goes or comes from.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Where {
Folder,
Drawing,
}
fn where_param(cmd: &str, p: &Value) -> Result<Option<Where>> {
place_param(cmd, p, "where")
}
/// A place parameter (`where`, or `fromWhere` for `new`'s `from`): folder or drawing.
fn place_param(cmd: &str, p: &Value, key: &str) -> Result<Option<Where>> {
match str_param(p, key).map(str::to_ascii_lowercase).as_deref() {
None => Ok(None),
Some("folder") => Ok(Some(Where::Folder)),
Some("drawing") => Ok(Some(Where::Drawing)),
Some(_) => Err(bad(cmd, format!("`{key}` must be folder or drawing"))),
}
}
/// `name` with the ending a table of `t`'s kind needs (added when it has none), at most 255
/// characters with it: the length every action that looks a table up reads (`table_name`).
fn with_ending(cmd: &str, t: &PlotStyleTable, name: &str) -> Result<String> {
let ext = if t.is_color_dependent() { ".ctb" } else { ".stb" };
let lower = name.to_ascii_lowercase();
if !lower.ends_with(ext) && (lower.ends_with(".ctb") || lower.ends_with(".stb")) {
return Err(bad(cmd, format!("a {} table's name ends in {ext}", if ext == ".ctb" { "colour-dependent" } else { "named" })));
}
let full = if lower.ends_with(ext) { name.to_string() } else { format!("{name}{ext}") };
if full.chars().count() > 255 {
return Err(bad(cmd, "a plot style table's name is at most 255 characters, with its ending"));
}
Ok(full)
}
/// Write `t` to the plot style folder.
fn write_folder(cmd: &str, t: &PlotStyleTable) -> Result<()> {
super::super::plotstyle_folder::write(t).map_err(|e| bad(cmd, e))
}
/// Copy the folder's table `name` into `d` when `d` has no table of that name: a layout that
/// chooses a folder table takes it into the drawing, and the drawing then plots with its copy
/// whatever later happens to the file. A table the drawing already has is left as it is.
/// Returns whether a copy was taken.
pub(super) fn keep_folder_copy(d: &mut Drawing, name: &str) -> bool {
let name = name.trim();
if !needs_folder_copy(d, name) {
return false;
}
match cadcraft_doc::plot_style_folder_table(name) {
Some(t) => {
store(d, t);
true
}
None => false,
}
}
/// Whether the drawing lacks the folder table `name`, which `keep_folder_copy` would copy in.
fn needs_folder_copy(d: &Drawing, name: &str) -> bool {
let name = name.trim();
!cadcraft_doc::no_plot_style_table(name) && !in_drawing(d, name) && cadcraft_doc::plot_style_folder_table(name).is_some()
}
/// `name` as Model's page setup keeps it: empty for no table.
fn model_name(name: &str) -> String {
let name: String = name.trim().chars().take(260).collect();
if cadcraft_doc::no_plot_style_table(&name) { String::new() } else { name }
}
/// Whether Model's table is something other than `name` (as `model_name` keeps it).
fn model_differs(d: &Drawing, name: &str) -> bool {
let current = d.model_page.as_ref().map(|p| p.plot_style_table.trim()).unwrap_or_default();
!current.eq_ignore_ascii_case(name)
}
/// Whether choosing `name` would change `d`: Model's table (`model`), or a folder copy the
/// drawing lacks. Read first, as changing the drawing copies it and records an undo step.
pub(crate) fn table_choice_changes(d: &Drawing, name: &str, model: bool) -> bool {
(model && model_differs(d, &model_name(name))) || needs_folder_copy(d, name)
}
/// Remember `name` as Model's plot style table. Model keeps no other page settings here, so its
/// page setup is the one the DXF writer gives it otherwise, with this table; `"None"` or an empty
/// name clears it. A folder table is copied into the drawing. Returns whether anything changed.
pub(crate) fn set_model_table(d: &mut Drawing, name: &str) -> bool {
let name = model_name(name);
let changed = model_differs(d, &name);
if changed {
d.model_page
.get_or_insert_with(|| cadcraft_doc::PageSetup { plot_area: "extents".into(), scale_to_fit: true, ..Default::default() })
.plot_style_table = name.clone();
}
keep_folder_copy(d, &name) || changed
}
/// Copy into `d` every folder table its page setups (each layout's and Model's) use that it
/// doesn't have yet, so a saved drawing carries all its plot style tables (like the built-in
/// ones, it then plots the same on a computer without the files). Returns whether anything was
/// copied.
pub(crate) fn keep_used_folder_copies(d: &mut Drawing) -> bool {
let used: Vec<String> = d.layouts.iter().map(|l| &l.page).chain(d.model_page.as_ref()).map(|page| page.plot_style_table.clone()).collect();
let mut copied = false;
for name in used {
copied |= keep_folder_copy(d, &name);
}
copied
}
/// Which table `name` an action works on: `where` when given, else the drawing's (the one its
/// layouts plot with), else the folder's. `None` for a table in neither (a built-in one).
fn place_of(cmd: &str, s: &Session, p: &Value, name: &str) -> Result<Option<Where>> {
Ok(match where_param(cmd, p)? {
Some(w) => Some(w),
None if in_drawing(s.doc()?, name) => Some(Where::Drawing),
None if in_folder(name) => Some(Where::Folder),
None => None,
})
}
/// Table `name` from `place`, or as the drawing sees it when `place` is `None`.
fn table_at(cmd: &str, d: &Drawing, name: &str, place: Option<Where>) -> Result<PlotStyleTable> {
let found = match place {
Some(Where::Drawing) => d.plot_style_tables.iter().find(|t| t.name.eq_ignore_ascii_case(name.trim())).cloned(),
Some(Where::Folder) => cadcraft_doc::plot_style_folder_table(name.trim()),
None => cadcraft_doc::plot_style_table(d, name),
};
let here = match place {
Some(Where::Drawing) => " in the drawing",
Some(Where::Folder) => " in the plot style folder",
None => "",
};
found.ok_or_else(|| bad(cmd, format!("no plot style table `{name}`{here}")))
}
fn table_name(cmd: &str, p: &Value) -> Result<String> {
let n = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "`name` (the table) is required"))?;
Ok(n.chars().take(255).collect())
@@ -192,18 +346,30 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "stylesmanager";
let action = str_param(p, "action").unwrap_or("list").to_ascii_lowercase();
match action.as_str() {
"list" => {
"list" | "reload" => {
if action == "reload" {
super::super::plotstyle_folder::reload();
for st in &mut s.docs {
st.revision += 1;
}
}
let d = s.doc()?;
let tables: Vec<Value> = cadcraft_doc::plot_style_table_names(d)
.iter()
.filter_map(|n| cadcraft_doc::plot_style_table(d, n))
.map(|t| table_summary(d, &t))
.collect();
Ok(json!({ "tables": tables }))
Ok(json!({
"tables": tables,
"folder": super::super::plotstyle_folder::location(),
"warnings": super::super::plotstyle_folder::warnings(),
}))
}
"get" => {
let name = table_name(cmd, p)?;
let place = where_param(cmd, p)?;
let d = s.doc()?;
let t = find_table(cmd, d, &table_name(cmd, p)?)?;
let t = table_at(cmd, d, &name, place)?;
let mut v = serde_json::to_value(&t).unwrap_or(Value::Null);
if let (Some(o), Value::Object(sum)) = (v.as_object_mut(), table_summary(d, &t)) {
o.insert("inDrawing".into(), sum.get("inDrawing").cloned().unwrap_or(Value::Null));
@@ -215,7 +381,8 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
let mut name = table_name(cmd, p)?;
let d = s.doc()?;
let mut t = match str_param(p, "from") {
Some(from) => find_table(cmd, d, from)?,
// A name both the drawing and the folder hold: `fromWhere` says which to copy.
Some(from) => table_at(cmd, d, from, place_param(cmd, p, "fromWhere")?)?,
None => {
let named = match str_param(p, "kind").map(str::to_ascii_lowercase).as_deref() {
None if name.to_ascii_lowercase().ends_with(".stb") => true,
@@ -226,15 +393,13 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
if named { PlotStyleTable::named("", "", Vec::new()) } else { PlotStyleTable::color_dependent("", "", |_| None) }
}
};
let ext = if t.is_color_dependent() { ".ctb" } else { ".stb" };
let lower = name.to_ascii_lowercase();
if !lower.ends_with(ext) {
if lower.ends_with(".ctb") || lower.ends_with(".stb") {
return Err(bad(cmd, format!("a {} table's name ends in {ext}", if ext == ".ctb" { "colour-dependent" } else { "named" })));
}
name.push_str(ext);
}
if d.plot_style_tables.iter().any(|x| x.name.eq_ignore_ascii_case(&name)) {
name = with_ending(cmd, &t, &name)?;
let place = where_param(cmd, p)?.unwrap_or(Where::Drawing);
let taken = match place {
Where::Folder => in_folder(&name),
Where::Drawing => in_drawing(d, &name),
};
if taken {
return Err(bad(cmd, format!("plot style table `{name}` already exists")));
}
t.name = name;
@@ -242,13 +407,19 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
t.description = desc.chars().take(255).collect();
}
let t = t.sanitized();
let out = table_summary(d, &t);
store(s.doc_mut()?, t);
Ok(out)
match place {
Where::Folder => {
write_folder(cmd, &t)?;
s.touch();
}
Where::Drawing => store(s.doc_mut()?, t.clone()),
}
Ok(table_summary(s.doc()?, &t))
}
"set" => {
let name = table_name(cmd, p)?;
let mut t = find_table(cmd, s.doc()?, &name)?;
let place = place_of(cmd, s, p, &name)?;
let mut t = table_at(cmd, s.doc()?, &name, place)?;
if let Some(desc) = str_param(p, "description") {
t.description = desc.chars().take(255).collect();
}
@@ -306,19 +477,18 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
o.insert("removedStyle".into(), json!(r.trim()));
}
}
store(s.doc_mut()?, t);
// The folder's file is written, and the drawings that keep a copy of it keep their copy;
// a built-in table edited keeps an edited copy in the drawing.
if place == Some(Where::Folder) {
write_folder(cmd, &t)?;
s.touch();
} else {
store(s.doc_mut()?, t);
}
Ok(out)
}
"delete" => {
let name = table_name(cmd, p)?;
let d = s.doc_mut()?;
let before = d.plot_style_tables.len();
d.plot_style_tables.retain(|t| !t.name.eq_ignore_ascii_case(&name));
if d.plot_style_tables.len() == before {
return Err(bad(cmd, format!("the drawing keeps no plot style table `{name}` (built-in tables can't be deleted)")));
}
Ok(json!({ "deleted": name }))
}
"rename" => run_rename(s, p, cmd),
"delete" => run_delete(s, p, cmd),
"load" => {
let text = match (str_param(p, "text"), str_param(p, "path")) {
(Some(t), _) => t.to_string(),
@@ -342,9 +512,15 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
if t.name.is_empty() {
return Err(bad(cmd, "the table has no name: pass `name`"));
}
let out = table_summary(s.doc()?, &t);
store(s.doc_mut()?, t);
Ok(out)
t.name = with_ending(cmd, &t, &t.name.clone())?;
match where_param(cmd, p)?.unwrap_or(Where::Drawing) {
Where::Folder => {
write_folder(cmd, &t)?;
s.touch();
}
Where::Drawing => store(s.doc_mut()?, t.clone()),
}
Ok(table_summary(s.doc()?, &t))
}
"save" => {
let name = table_name(cmd, p)?;
@@ -364,6 +540,86 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
other => Err(bad(cmd, format!("unknown action `{other}` (list, get, new, set, delete, load, save)"))),
other => Err(bad(cmd, format!("unknown action `{other}` (list, get, new, set, rename, delete, load, save, reload)"))),
}
}
/// STYLESMANAGER rename: the folder's file, or the drawing's table and the layouts (and Model)
/// of this drawing that use it. Renaming the file leaves the drawings' copies as they are.
fn run_rename(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
let name = table_name(cmd, p)?;
let to = str_param(p, "to").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "`to` (the new name) is required"))?;
let Some(place) = place_of(cmd, s, p, &name)? else {
return Err(bad(
cmd,
format!("no plot style table `{name}` in the folder or the drawing (built-in tables can't be renamed: copy one with `new` and `from`)"),
));
};
let mut t = table_at(cmd, s.doc()?, &name, Some(place))?;
let old = t.name.clone();
let to = with_ending(cmd, &t, to)?;
let same = to.eq_ignore_ascii_case(&old);
let taken = match place {
Where::Folder => in_folder(&to),
Where::Drawing => in_drawing(s.doc()?, &to),
};
if !same && taken {
return Err(bad(cmd, format!("plot style table `{to}` already exists")));
}
t.name = to.clone();
let mut layouts = 0usize;
match place {
Where::Folder => {
write_folder(cmd, &t)?;
if !same && let Err(e) = super::super::plotstyle_folder::delete(&old) {
// Take the new file back, so the table isn't held twice and the rename can be tried again.
let undone = super::super::plotstyle_folder::delete(&to);
let left = if undone.is_ok() { "the table keeps its old name" } else { "both files now hold the table" };
return Err(bad(cmd, format!("can't remove `{old}` from the plot style folder ({e}); {left}")));
}
s.touch();
}
Where::Drawing => {
let d = s.doc_mut()?;
for x in d.plot_style_tables.iter_mut().filter(|x| x.name.eq_ignore_ascii_case(&old)) {
x.name = to.clone();
}
for l in d.layouts.iter_mut().filter(|l| l.page.plot_style_table.trim().eq_ignore_ascii_case(&old)) {
l.page.plot_style_table = to.clone();
layouts += 1;
}
if let Some(m) = d.model_page.as_mut().filter(|m| m.plot_style_table.trim().eq_ignore_ascii_case(&old)) {
m.plot_style_table = to.clone();
}
}
}
Ok(json!({ "name": to, "renamed": old, "layouts": layouts, "where": if place == Where::Folder { "folder" } else { "drawing" } }))
}
/// STYLESMANAGER delete: the drawing's table or the folder's file.
fn run_delete(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
let name = table_name(cmd, p)?;
let place = match where_param(cmd, p)? {
Some(w) => w,
None if in_drawing(s.doc()?, &name) => Where::Drawing,
None if in_folder(&name) => Where::Folder,
None => {
return Err(bad(cmd, format!("no plot style table `{name}` in the folder or the drawing (built-in tables can't be deleted)")));
}
};
match place {
Where::Folder => {
super::super::plotstyle_folder::delete(&name).map_err(|e| bad(cmd, e))?;
s.touch();
}
Where::Drawing => {
let d = s.doc_mut()?;
let before = d.plot_style_tables.len();
d.plot_style_tables.retain(|t| !t.name.eq_ignore_ascii_case(&name));
if d.plot_style_tables.len() == before {
return Err(bad(cmd, format!("the drawing keeps no plot style table `{name}` (built-in tables can't be deleted)")));
}
}
}
Ok(json!({ "deleted": name, "where": if place == Where::Folder { "folder" } else { "drawing" } }))
}
+59 -4
View File
@@ -1,3 +1,5 @@
use crate::cmd::helpers::v3;
use super::{
Accept, Arc, EngineError, Entity, EntityKind, Handle, Input, Interactive, Line, PolyVertex, Prompt, Result, Session, Step, Value, Vec2, arc, bad,
bool_or, ccw_sweep, f64_or, json, line, line_line_infinite, number, point_param,
@@ -7,15 +9,43 @@ use super::{
/// What CHAMFER takes (as in AutoCAD, not arcs, circles, ellipses or splines).
const CHAMFER_LINES_ONLY: &str =
"CHAMFER works on lines (and polylines with the Polyline option); it cannot chamfer arcs, circles, ellipses or splines.";
"CHAMFER works on lines, rays and xlines (and polylines with the Polyline option); it cannot chamfer arcs, circles, ellipses or splines.";
fn as_line(e: &Entity) -> Option<Line> {
match &e.kind {
EntityKind::Line(l) => Some(Line::new(l.a.xy(), l.b.xy())),
EntityKind::Ray(r) | EntityKind::XLine(r) => Some(half_line(r, Some(true))),
_ => None,
}
}
/// Both objects as lines for FILLET and CHAMFER, an xline as the half-line from its base towards
/// the side picked of the corner: a line starting 1e8 away puts the corner ~1e-8 off.
fn fillet_pair(e1: &Entity, p1: Vec2, e2: &Entity, p2: Vec2) -> Option<(Line, Line)> {
let (l1, l2) = (as_line(e1)?, as_line(e2)?);
let Some((x, _, _)) = line_line_infinite(l1.a, l1.b, l2.a, l2.b) else { return Some((l1, l2)) };
let side = |e: &Entity, l: Line, p: Vec2| match &e.kind {
EntityKind::XLine(r) => {
let t = r.dir.xy().dot(p - x);
half_line(r, (t != 0.0).then_some(t > 0.0))
}
_ => l,
};
Some((side(e1, l1, p1), side(e2, l2, p2)))
}
/// A ray or xline as a line from its base whose far end lies beyond any corner, so that FILLET
/// and CHAMFER keep the picked side; `unbounded_after_fillet` makes the unbounded ends rays
/// again. With no side (a pick on the corner itself), both far ends.
fn half_line(r: &cadcraft_doc::RayLine, forward: Option<bool>) -> Line {
let (base, dir) = (r.base.xy(), r.dir.xy().normalized());
match forward {
Some(true) => Line::new(base, base + dir * 1e8),
Some(false) => Line::new(base, base - dir * 1e8),
None => Line::new(base - dir * 1e8, base + dir * 1e8),
}
}
/// Fillet (or chamfer) two lines. `p1`/`p2` mark the kept side of each line.
pub(crate) fn fillet_lines(
s: &mut Session,
@@ -32,7 +62,7 @@ pub(crate) fn fillet_lines(
let d = s.doc()?;
let e1 = d.entity(h1).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?;
let e2 = d.entity(h2).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?;
let (Some(l1), Some(l2)) = (as_line(&e1), as_line(&e2)) else {
let Some((l1, l2)) = fillet_pair(&e1, p1, &e2, p2) else {
if chamfer.is_none() {
return crate::cmd::modify2::fillet_curves(s, h1, p1, h2, p2, radius);
}
@@ -487,17 +517,18 @@ fn fillet_corner(s: &mut Session, h1: Handle, p1: Vec2, h2: Handle, p2: Vec2, r:
let d = s.doc()?;
let k1 = d.entity(h1).map(|e| e.kind.clone());
let k2 = d.entity(h2).map(|e| e.kind.clone());
let pair = || fillet_pair(d.entity(h1)?, p1, d.entity(h2)?, p2);
let chamfer = match cut {
None => None,
Some(c) => {
let l = |h| d.entity(h).and_then(|e| as_line(e)).ok_or_else(|| EngineError::Other(CHAMFER_LINES_ONLY.into()));
let (l1, l2) = (l(h1)?, l(h2)?);
let (l1, l2) = pair().ok_or_else(|| EngineError::Other(CHAMFER_LINES_ONLY.into()))?;
let (x, _, _) = line_line_infinite(l1.a, l1.b, l2.a, l2.b).ok_or_else(|| EngineError::Other("Lines are parallel.".into()))?;
// The direction along each line towards its picked side.
let dir = |l: &Line, p: Vec2| if (l.a - x).dot(p - x) >= (l.b - x).dot(p - x) { (l.a - x).normalized() } else { (l.b - x).normalized() };
Some(c.distances(dir(&l1, p1), dir(&l2, p2))?)
}
};
let lines = pair().is_some();
let made = fillet_lines(s, h1, p1, h2, p2, r, chamfer)?;
if !trim {
let doc = s.doc_mut()?;
@@ -506,10 +537,34 @@ fn fillet_corner(s: &mut Session, h1: Handle, p1: Vec2, h2: Handle, p2: Vec2, r:
doc.modify_entity(h, |e| e.kind = k)?;
}
}
} else if lines {
for (h, k) in [(h1, &k1), (h2, &k2)] {
if let Some(k) = k {
unbounded_after_fillet(s, h, k)?;
}
}
}
Ok(made)
}
/// What FILLET or CHAMFER leaves of a ray or xline `was`, trimmed by `fillet_lines` as a line to
/// the corner: a ray where the picked side is unbounded, as in AutoCAD (#1235).
fn unbounded_after_fillet(s: &mut Session, h: Handle, was: &EntityKind) -> Result<()> {
let (EntityKind::Ray(r) | EntityKind::XLine(r)) = was else { return Ok(()) };
// The far end `half_line` gave it, if `fillet_lines` kept one; a ray never has the backward one.
let far = [half_line(r, Some(true)).b, half_line(r, Some(false)).b];
let doc = s.doc_mut()?;
let Some(EntityKind::Line(l)) = doc.entity(h).map(|e| e.kind.clone()) else { return Ok(()) };
let (kept, t) = match (l.a.xy(), l.b.xy()) {
(a, b) if far.contains(&a) => (a, b),
(a, b) if far.contains(&b) => (b, a),
_ => return Ok(()),
};
let ray = cadcraft_doc::RayLine { base: v3(t), dir: v3((kept - t).normalized()) };
doc.modify_entity(h, |e| e.kind = EntityKind::Ray(ray))?;
Ok(())
}
/// CHAMFER Polyline: cut every corner between two straight segments of a 2D polyline. Returns
/// how many corners were chamfered.
fn chamfer_polyline(s: &mut Session, h: Handle, cut: ChamferCut) -> Result<usize> {
+15 -4
View File
@@ -116,7 +116,10 @@ impl SelectThen {
Some((f, from)) => (Mat3::scale_about(base, f), from),
None => return self.ref_from.map(|a| vec![line(a, c)]).unwrap_or_default(),
},
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
Op::Mirror => match self.mirror_end(c) {
Some(end) => (Mat3::mirror(base, end), base),
None => return Vec::new(),
},
_ => return Vec::new(),
};
let Ok(d) = s.doc() else { return Vec::new() };
@@ -135,7 +138,9 @@ impl SelectThen {
k
})
.collect();
out.push(line(rubber_from, c));
if !self.ask_erase {
out.push(line(rubber_from, c));
}
out
}
/// The drag with the cursor at `c` and the base point at `base`.
@@ -148,10 +153,10 @@ impl SelectThen {
let (f, from) = self.scale_reference_factor(base, c)?;
(Mat3::scale_about(base, f), from)
}
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
Op::Mirror => (Mat3::mirror(base, self.mirror_end(c)?), base),
_ => return None,
};
let mut extra = vec![line(rubber_from, c)];
let mut extra = if self.ask_erase { Vec::new() } else { vec![line(rubber_from, c)] };
if self.op != Op::Mirror {
return Some(crate::prompt::Drag { handles: self.objs.clone(), matrix, extra, clipboard: false });
}
@@ -489,6 +494,12 @@ impl SelectThen {
s.set_selection(Vec::new());
Ok(Step::Done)
}
/// The second point of MIRROR's line: the cursor while it is picked, then the picked point,
/// so the mirrored copy stays on screen at "Erase source objects?" (#2667).
fn mirror_end(&self, cursor: Vec2) -> Option<Vec2> {
if self.ask_erase { self.pts.get(1).copied() } else { Some(cursor) }
}
}
/// Objects MIRROR must preview individually: readable text and hatches retaining fill direction.
+4 -1
View File
@@ -117,7 +117,10 @@ fn prim_to_segments(p: &Prim) -> Vec<Segment> {
match p {
Prim::Seg(s) => vec![*s],
Prim::Circle(c) => vec![Segment::Arc { arc: Arc { center: c.center, radius: c.radius, start: 0.0, end: TAU - 1e-12 }, ccw: true }],
Prim::Infinite { base, dir, .. } => vec![Segment::Line(Line::new(*base - *dir * 1e8, *base + *dir * 1e8))],
Prim::Infinite { base, dir, ray } => {
let start = if *ray { *base } else { *base - *dir * 1e8 };
vec![Segment::Line(Line::new(start, *base + *dir * 1e8))]
}
Prim::Ellipse(e) => {
let mut pts = Vec::new();
e.tessellate(e.major.len() * 1e-4, &mut pts);
+54 -4
View File
@@ -1,7 +1,7 @@
use super::{Ellipse, EntityKind, Line, Result, Segment, TAU, Vec2, ccw_sweep, curve_edits, curves, intersect_ext, norm_angle, other, v3};
use super::{Ellipse, EntityKind, Line, Result, Segment, TAU, Vec2, ccw_sweep, curve_edits, curves, intersect_ext, line, norm_angle, other, v3};
// =====================================================================================
// TRIM / EXTEND for ellipses and splines
// TRIM / EXTEND for ellipses, splines and unbounded lines
// =====================================================================================
pub(super) fn ellipse_of(e: &cadcraft_doc::Ellipse) -> Ellipse {
@@ -63,7 +63,7 @@ fn ellipse_samples(ge: &Ellipse) -> Vec<f64> {
(0..=n).map(|i| ge.start + sw * i as f64 / n as f64).collect()
}
/// Trim objects that modify.rs does not handle itself (ellipses and splines).
/// Trim objects that modify.rs does not handle itself (ellipses, splines, rays and xlines).
pub(crate) fn trim_other(k: &EntityKind, cut: &[Segment], pick: Vec2) -> Result<Vec<EntityKind>> {
let none = || other("Object does not intersect a cutting edge.");
match k {
@@ -142,11 +142,49 @@ pub(crate) fn trim_other(k: &EntityKind, cut: &[Segment], pick: Vec2) -> Result<
}
Ok(v)
}
EntityKind::Ray(rl) | EntityKind::XLine(rl) => {
// As in AutoCAD, a piece with two ends is a line and an unbounded one a ray (#1235).
let xline = matches!(k, EntityKind::XLine(_));
let (base, dir) = (rl.base.xy(), rl.dir.xy().normalized());
// An xline is cut as two half-lines from its base: a segment starting 1e8 away puts
// the cut points ~1e-8 off, enough for a later TRIM to see the edge again.
let sides: &[f64] = if xline { &[1e8, -1e8] } else { &[1e8] };
let mut ts: Vec<f64> = sides
.iter()
.map(|far| Segment::Line(Line::new(base, base + dir * *far)))
.flat_map(|half| cut.iter().flat_map(move |c| intersect_ext(&half, c, false)))
.map(|x| (x - base).dot(dir))
.filter(|t| xline || *t > 1e-9)
.collect();
ts.sort_by(f64::total_cmp);
let tp = (pick - base).dot(dir);
let found = ts.len();
ts.retain(|t| (t - tp).abs() > 5e-7);
if found > 0 && ts.is_empty() {
return Err(other("The pick is on the cut: nothing to trim."));
}
let lo = ts.iter().copied().rfind(|t| *t < tp);
let hi = ts.iter().copied().find(|t| *t > tp);
if lo.is_none() && hi.is_none() {
return Err(none());
}
let ray = |p: Vec2, d: Vec2| EntityKind::Ray(cadcraft_doc::RayLine { base: v3(p), dir: v3(d) });
let mut v = Vec::new();
match lo {
Some(t) if xline => v.push(ray(base + dir * t, -dir)),
Some(t) => v.push(line(base, base + dir * t)),
None => {}
}
if let Some(t) = hi {
v.push(ray(base + dir * t, dir));
}
Ok(v)
}
_ => Err(other("Cannot trim that object.")),
}
}
/// Extend objects that modify.rs does not handle itself (elliptical arcs and open splines).
/// Extend objects that modify.rs does not handle itself (elliptical arcs, open splines and rays).
pub(crate) fn extend_other(k: &EntityKind, cut: &[Segment], pick: Vec2) -> Result<EntityKind> {
match k {
EntityKind::Ellipse(e) => {
@@ -171,6 +209,18 @@ pub(crate) fn extend_other(k: &EntityKind, cut: &[Segment], pick: Vec2) -> Resul
Ok(ellipse_kind(&if from_end { Ellipse { end: t, ..ge } } else { Ellipse { start: t, ..ge } }))
}
EntityKind::Spline(sp) => curve_edits::extend_spline(sp, cut, pick),
EntityKind::Ray(rl) => {
// A ray's one end is its base: EXTEND moves it back to the nearest edge (#1236).
let (base, dir) = (rl.base.xy(), rl.dir.xy().normalized());
let back = Segment::Line(Line::new(base, base - dir * 1e8));
let np = cut
.iter()
.flat_map(|c| intersect_ext(&back, c, false))
.filter(|x| (*x - base).dot(dir) < -1e-9)
.min_by(|x, y| x.dist(base).total_cmp(&y.dist(base)))
.ok_or_else(|| other("Object does not intersect an edge."))?;
Ok(EntityKind::Ray(cadcraft_doc::RayLine { base: v3(np), dir: rl.dir }))
}
_ => Err(other("Cannot extend that object.")),
}
}
+287
View File
@@ -0,0 +1,287 @@
//! The user's plot style folder: plot style tables kept as files on the computer, which every
//! drawing can use (STYLESMANAGER `where: "folder"`, `docs/plot-styles.md`).
//!
//! Each table is one file in our own format ([`cadcraft_doc::PlotStyleTable::to_file_text`]),
//! named after the table plus `.json`: `studio.ctb.json` holds `studio.ctb`. Native builds use
//! the `plotstyles` folder of the CADCraft settings directory ([`crate::settings_dir::current`]);
//! the web keeps the tables for the session. A host can install another store with
//! [`set_plot_style_store`] (first call wins).
//!
//! The tables read are handed to `cadcraft_doc` ([`cadcraft_doc::set_plot_style_folder`]), so
//! layouts, plots and the screen find them by name like the drawing's own tables.
use std::sync::{Mutex, OnceLock};
use cadcraft_doc::PlotStyleTable;
/// Ending of a table file.
pub const FILE_EXT: &str = ".json";
/// Most table files read from the folder.
pub const MAX_FILES: usize = 1000;
/// Where table files live. Names are file names ending in [`FILE_EXT`]; the engine never passes paths.
#[derive(Clone, Copy)]
pub struct PlotStyleStore {
/// The folder as the user would look for it, if it is a place on disk.
pub location: fn() -> Option<String>,
/// File names in the folder.
pub list: fn() -> std::result::Result<Vec<String>, String>,
pub read: fn(&str) -> std::result::Result<String, String>,
pub write: fn(&str, &str) -> std::result::Result<(), String>,
pub delete: fn(&str) -> std::result::Result<(), String>,
}
static STORE: OnceLock<PlotStyleStore> = OnceLock::new();
static MEMORY: Mutex<Vec<(String, String)>> = Mutex::new(Vec::new());
/// Files skipped by the last read, with the reason.
static WARNINGS: Mutex<Vec<String>> = Mutex::new(Vec::new());
/// Which file holds each table the last read found: (table name, file name). A file need not be
/// named after its table (`studio.json` holds `studio.ctb`), and edits go back to that file.
static SOURCES: Mutex<Vec<(String, String)>> = Mutex::new(Vec::new());
static READ_ONCE: OnceLock<()> = OnceLock::new();
/// Held through a whole read, so a read that started before a change can't hand `cadcraft_doc`
/// its older list after the read that follows the change.
static READING: Mutex<()> = Mutex::new(());
/// Install the host's plot style folder (first call wins).
pub fn set_plot_style_store(s: PlotStyleStore) {
let _ = STORE.set(s);
}
/// Whether `name` can be a table file's name: no path separators, no leading dot, no characters
/// a file system refuses, at most 200 characters (the file name adds its ending).
pub fn valid_table_name(name: &str) -> bool {
let n = name.trim();
!n.is_empty()
&& n == name
&& n.chars().count() <= 200
&& !n.starts_with('.')
&& !n.ends_with('.')
&& !n.chars().any(|c| c.is_control() || matches!(c, '/' | '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*'))
}
/// The file that holds table `name`.
pub fn file_name(name: &str) -> String {
format!("{name}{FILE_EXT}")
}
impl PlotStyleStore {
/// A folder kept in memory for the life of the process.
pub fn memory() -> PlotStyleStore {
fn lock() -> std::result::Result<std::sync::MutexGuard<'static, Vec<(String, String)>>, String> {
MEMORY.lock().map_err(|_| "the plot style folder is unavailable".to_string())
}
PlotStyleStore {
location: || None,
list: || Ok(lock()?.iter().map(|(n, _)| n.clone()).collect()),
read: |n| lock()?.iter().find(|(f, _)| f == n).map(|(_, t)| t.clone()).ok_or_else(|| format!("{n}: no such file")),
write: |n, t| {
let mut m = lock()?;
m.retain(|(f, _)| f != n);
m.push((n.to_string(), t.to_string()));
Ok(())
},
delete: |n| {
let mut m = lock()?;
let before = m.len();
m.retain(|(f, _)| f != n);
if m.len() == before { Err(format!("{n}: no such file")) } else { Ok(()) }
},
}
}
/// The `plotstyles` folder of the CADCraft settings directory.
#[cfg(not(target_arch = "wasm32"))]
pub fn settings_folder() -> PlotStyleStore {
fn dir() -> std::result::Result<std::path::PathBuf, String> {
crate::settings_dir::current()
.map(|r| r.join("plotstyles"))
.ok_or_else(|| "there is no settings folder for plot style tables".to_string())
}
fn file(n: &str) -> std::result::Result<std::path::PathBuf, String> {
let ok = n.strip_suffix(FILE_EXT).is_some_and(valid_table_name);
if !ok {
return Err(format!("`{n}` is not a plot style table file name"));
}
Ok(dir()?.join(n))
}
PlotStyleStore {
location: || dir().ok().map(|d| d.display().to_string()),
list: || {
let d = dir()?;
crate::file_access::check_read(&d)?;
let rd = match std::fs::read_dir(d) {
Ok(rd) => rd,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(e.to_string()),
};
// All of them: `reload` keeps the first [`MAX_FILES`] in name order and says so.
Ok(rd.filter_map(|e| e.ok()?.file_name().into_string().ok()).filter(|n| n.ends_with(FILE_EXT) && !n.starts_with('.')).collect())
},
read: |n| {
let p = file(n)?;
crate::file_access::check_read(&p)?;
let bytes = crate::capped_read::read_capped(&p, cadcraft_doc::MAX_TABLE_FILE).map_err(|e| format!("{n}: {e}"))?;
String::from_utf8(bytes).map_err(|e| format!("{n}: {e}"))
},
write: |n, t| {
let p = file(n)?;
crate::file_access::check_write(&p)?;
std::fs::create_dir_all(dir()?).map_err(|e| e.to_string())?;
crate::atomic_write::write_atomic(&p, t.as_bytes()).map_err(|e| format!("{n}: {e}"))
},
delete: |n| {
let p = file(n)?;
crate::file_access::check_write(&p)?;
std::fs::remove_file(p).map_err(|e| format!("{n}: {e}"))
},
}
}
}
fn store() -> PlotStyleStore {
*STORE.get_or_init(|| {
#[cfg(not(target_arch = "wasm32"))]
{
PlotStyleStore::settings_folder()
}
#[cfg(target_arch = "wasm32")]
{
PlotStyleStore::memory()
}
})
}
/// The folder as the user would look for it (`None` on the web or without a settings folder).
pub fn location() -> Option<String> {
(store().location)()
}
/// Files the last read skipped, and why.
pub fn warnings() -> Vec<String> {
WARNINGS.lock().map(|w| w.clone()).unwrap_or_default()
}
/// The table a file holds: named after the file (so renaming the file renames the table), with
/// the `.ctb`/`.stb` ending its kind asks for.
fn table_from_file(file: &str, text: &str) -> std::result::Result<PlotStyleTable, String> {
let mut t = PlotStyleTable::from_file_text(text)?;
let stem = file.strip_suffix(FILE_EXT).unwrap_or(file);
let ext = if t.is_color_dependent() { ".ctb" } else { ".stb" };
let lower = stem.to_ascii_lowercase();
t.name = if lower.ends_with(ext) {
stem.to_string()
} else if lower.ends_with(".ctb") || lower.ends_with(".stb") {
return Err(format!("the file name ends in {} but the table is {}", &stem[stem.len() - 4..], kind_words(&t)));
} else {
format!("{stem}{ext}")
};
Ok(t)
}
fn kind_words(t: &PlotStyleTable) -> &'static str {
if t.is_color_dependent() { "colour-dependent (.ctb)" } else { "named (.stb)" }
}
/// Read the folder again and hand its tables to `cadcraft_doc`. Unreadable files are skipped and
/// listed in [`warnings`]; a folder that can't be listed counts as empty.
pub fn reload() -> Vec<PlotStyleTable> {
let _reading = READING.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let st = store();
let mut warn = Vec::new();
let mut tables: Vec<PlotStyleTable> = Vec::new();
let mut sources = Vec::new();
match (st.list)() {
Ok(mut files) => {
files.sort();
if files.len() > MAX_FILES {
warn.push(format!("only the first {MAX_FILES} files by name are read; {} more were left out", files.len() - MAX_FILES));
}
for f in files.iter().take(MAX_FILES) {
match (st.read)(f).and_then(|text| table_from_file(f, &text)) {
Ok(t) if tables.iter().any(|x| x.name.eq_ignore_ascii_case(&t.name)) => {
warn.push(format!("{f}: another file already holds `{}`", t.name));
}
Ok(t) => {
sources.push((t.name.clone(), f.clone()));
tables.push(t);
}
Err(e) => warn.push(format!("{f}: {e}")),
}
}
}
Err(e) => warn.push(e),
}
tables.sort_by_key(|t| t.name.to_lowercase());
if let Ok(mut w) = WARNINGS.lock() {
*w = warn;
}
if let Ok(mut x) = SOURCES.lock() {
*x = sources;
}
cadcraft_doc::set_plot_style_folder(tables.clone());
let _ = READ_ONCE.set(());
tables
}
/// Read the folder the first time a session starts; later calls do nothing.
pub fn read_once() {
if READ_ONCE.get().is_none() {
reload();
}
}
/// The file that holds table `name`: the one the last read found it in, else one named after it
/// in any case.
fn held_by(st: &PlotStyleStore, name: &str) -> Option<String> {
let known = SOURCES.lock().ok().and_then(|x| x.iter().find(|(t, _)| t.eq_ignore_ascii_case(name)).map(|(_, f)| f.clone()));
known.or_else(|| {
let file = file_name(name);
(st.list)().unwrap_or_default().into_iter().find(|f| f.eq_ignore_ascii_case(&file))
})
}
/// Write `t` to the folder and read it again. The file that held a table of the same name (under
/// another file name, or another case of it) is replaced, not doubled.
pub fn write(t: &PlotStyleTable) -> std::result::Result<(), String> {
if !valid_table_name(&t.name) {
return Err(format!("`{}` can't be a file name in the plot style folder (no / \\ : < > \" | ? * or leading dot)", t.name));
}
let st = store();
let file = file_name(&t.name);
let text = t.to_file_text();
let old = held_by(&st, &t.name).filter(|f| *f != file);
(st.write)(&file, &text)?;
let result = match old {
None => Ok(()),
Some(old) => {
let files = (st.list)().unwrap_or_default();
if files.contains(&old) && files.contains(&file) {
// Two files: the old one would still win the next read.
(st.delete)(&old).map_err(|e| format!("{file} was written, but {old} still holds the old `{}`: {e}", t.name))
} else {
// One file under two spellings (a disk that ignores case): the write went to the
// old file. Remove it and write again, so the file takes the new spelling; if
// that fails, put the table back under the old one.
(st.delete)(&old).and_then(|()| match (st.write)(&file, &text) {
Ok(()) => Ok(()),
Err(e) => {
let _ = (st.write)(&old, &text);
Err(e)
}
})
}
}
};
reload();
result
}
/// Remove table `name` from the folder and read it again.
pub fn delete(name: &str) -> std::result::Result<(), String> {
let st = store();
let found = held_by(&st, name.trim()).ok_or_else(|| format!("the plot style folder has no table `{name}`"))?;
let result = (st.delete)(&found);
reload();
result
}
+4 -1
View File
@@ -170,7 +170,10 @@ fn copy_props(src: &Entity, dst: &mut Entity, m: &MatchProps) {
b.overrides.clone_from(&a.overrides);
b.block = None;
}
(EntityKind::Leader(a), EntityKind::Leader(b)) if m.dimension => b.style.clone_from(&a.style),
(EntityKind::Leader(a), EntityKind::Leader(b)) if m.dimension => {
b.style.clone_from(&a.style);
b.overrides.clone_from(&a.overrides);
}
(EntityKind::Text(a), EntityKind::Text(b)) if m.text => {
b.style.clone_from(&a.style);
b.height = a.height;
+57 -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>,
@@ -344,6 +345,20 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
),
));
}
// On a leader that holds for the DSTYLE list of its `ACAD` run (its overrides); the
// rest of the run is kept raw and may be set.
if let Some((app, _)) =
changes.iter().find(|(app, groups)| cadcraft_doc::is_model_xdata(app, groups.as_deref().unwrap_or_default(), &e.kind))
{
return Err(bad(
"properties.set",
format!(
"{}: the DSTYLE list in xdata application {app} of a {} holds its dimension-style overrides, written from its own properties, and can't be set as raw data",
h.hex(),
e.kind.dxf_name()
),
));
}
let mut after = e.common.xdata.clone();
super::xdata::apply(&mut after, changes);
if after.len() > cadcraft_doc::MAX_XDATA_GROUPS {
@@ -351,8 +366,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 +380,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 +822,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");
}
@@ -818,3 +835,41 @@ fn hatch(ha: &mut Hatch, c: &Call<'_>, used: &mut Used<'_>) {
used.insert("angle");
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The hatch of a drawing, by handle.
fn hatch_of(s: &Session, h: Handle) -> Hatch {
match &s.doc().unwrap().entity(h).unwrap().kind {
EntityKind::Hatch(ha) => ha.clone(),
other => panic!("{h:?} is a {}", other.type_name()),
}
}
#[test]
fn setting_the_same_pattern_keeps_the_lines_the_hatch_carries() {
// The loaded patterns are session-wide: HATCH.PATTERNS can clear them, and a drawing
// reopened without its .pat file leaves the hatch's own families as the only copy.
// Setting the name the hatch already carries must keep them (#1232).
let mut s = Session::new();
let kind = EntityKind::Hatch(
serde_json::from_value(json!({
"pattern": "MYGRID",
"solid": false,
"loops": [],
"patternLines": [{"angle": 0.0, "origin": [0.0, 0.0], "delta": [0.0, 0.5], "dashes": []}],
}))
.unwrap(),
);
let h = s.add_entity(kind).unwrap();
s.execute("properties.set", &json!({ "handles": [h.hex()], "pattern": "mygrid" })).unwrap();
let ha = hatch_of(&s, h);
assert_eq!(ha.pattern, "MYGRID");
assert_eq!(ha.pattern_lines.len(), 1, "the definition the hatch carries was dropped");
// A library pattern is drawn from the library: it has no lines of its own.
s.execute("properties.set", &json!({ "handles": [h.hex()], "pattern": "ANSI31" })).unwrap();
assert!(hatch_of(&s, h).pattern_lines.is_empty());
}
}
+15 -17
View File
@@ -397,7 +397,7 @@ impl TrimM {
let e = d.entity(h)?;
// Half a pixel: finer than the eye can tell apart, coarse enough to stay quick.
let tol = (s.pixel_size() / 2.0).max(1e-9);
let extending = self.extend ^ s.shift_down;
let extending = self.extend ^ (s.shift_down && s.person_input());
let part = if extending {
let grown = Entity { kind: extended(s, h, cursor, cut).ok()?, ..(**e).clone() };
uncovered(d, &grown, std::slice::from_ref(&e.kind), tol)
@@ -415,7 +415,7 @@ impl TrimM {
Edges { only: self.edges.as_deref(), implied: !quick && implied }
}
fn select_edges(&mut self, s: &mut Session) {
let extending = self.extend ^ s.shift_down;
let extending = self.extend ^ (s.shift_down && s.person_input());
s.echo(if extending { "Select boundary edges ..." } else { "Select cutting edges ..." });
s.set_selection(Vec::new());
self.stage = Stage::Edges(Vec::new());
@@ -485,6 +485,7 @@ impl Interactive for TrimM {
if self.extend { "EXTEND" } else { "TRIM" }
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
let preselected = if s.settings.pickfirst { s.selection() } else { Vec::new() };
s.set_selection(Vec::new());
let quick = quick_mode(s);
let proj = match proj_mode(s) {
@@ -497,7 +498,9 @@ impl Interactive for TrimM {
if edge_mode(s) { "Extend" } else { "None" },
if quick { "Quick" } else { "Standard" }
));
if !quick {
if !preselected.is_empty() {
self.edges = Some(preselected);
} else if !quick {
self.select_edges(s);
}
Ok(Step::Continue)
@@ -505,20 +508,15 @@ impl Interactive for TrimM {
fn prompt(&self, s: &Session) -> Prompt {
match &self.stage {
Stage::Pick => {
let extending = self.extend ^ s.shift_down;
let shift = s.shift_down && s.person_input();
let extending = self.extend ^ shift;
let (msg, first) = if extending {
let msg = if s.shift_down {
"Select object to extend or release Shift to trim"
} else {
"Select object to extend or shift-select to trim"
};
let msg =
if shift { "Select object to extend or release Shift to trim" } else { "Select object to extend or shift-select to trim" };
(msg, "Boundary edges")
} else {
let msg = if s.shift_down {
"Select object to trim or release Shift to extend"
} else {
"Select object to trim or shift-select to extend"
};
let msg =
if shift { "Select object to trim or release Shift to extend" } else { "Select object to trim or shift-select to extend" };
(msg, "cuTting edges")
};
let mut kw = vec![first, "Fence", "Crossing", "mOde", "Project"];
@@ -541,7 +539,7 @@ impl Interactive for TrimM {
Stage::Crossing(None) => Prompt::new("Specify first corner", Accept::POINT),
Stage::Crossing(Some(_)) => Prompt::new("Specify opposite corner", Accept::POINT),
Stage::Mode => {
let extending = self.extend ^ s.shift_down;
let extending = self.extend ^ (s.shift_down && s.person_input());
let msg = if extending { "Enter an extend mode option" } else { "Enter a trim mode option" };
Prompt::new(msg, KW).kw(&["Quick", "Standard"]).default(if quick_mode(s) { "Quick" } else { "Standard" })
}
@@ -565,7 +563,7 @@ impl Interactive for TrimM {
self.cut.take();
let quick = quick_mode(s);
let implied = edge_mode(s);
let extending = self.extend ^ s.shift_down;
let extending = self.extend ^ (s.shift_down && s.person_input());
match self.stage.clone() {
Stage::Mode | Stage::Project | Stage::Edge => self.option(s, i),
Stage::Edges(mut picked) => {
@@ -734,7 +732,7 @@ impl Interactive for TrimM {
return None;
}
let px = (s.pixel_size() / 2.0).max(1e-9);
let extending = self.extend ^ s.shift_down;
let extending = self.extend ^ (s.shift_down && s.person_input());
Some(picks_preview(s, &work, extending, self.edges(quick, implied), quick, tol, px))
}
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
@@ -93,6 +93,8 @@ pub const NO_FILES: &[&str] = &[
"close",
"closeall",
"document.switch",
"document.next",
"document.prev",
"document.bytes",
"u",
"undo",
@@ -241,6 +243,7 @@ pub const NO_FILES: &[&str] = &[
"gradient",
"boundary",
"region",
"hatch.capture",
"hatchedit",
"hatchgenerateboundary",
"hatchpick",
+19 -5
View File
@@ -46,7 +46,7 @@ pub mod units;
use std::sync::Arc;
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Space};
use cadcraft_geom::{Bounds2, Vec2};
use cadcraft_geom::{Bounds2, Vec2, Vec3};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -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};
@@ -138,6 +138,12 @@ pub struct Session {
pub(crate) last_paste_table: Option<(String, Option<f64>)>,
/// LASTPOINT.
pub last_point: Vec2,
/// LASTPOINT's Z, as `(last_point, z)`: it holds only while `last_point` is still that point
/// (whatever sets `last_point` without a Z puts it back on z = 0). See [`Session::last_point3`].
last_point_z: (Vec2, f64),
/// The Z of the point being entered: the third number of a typed point
/// ([`prompt::parse_point3_with`]), 0 for a picked one. See [`Session::point_z`].
point_z: f64,
/// AREA and PERIMETER: the last area AREA or MEASUREGEOM measured (in their Add and Subtract
/// modes the running total) and that area's perimeter. Not saved, as in AutoCAD.
pub area: f64,
@@ -164,7 +170,8 @@ pub struct Session {
/// this instead of receiving modifiers through `Input`, which stays free of UI state.
pub ctrl_down: bool,
/// Whether Shift is held right now (from the UI, overwritten every frame). TRIM/EXTEND read
/// this to temporarily toggle the active mode, as in AutoCAD.
/// this to temporarily toggle the active mode, as in AutoCAD; commands should gate it through
/// [`Session::person_input`], which is false for program-fed input.
pub shift_down: bool,
/// Origin of the point currently being fed by `input_snapped`; never reused by typed points.
picked_viewport: Option<snap::ViewportPoint>,
@@ -223,6 +230,8 @@ impl Session {
}
/// A session with no open drawing (the Start tab).
pub fn empty() -> Self {
// The user's plot style folder, read once per process (STYLESMANAGER reads it again).
cmd::plotstyle_folder::read_once();
Session {
docs: Vec::new(),
active: 0,
@@ -241,6 +250,8 @@ impl Session {
last_command: None,
last_paste_table: None,
last_point: Vec2::ZERO,
last_point_z: (Vec2::ZERO, 0.0),
point_z: 0.0,
area: 0.0,
perimeter: 0.0,
distance: 0.0,
@@ -284,9 +295,12 @@ impl Session {
pub fn doc(&self) -> Result<&Drawing> {
Ok(&self.state()?.doc)
}
/// Copy-on-write access to the drawing.
/// Copy-on-write access to the drawing. The revision changes too: a drawing nothing else holds
/// is edited in place, so a cache keyed by the drawing's pointer alone would miss the edit.
pub fn doc_mut(&mut self) -> Result<&mut Drawing> {
Ok(Arc::make_mut(&mut self.state_mut()?.doc))
let st = self.state_mut()?;
st.revision += 1;
Ok(Arc::make_mut(&mut st.doc))
}
/// Settings for the active drawing, without caching drawing variables in the profile.
pub fn drafting_settings(&self) -> Settings {
+93 -8
View File
@@ -156,6 +156,8 @@ pub struct LispState {
/// pass: the lowest of its own and its callers' allowances, and of what is left to an
/// expression typed at a prompt.
pub(crate) callback_ceiling: Option<u64>,
/// The host draws frames and calls [`Session::lisp_tick`] in each ([`Session::lisp_by_frames`]).
frames: bool,
}
/// What U and REDO inside the running routine take back: the commands it ran, each as the drawing
@@ -169,6 +171,10 @@ struct RoutineSteps {
/// Where the routine's undo step starts, when U or REDO inside it went on to the drawing's
/// own steps; else where the routine started.
base: Option<(Arc<Drawing>, Vec<Handle>)>,
/// The commands the routine was started in that still run: the one an expression was typed
/// at the prompt of, and the one that command interrupted when it is transparent. What they
/// did is their own undo step, not the routine's ([`Session::lisp_host_ends`]).
hosts: u8,
}
/// What a run may use (see [`value`]'s memory notes).
@@ -216,6 +222,9 @@ struct Run {
/// An expression typed at a command's prompt ([`Session::lisp_eval_answer`]): blocking, with
/// [`ANSWER_CAP`] steps instead of [`BLOCKING_CAP`].
answer: bool,
/// An answer the frames carry on ([`Session::lisp_by_frames`]): its value goes to the prompt
/// when it ends, since the call that started it has returned.
deferred: bool,
/// Steps taken, for the caps on blocking runs and on routines run on without frames.
steps: u64,
/// The `*error*` handler is the one running.
@@ -231,9 +240,11 @@ struct Run {
const SLICE: u64 = 400_000;
/// Steps a blocking run (a programmatic call) may take before it is stopped.
const BLOCKING_CAP: u64 = 500_000_000;
/// Steps an expression typed at a command's prompt may take, the callbacks it runs included. It
/// runs blocking, since its value is the prompt's answer, so the interface draws no frame and
/// Esc doesn't reach it until it ends; a routine at `Command:` runs a slice per frame instead.
/// Steps an expression typed at a command's prompt may take, the callbacks it runs included. Its
/// value is the prompt's answer, so every input but Esc waits for it. Without frames it runs
/// blocking; with them ([`Session::lisp_by_frames`]) it runs a slice per frame, as a routine at
/// `Command:` does, so Esc stops it. A callback runs inside one step either way, so Esc doesn't
/// reach it before it ends.
const ANSWER_CAP: u64 = 20_000_000;
impl Session {
@@ -303,7 +314,9 @@ impl Session {
}
/// Evaluate an expression typed at a command's prompt, whose value is the answer: it runs to
/// the end as a programmatic call does, within [`ANSWER_CAP`] steps.
/// the end as a programmatic call does, within [`ANSWER_CAP`] steps. Where the host draws
/// frames ([`Session::lisp_by_frames`]) and the first slice doesn't end it, this returns
/// `None` and the frames carry it on; its value then answers the prompt by itself.
pub(crate) fn lisp_eval_answer(&mut self, src: &str) -> crate::Result<Option<std::result::Result<Value, String>>> {
let forms = read::read_all(src).map_err(|e| crate::EngineError::Other(format!("; error: {}", e.msg)))?;
self.lisp_start(Machine::forms(forms), false, true, Vec::new(), "LISP".into(), true)
@@ -330,7 +343,11 @@ impl Session {
let st = self.state()?;
let before = Some((st.doc.clone(), st.selection.clone()));
let uid = st.uid;
self.lisp.steps = RoutineSteps { uid, ..RoutineSteps::default() };
let hosts = u8::from(self.running.is_some()) + u8::from(self.suspended.is_some());
self.lisp.steps = RoutineSteps { uid, hosts, ..RoutineSteps::default() };
// What an earlier routine left when it ended in a later frame or at a later input, where
// no call was waiting for it, is not this one's.
self.lisp_last = None;
self.lisp.run = Some(Box::new(Run {
machine,
uid,
@@ -341,6 +358,7 @@ impl Session {
inputs: inputs.into(),
blocking,
answer,
deferred: false,
steps: 0,
handler: false,
string_bytes: 0,
@@ -349,7 +367,8 @@ impl Session {
self.lisp_drive();
if blocking {
// A blocking run that waits for a command's input (`pause`) can't get it: cancel.
if self.lisp.run.is_some() {
// An answer the frames carry on is not waiting for input.
if self.lisp.run.as_ref().is_some_and(|r| !r.deferred) {
self.lisp_abort("Function cancelled");
}
}
@@ -377,6 +396,24 @@ impl Session {
}
}
/// Say whether the host draws frames and calls [`Session::lisp_tick`] in each. Where it does,
/// an expression typed at a command's prompt runs a slice per frame, so Esc
/// ([`Session::cancel`]) stops it; elsewhere it runs to its end before the call returns.
pub fn lisp_by_frames(&mut self, on: bool) {
self.lisp.frames = on;
}
/// An input other than Esc comes after the answer the frames are working out, as it did when
/// the answer ran blocking: run the expression to its end first, within its allowance. The
/// input entry points call this themselves; a host calls it before it reads the command's
/// state ([`Session::prompting`]) to choose where an input goes, so the choice is the one it
/// would make with the answer in.
pub fn lisp_settle_answer(&mut self) {
if self.lisp.run.as_ref().is_some_and(|r| r.deferred && matches!(r.waiting, Some(Need::Yield))) {
self.lisp_run_until_input();
}
}
/// Whether the routine needs ticks ([`Session::lisp_tick`]) to go on.
pub fn lisp_busy(&self) -> bool {
self.lisp.run.as_ref().is_some_and(|r| matches!(r.waiting, Some(Need::Yield)))
@@ -486,10 +523,14 @@ impl Session {
return;
}
Outcome::Wait(Need::Yield) => {
if run.blocking {
// An answer gives the interface a frame where there is one, so Esc reaches
// it. A script's line is answered before its next one, so it runs on.
let by_frames = run.answer && self.lisp.frames && !self.in_script;
if run.blocking && !by_frames {
self.lisp.run = Some(run);
continue;
}
run.deferred |= by_frames;
run.waiting = Some(Need::Yield);
self.lisp.run = Some(run);
return;
@@ -510,7 +551,8 @@ impl Session {
return;
}
Outcome::Wait(Need::Get(req)) => {
if let Some(v) = run.inputs.pop_front() {
let (req, given) = self.lisp_supplied(&mut run.inputs, req);
if let Some(v) = given {
run.machine.resume(v);
self.lisp.run = Some(run);
continue;
@@ -528,6 +570,25 @@ impl Session {
}
}
/// The value a `get…` call takes from the inputs given up front, `None` when they ran out, and
/// the request as it then stands. `getangle` and `getorient` read each input as the prompt
/// would ([`input::GetRequest::supplied`]): one the prompt refuses is echoed with the reason
/// and the next one is taken, and the first of two points makes the request ask for the
/// second. The other calls take the input as their value.
fn lisp_supplied(&mut self, inputs: &mut std::collections::VecDeque<Value>, mut req: input::GetRequest) -> (input::GetRequest, Option<Value>) {
if !req.reads_supplied() {
return (req, inputs.pop_front());
}
while let Some(v) = inputs.pop_front() {
match req.supplied(self, &v) {
input::Answer::Value(v) => return (req, Some(v)),
input::Answer::Again(msg) => self.echo(msg),
input::Answer::Second(p) => req = input::with_first(&req, p),
}
}
(req, None)
}
/// Move printed text to the command history: complete lines, and with `all` the rest too.
fn lisp_flush(&mut self, env: &mut Env, all: bool) {
// One pass over the buffer, dropping the printed lines once at the end: draining each line
@@ -556,6 +617,7 @@ impl Session {
/// The routine finished: print its value (command-line expressions), record its undo step.
fn lisp_end(&mut self, result: std::result::Result<Value, String>) {
let Some(run) = self.lisp.run.take() else { return };
let (deferred, handler) = (run.deferred, run.handler);
self.lisp.active = false;
let steps = std::mem::take(&mut self.lisp.steps);
let mut env = self.lisp.envs.remove(&run.uid).unwrap_or_default();
@@ -575,6 +637,16 @@ impl Session {
st.revision += 1;
}
self.lisp_last = Some(result);
// The call that started an answer the frames carried on has returned: nothing reads how
// it ended, and its value answers the prompt here. A failed answer's `*error*` handler
// returns no answer.
if deferred
&& let Some(Ok(v)) = self.lisp_last.take()
&& !handler
&& let Err(e) = self.lisp_answer(v)
{
self.echo(e.to_string());
}
}
/// A LISP error: run `*error*` when the routine defined one, else print it.
@@ -719,6 +791,19 @@ impl Session {
self.lisp.active
}
/// A command ends, `nested` when it ran inside another. Whether the running routine was
/// started in it (an expression typed at its prompt, or at the prompt of a transparent command
/// inside it) rather than having started it: such a command began before the routine, so its
/// undo step is its own.
pub(crate) fn lisp_host_ends(&mut self, nested: bool) -> bool {
let depth = 1 + u8::from(nested);
if !self.lisp.active || depth > self.lisp.steps.hosts {
return false;
}
self.lisp.steps.hosts = depth - 1;
true
}
/// A command the running routine ran changed the drawing (`snap` holds it as it was): U inside
/// the routine takes it back, as AutoCAD's does, while the routine stays one undo step. UNDO
/// Control One keeps only the last, None none.
+1
View File
@@ -253,6 +253,7 @@ static BUILTINS: &[Builtin] = &[
ctx!("ENTUPD", drawing::entupd),
ctx!("HANDENT", drawing::handent),
ctx!("REGAPP", drawing::regapp),
ctx!("TEXTBOX", drawing::textbox),
ctx!("SSGET", drawing::ssget),
ctx!("SSADD", drawing::ssadd),
ctx!("SSDEL", drawing::ssdel),
+169 -4
View File
@@ -836,6 +836,73 @@ pub fn regapp(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
Ok(Flow::Value(Value::str(name.trim())))
}
/// `(textbox elist)`: the smallest box around a TEXT that `elist` describes (an `entget` list, or
/// a partial one with at least the string, group 1), as its lower-left and upper-right corners
/// relative to the insertion point, the text unrotated and left-justified. Groups the list
/// leaves out take the current text style (TEXTSTYLE) and that style's height (TEXTSIZE when
/// the style's is 0), width factor and obliquing. The text is shaped as it is drawn, so the box
/// is that of the drawn glyphs (control codes such as `%%u` as drawn): its first corner is the
/// insertion point unless letters reach below the baseline or lean left of it. A string that
/// draws nothing (spaces) gives the line's advance by the text height. nil for a list that is
/// not a TEXT.
pub fn textbox(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 1, 1)?;
let list = &a[0];
let nil = || Ok(Flow::Value(Value::Nil));
if !matches!(list, Value::Cons(_)) {
return nil();
}
let group = |code: i32| list.iter().find(|p| matches!(p.car(), Value::Int(c) if c == code)).map(|p| p.cdr());
if group(1).is_none() || group(0).is_some_and(|k| !matches!(&k, Value::Str(s) if s.eq_ignore_ascii_case("TEXT"))) {
return nil();
}
let Ok(d) = ctx.s.doc() else { return nil() };
let style = match group(7) {
Some(Value::Str(s)) => s.to_string(),
_ => d.header.str("TEXTSTYLE", "Standard"),
};
let ts = d.text_style(&style).cloned().unwrap_or_default();
let pair = |c: i32, v: Value| Value::cons(Value::Int(c), v);
let mut items = vec![pair(0, Value::str("TEXT"))];
if group(7).is_none() {
items.push(pair(7, Value::str(&style)));
}
if group(40).is_none() {
let h = if ts.height.is_finite() && ts.height > 0.0 { ts.height } else { d.header.f64("TEXTSIZE", 0.2) };
items.push(pair(40, Value::Real(h)));
}
if group(41).is_none() {
items.push(pair(41, Value::Real(ts.width_factor)));
}
if group(51).is_none() {
items.push(pair(51, Value::Real(ts.oblique)));
}
items.extend(list.iter().filter(|p| !matches!(p.car(), Value::Int(0))));
let Ok((_, _, cadcraft_doc::EntityKind::Text(t), _)) = entity_from_list(ctx, &Value::list(items)) else { return nil() };
let t = cadcraft_doc::Text {
insert: Default::default(),
align_pt: None,
rotation: 0.0,
halign: cadcraft_doc::HAlign::Left,
valign: cadcraft_doc::VAlign::Baseline,
backwards: false,
upside_down: false,
..t
};
let Ok(d) = ctx.s.doc() else { return nil() };
// The line's box runs from the font's descent to the text height over the advance; the
// drawn points give the smallest box. With nothing drawn, the advance from the baseline up.
let (sh, line) = cadcraft_render::place_text_entity(d, &t, &t.value);
let mut b = cadcraft_geom::Bounds2::from_points(sh.strokes.iter().flatten().chain(sh.glyphs.iter().flatten().flatten()).copied());
if b.is_empty() {
b = cadcraft_geom::Bounds2::from_points([cadcraft_geom::Vec2::new(0.0, 0.0), line.max]);
}
if b.is_empty() || ![b.min.x, b.min.y, b.max.x, b.max.y].iter().all(|v| v.is_finite()) {
return nil();
}
Ok(Flow::Value(Value::list([Value::point(&[b.min.x, b.min.y, 0.0]), Value::point(&[b.max.x, b.max.y, 0.0])])))
}
/// The upper-case names of every application registered in the drawing or carrying xdata on an object.
fn xdata_app_names(d: &cadcraft_doc::Drawing) -> std::collections::BTreeSet<String> {
std::iter::once(&d.model)
@@ -864,8 +931,9 @@ fn entity_from_list(ctx: &Ctx<'_>, list: &Value) -> Result<ListedEntity, LispErr
Some((mut common, k)) => {
if let Some(apps) = &xdata {
for (app, groups) in apps {
// `ACAD` on a dimension holds its overrides (DSTYLE), written from the model.
if cadcraft_doc::is_model_xdata_app(app, &k) {
// `ACAD` on a dimension holds its overrides (DSTYLE), written from the model; on
// a leader its DSTYLE list does, and the rest of the run is kept.
if cadcraft_doc::is_model_xdata(app, groups, &k) {
return Err(LispError::new(format!("bad DXF group: xdata application {app} of a {kind} is written from its own properties")));
}
cadcraft_doc::set_xdata_app(&mut common.xdata, app, Some(groups));
@@ -1024,6 +1092,12 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
{
new.attribs = was.attribs.clone();
}
// A leader's style overrides are read from its `ACAD` DSTYLE xdata with the file's handle
// tables, which a list has not: they are kept from the leader, and a list that gives a
// DSTYLE list as raw xdata was refused above (`entity_from_list`).
if let (cadcraft_doc::EntityKind::Leader(new), cadcraft_doc::EntityKind::Leader(was)) = (&mut kind, &old.kind) {
new.overrides.clone_from(&was.overrides);
}
let Ok(d) = ctx.s.doc_mut() else { return Ok(Flow::Value(Value::Nil)) };
d.ensure_layer(&common.layer);
let ok = d
@@ -1891,7 +1965,7 @@ pub fn load_source(s: &Session, name: &str) -> Option<String> {
// startup files) a relative name is read as given.
let dir = match s.lisp_support_dir() {
Some(d) if !std::path::Path::new(name).is_absolute() => d,
_ => return candidates.iter().find_map(super::builtins::read_text_file),
_ => return read_module(candidates.iter().map(std::path::PathBuf::from)),
};
// A relative name stays inside the support folder: plain folder and file names only. `..` would
// climb out of it, and on Windows a rooted name (`\tools`) or a drive-relative one (`C:tools`,
@@ -1900,7 +1974,98 @@ pub fn load_source(s: &Session, name: &str) -> Option<String> {
if !std::path::Path::new(name).components().all(|c| matches!(c, Component::Normal(_) | Component::CurDir)) {
return None;
}
candidates.iter().find_map(|c| super::builtins::read_text_file(dir.join(c)))
read_module(candidates.iter().map(|c| dir.join(c)))
}
/// Read the first candidate that exists, trying each exact name first. A module written on Windows
/// names its include in one case and ships the file in another: Windows resolved that for free and
/// a case-sensitive file system does not, so when no candidate matched, retry with the case of the
/// name ignored. The folders in a candidate are used exactly as given.
fn read_module(paths: impl Iterator<Item = std::path::PathBuf>) -> Option<String> {
let paths: Vec<std::path::PathBuf> = paths.collect();
if let Some(text) = paths.iter().find_map(super::builtins::read_text_file) {
return Some(text);
}
paths.iter().find_map(|path| resolve_name_ignoring_case(path).and_then(|found| super::builtins::read_text_file(&found)))
}
/// Find `path` when only the case of its last component differs from what is on disk.
///
/// Where a folder holds more than one spelling that matches, the smallest name wins, so the answer
/// does not depend on directory order.
#[cfg(not(target_arch = "wasm32"))]
fn resolve_name_ignoring_case(path: &std::path::Path) -> Option<std::path::PathBuf> {
let wanted = path.file_name()?.to_str()?.to_lowercase();
let dir = match path.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent,
_ => std::path::Path::new("."),
};
// Listing a folder opens it, and for a network path contacts its host: ask first.
crate::file_access::check_read(dir).ok()?;
let mut best: Option<std::path::PathBuf> = None;
for entry in std::fs::read_dir(dir).ok()?.flatten() {
let name = entry.file_name();
let Some(candidate) = name.to_str() else { continue };
if candidate.to_lowercase() != wanted {
continue;
}
let full = dir.join(candidate);
// A link counts as the file it leads to. Following it opens its target, so ask first.
if crate::file_access::check_read(&full).is_err() || !std::fs::metadata(&full).is_ok_and(|meta| meta.is_file()) {
continue;
}
if best.as_ref().is_none_or(|prev| full < *prev) {
best = Some(full);
}
}
best
}
/// The web has no file system for path lookup.
#[cfg(target_arch = "wasm32")]
fn resolve_name_ignoring_case(_path: &std::path::Path) -> Option<std::path::PathBuf> {
None
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod case_lookup_tests {
use super::resolve_name_ignoring_case;
use crate::file_access::{AutomationRoots, confine};
/// Under automation roots the case fallback lists only a folder the roots let it read, and a
/// link that leaves them is not a match.
#[test]
fn the_case_fallback_stays_inside_the_automation_roots() {
let base = std::env::temp_dir().join(format!("cadcraft-case-roots-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let (inside, outside) = (base.join("in"), base.join("outside"));
std::fs::create_dir_all(&inside).unwrap();
std::fs::create_dir_all(&outside).unwrap();
std::fs::write(inside.join("Tool.lsp"), "").unwrap();
std::fs::write(outside.join("Tool.lsp"), "").unwrap();
let roots = AutomationRoots::new(Some(&inside), None).unwrap();
let find = |path: std::path::PathBuf| confine(roots.as_ref(), || resolve_name_ignoring_case(&path));
assert!(find(inside.join("tool.lsp")).is_some(), "found inside the read root");
assert!(find(outside.join("tool.lsp")).is_none(), "nothing is found outside the roots");
#[cfg(unix)]
{
// A link's target is read from the link's own folder, so these hold even where the
// temporary folder's path is relative.
std::os::unix::fs::symlink("../outside/Tool.lsp", inside.join("Away.lsp")).unwrap();
assert!(inside.join("Away.lsp").is_file(), "the link has a target");
assert!(find(inside.join("away.lsp")).is_none(), "a link that leaves the roots");
// This link may be read, since it leads back inside: only the check on the folder
// itself keeps the fallback from listing that folder and finding it.
std::os::unix::fs::symlink("../in/Tool.lsp", outside.join("Back.lsp")).unwrap();
let back = confine(roots.as_ref(), || crate::file_access::check_read(outside.join("Back.lsp")));
assert_eq!(back, Ok(()));
assert!(find(outside.join("back.lsp")).is_none(), "a folder outside the roots is not listed");
}
// Without roots nothing is confined.
assert!(resolve_name_ignoring_case(&outside.join("tool.lsp")).is_some());
let _ = std::fs::remove_dir_all(&base);
}
}
#[cfg(test)]
+45
View File
@@ -86,6 +86,51 @@ impl GetRequest {
}
}
/// Whether an answer given up front (`lisp {code, inputs}`) is read as the prompt reads one
/// ([`GetRequest::supplied`]) instead of being the value as it is: `getangle` and `getorient`
/// return radians whatever the form of the answer.
pub fn reads_supplied(&self) -> bool {
matches!(self.kind, GetKind::Angle { .. })
}
/// What an answer given up front gives, read as the same answer at the prompt: a number as
/// that number typed (in AUNITS), a string as the text typed ([`GetRequest::typed`]), a point
/// as a point picked, nil as Enter. The point is in the UCS, as the routine sees points.
pub fn supplied(&self, s: &mut Session, v: &Value) -> Answer {
let r = match v {
Value::Nil => self.answer_value(s, Input::Enter),
Value::Int(i) => self.text(s, &i.to_string()),
Value::Real(x) => self.text(s, &x.to_string()),
Value::Str(t) => self.typed(s, t),
other => match other.as_point() {
Some(p) => self.point(s, p),
None => Err("Requires valid numeric angle or second point.".into()),
},
};
match r {
Ok(v) => Answer::Value(v),
Err(Again::Second(p)) => Answer::Second(p),
Err(Again::Msg(m)) => Answer::Again(m),
}
}
/// What text gives, read as the command line reads it typed at the prompt
/// (`Session::typed_token`): empty or blank text is Enter, a keyword is that keyword,
/// coordinates are a point (`1,1`, `@1,1`, `1<45`, `*1,1`: in the current UCS, the relative
/// forms from the last point), and anything else is text (`45`, `45d`, `0.5r`, `50g`).
fn typed(&self, s: &mut Session, t: &str) -> Result<Value, Again> {
let t = t.trim();
if t.is_empty() {
return self.answer_value(s, Input::Enter);
}
if keyword(&self.initget.keywords, t).is_none()
&& let Some(p) = s.parse_typed_point(t, s.last_point)
{
return self.answer_value(s, Input::Point(p));
}
self.text(s, t)
}
fn answer_value(&self, s: &mut Session, input: Input) -> Result<Value, Again> {
let ig = &self.initget;
let no_null = ig.bits & 1 != 0;
+130
View File
@@ -619,6 +619,91 @@ fn entmod_of_a_block_reference_keeps_its_attributes() {
assert_eq!(insert(&s).1, want);
}
/// entmod of a leader keeps its own dimension style overrides: they come from its DSTYLE xdata,
/// read with the file's handle tables, and a list rebuilds the leader without them (#3721).
#[test]
fn entmod_of_a_leader_keeps_its_style_overrides() {
let mut s = session();
let overrides = serde_json::json!({ "arrowSize": 1.5, "leaderArrowBlock": "_ArchTick" });
let overrides = overrides.as_object().cloned().unwrap();
let leader = cadcraft_doc::Leader {
vertices: vec![cadcraft_geom::Vec3::ZERO, cadcraft_geom::Vec3::new(10.0, 0.0, 0.0)],
arrow: true,
spline: false,
style: "Standard".into(),
overrides: overrides.clone(),
};
s.doc_mut().unwrap().add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), cadcraft_doc::EntityKind::Leader(leader)).unwrap();
let leader = |s: &Session| {
s.doc()
.unwrap()
.model
.iter()
.find_map(|e| match &e.kind {
cadcraft_doc::EntityKind::Leader(l) => Some((e.common.layer.clone(), l.overrides.clone())),
_ => None,
})
.unwrap()
};
ok(&mut s, "(setq d (entget (entlast))) (entmod (subst (cons 8 \"UGO\") (assoc 8 d) d))");
assert_eq!(leader(&s), ("UGO".to_string(), overrides));
}
/// A session with one leader that has `overrides`.
fn session_with_leader(overrides: serde_json::Value) -> Session {
let mut s = session();
let leader = cadcraft_doc::Leader {
vertices: vec![cadcraft_geom::Vec3::ZERO, cadcraft_geom::Vec3::new(10.0, 0.0, 0.0)],
arrow: true,
spline: false,
style: "Standard".into(),
overrides: overrides.as_object().cloned().unwrap(),
};
s.doc_mut().unwrap().add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), cadcraft_doc::EntityKind::Leader(leader)).unwrap();
s
}
/// The overrides of the one leader of a drawing.
fn leader_overrides(d: &cadcraft_doc::Drawing) -> serde_json::Map<String, serde_json::Value> {
d.model
.iter()
.find_map(|e| match &e.kind {
cadcraft_doc::EntityKind::Leader(l) => Some(l.overrides.clone()),
_ => None,
})
.unwrap()
}
/// A leader's DSTYLE list is its style overrides, written from the model: `ACAD` xdata that
/// holds one is refused by entmod and entmake (nil, nothing changes), with or without overrides
/// on the leader. Other `ACAD` data on a leader is taken and survives a save beside them.
#[test]
fn a_dstyle_list_in_a_leaders_acad_xdata_is_refused_and_other_acad_data_kept() {
const DSTYLE: &str = "(-3 (\"ACAD\" (1000 . \"DSTYLE\") (1002 . \"{\") (1070 . 41) (1040 . 9.0) (1002 . \"}\")))";
for overrides in [serde_json::json!({}), serde_json::json!({ "arrowSize": 1.5 })] {
let mut s = session_with_leader(overrides.clone());
let want = overrides.as_object().cloned().unwrap();
let count = s.doc().unwrap().model.len();
assert_eq!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '({DSTYLE})))")), "nil", "{overrides}");
assert_eq!(ok(&mut s, "(assoc -3 (entget (entlast) '(\"*\")))"), "nil", "{overrides}");
assert_eq!(leader_overrides(s.doc().unwrap()), want);
// The same list after other groups of the run, and a new leader made with it.
let later = DSTYLE.replace("(\"ACAD\" ", "(\"ACAD\" (1000 . \"MINE\") ");
assert_eq!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '({later})))")), "nil", "{overrides}");
assert_eq!(ok(&mut s, &format!("(entmake (append (entget (entlast)) '({DSTYLE})))")), "nil", "{overrides}");
assert_eq!(s.doc().unwrap().model.len(), count, "nothing was made");
// Other ACAD data, also a string that only reads DSTYLE, is foreign data and stays.
let other = "(\"ACAD\" (1000 . \"DSTYLE\") (1000 . \"MINE\") (1070 . 42))";
assert!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '((-3 {other}))))")).contains("LEADER"));
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"ACAD\"))))"), format!("({other})"));
assert_eq!(leader_overrides(s.doc().unwrap()), want);
let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap();
assert_eq!(leader_overrides(&back), want, "the overrides after a save and reopen");
s.open_drawing(back, "back", None);
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"ACAD\"))))"), format!("({other})"), "{overrides}");
}
}
/// An edit that leaves every handle where it was (a layer change) keeps entlast's cached order;
/// one that adds an entity rebuilds it.
#[test]
@@ -1376,6 +1461,51 @@ fn a_leading_newline_ends_the_command_line_instead_of_adding_an_empty_one() {
assert_eq!(&s.log[from..], ["Hello", "", "After a blank"]);
}
/// A module written on Windows names its include in one case and ships the file in another.
/// Windows resolved that for free; a case-sensitive file system does not.
#[test]
fn load_finds_a_support_file_named_in_another_case() {
let dir = std::env::temp_dir().join(format!("cadcraft-lisp-case-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("UpperCase.lsp"), "(setq case-test-loaded 1)").unwrap();
let mut s = session();
s.set_lisp_support_dir(Some(dir.clone()));
let _ = ok(&mut s, "(load \"uppercase\")");
assert_eq!(to_text(&s.lisp_var("CASE-TEST-LOADED"), true), "1", "(load \"uppercase\") reads UpperCase.lsp");
// An exact name still wins when the folder also holds a spelling that differs only by case.
// Where the folder ignores case (Windows and macOS by default) the two names are one file, so
// there is nothing to choose between.
std::fs::write(dir.join("case-probe"), "").unwrap();
if !dir.join("CASE-PROBE").exists() {
std::fs::write(dir.join("variant.lsp"), "(setq picked 1)").unwrap();
std::fs::write(dir.join("Variant.lsp"), "(setq picked 2)").unwrap();
let _ = ok(&mut s, "(load \"variant\")");
assert_eq!(to_text(&s.lisp_var("PICKED"), true), "1", "the exact name wins");
}
let _ = std::fs::remove_dir_all(&dir);
}
/// A support file may be a link: it counts as the file it leads to.
#[cfg(unix)]
#[test]
fn load_finds_a_linked_support_file_named_in_another_case() {
let dir = std::env::temp_dir().join(format!("cadcraft-lisp-case-link-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("kept")).unwrap();
std::fs::write(dir.join("kept/real.lsp"), "(setq linked-loaded 1)").unwrap();
// The target is read from the link's own folder, so it holds even where `dir` is relative.
std::os::unix::fs::symlink("kept/real.lsp", dir.join("Linked.lsp")).unwrap();
let mut s = session();
s.set_lisp_support_dir(Some(dir.clone()));
let _ = ok(&mut s, "(load \"linked\")");
assert_eq!(to_text(&s.lisp_var("LINKED-LOADED"), true), "1", "(load \"linked\") reads through Linked.lsp");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn startup_files_load_from_the_support_folder() {
let dir = std::env::temp_dir().join(format!("cadcraft-lisp-startup-{}", std::process::id()));
+27 -10
View File
@@ -75,8 +75,8 @@ impl Axes {
pub enum Frame {
/// `FROM`: the base point once given, then the offset point.
From { base: Option<Vec2> },
/// `M2P`/`MTP`: the first point once given, then the second.
Mid { first: Option<Vec2> },
/// `M2P`/`MTP`: the first point once given (with its Z), then the second.
Mid { first: Option<Vec2>, z: f64 },
/// A point filter: the point to take `keep` from once given, then the rest.
Filter { keep: Axes, first: Option<Vec2> },
/// `<a`: the next point lies on the line through `base` in direction `dir` (a unit vector).
@@ -153,8 +153,8 @@ impl Session {
self.point_mods.iter().fold(cmd, |p, f| match *f {
Frame::From { base: None } => Prompt::new("Base point", point),
Frame::From { base: Some(b) } => Prompt::new("<Offset>", point).base(b),
Frame::Mid { first: None } => Prompt::new("First point of mid", point),
Frame::Mid { first: Some(f) } => Prompt::new("Second point of mid", point).base(f),
Frame::Mid { first: None, .. } => Prompt::new("First point of mid", point),
Frame::Mid { first: Some(f), .. } => Prompt::new("Second point of mid", point).base(f),
Frame::Filter { keep, first: None } => Prompt::new(format!("{} of", keep.name()), point).base_opt(p.base),
Frame::Filter { keep, first: Some(_) } => Prompt::new(format!("(need {})", keep.need()), point).base_opt(p.base),
Frame::TempTrack => Prompt::new("Specify temporary OTRACK point", point),
@@ -200,7 +200,7 @@ impl Session {
let b = b.to_ascii_lowercase();
match b.as_str() {
"from" | "fro" => Some(Frame::From { base: None }),
"m2p" | "mtp" => Some(Frame::Mid { first: None }),
"m2p" | "mtp" => Some(Frame::Mid { first: None, z: 0.0 }),
"tt" => Some(Frame::TempTrack),
// TK, or TRACKING from three letters (TRA, TRACK).
"tk" => Some(Frame::Track { last: None }),
@@ -300,7 +300,16 @@ impl Session {
/// A point given while modifiers are pending: complete the top frame, and when it has its
/// point, hand that to the frame (or command) below.
pub(crate) fn modifier_point(&mut self, mut p: Vec2) -> Result<()> {
pub(crate) fn modifier_point(&mut self, p: Vec2) -> Result<()> {
// The frames below may give the point another Z (a snap's, a midpoint's); the next
// point starts from the Z it comes with.
let z = self.point_z;
let result = self.modifier_point_frames(p);
self.point_z = z;
result
}
fn modifier_point_frames(&mut self, mut p: Vec2) -> Result<()> {
if !p.is_finite() {
self.echo("Invalid point.");
return Ok(());
@@ -313,8 +322,8 @@ impl Session {
self.last_point = p;
return Ok(());
}
Frame::Mid { first: None } => {
self.point_mods.push(Frame::Mid { first: Some(p) });
Frame::Mid { first: None, .. } => {
self.point_mods.push(Frame::Mid { first: Some(p), z: self.point_z });
self.last_point = p;
return Ok(());
}
@@ -336,7 +345,11 @@ impl Session {
}
// The offset point is already measured from the base (`@` reads the last point).
Frame::From { base: Some(_) } => {}
Frame::Mid { first: Some(f) } => p = (f + p) * 0.5,
Frame::Mid { first: Some(f), z } => {
p = (f + p) * 0.5;
// Midway in Z too: between two snapped levels, or typed `x,y,z` points.
self.point_z = (z + self.point_z) * 0.5;
}
Frame::Filter { keep, first: Some(f) } => p = keep.combine_in(&self.input_ucs(), f, p),
Frame::Angle { base, dir } => p = base + dir * (p - base).dot(dir),
Frame::Snap { mode: 0 } => {}
@@ -351,7 +364,11 @@ impl Session {
let hit = crate::snap::osnap(self.doc()?, &space, p, aperture, mode | hatch, base, deferred);
match hit {
Some(h) if self.point_mods.is_empty() => return self.input_snapped(h),
Some(h) => p = h.point,
Some(h) => {
// The Z of what it snapped to, as for a snapped pick (OSNAPZ-aware).
self.point_z = if h.viewport.is_none() { self.snap_z(&h) } else { 0.0 };
p = h.point;
}
None => {
self.echo(format!("No {} found for specified point.", snap_name(mode)));
return Ok(());
+64 -8
View File
@@ -1,7 +1,7 @@
//! Interactive commands: prompts, inputs and the command-line coordinate grammar.
use cadcraft_doc::{EntityKind, Handle};
use cadcraft_geom::{Mat3, Vec2};
use cadcraft_geom::{Mat3, Vec2, Vec3};
use serde::Serialize;
use crate::{Result, Session};
@@ -511,16 +511,33 @@ pub fn parse_point(text: &str, last: Vec2) -> Option<Vec2> {
}
/// `parse_point` with polar angles read per `angles` (AUNITS, ANGBASE, ANGDIR); `d<<a` and
/// `d<<<a` measure from +X counterclockwise (in degrees and in AUNITS).
/// `d<<<a` measure from +X counterclockwise (in degrees and in AUNITS). A third number is
/// accepted and dropped; [`parse_point3_with`] keeps it.
pub fn parse_point_with(text: &str, last: Vec2, angles: &crate::units::AngleSettings) -> Option<Vec2> {
parse_point_in(text, last, angles, &crate::ucs::UcsFrame::WORLD)
}
/// [`parse_point_with`] keeping Z: `x,y,z` and `#x,y,z` give that Z, `x,y` and `d<a` lie at
/// z = 0, and the relative forms add to `last`'s Z (`@dx,dy,dz`; `@dx,dy` and `@d<a` keep it,
/// as in AutoCAD).
pub fn parse_point3_with(text: &str, last: Vec3, angles: &crate::units::AngleSettings) -> Option<Vec3> {
parse_point3_in(text, last, angles, &crate::ucs::UcsFrame::WORLD)
}
/// `parse_point_with` in a UCS: coordinates are UCS coordinates (`x,y` from its origin along its
/// axes, `@dx,dy` along its axes), and polar angles are measured as `angles` says (which carries
/// the UCS rotation, [`crate::units::AngleSettings::ucs`]). A `*` prefix reads the point in
/// world coordinates instead. `last` and the result are world points.
/// world coordinates instead. `last` and the result are world points. A third number is
/// accepted and dropped; [`parse_point3_in`] keeps it.
pub fn parse_point_in(text: &str, last: Vec2, angles: &crate::units::AngleSettings, ucs: &crate::ucs::UcsFrame) -> Option<Vec2> {
parse_point3_in(text, last.to3(0.0), angles, ucs).map(Vec3::xy)
}
/// [`parse_point_in`] keeping Z, as [`parse_point3_with`] does: `x,y,z` is a UCS point (its Z
/// measured along the UCS Z axis, from its origin), `x,y` and `d<a` lie at world z = 0, and the
/// relative forms add their Z to `last`'s (`@dx,dy` and `@d<a` keep it). `last` and the result
/// are world points.
pub fn parse_point3_in(text: &str, last: Vec3, angles: &crate::units::AngleSettings, ucs: &crate::ucs::UcsFrame) -> Option<Vec3> {
let t = text.trim();
if t.is_empty() {
return None;
@@ -554,7 +571,7 @@ pub fn parse_point_in(text: &str, last: Vec2, angles: &crate::units::AngleSettin
// `d<<a` / `d<<<a`: the override prefixes keep their `<<` / `<<<`.
let ang = if a.starts_with('<') { angles.direction(&format!("<{a}"))? } else { angles.direction(a)? };
let v = Vec2::from_angle(ang) * dist;
if rel { last + v } else { frame.origin.xy() + v }
if rel { (last.xy() + v).to3(last.z) } else { (frame.origin.xy() + v).to3(0.0) }
} else {
let parts: Vec<&str> = body.split(',').collect();
if parts.len() < 2 || parts.len() > 3 {
@@ -562,11 +579,18 @@ pub fn parse_point_in(text: &str, last: Vec2, angles: &crate::units::AngleSettin
}
let x = crate::units::parse_distance(parts.first()?)?;
let y = crate::units::parse_distance(parts.get(1)?)?;
if let Some(z) = parts.get(2) {
crate::units::parse_distance(z)?;
}
let z = match parts.get(2) {
Some(z) => Some(crate::units::parse_distance(z)?),
None => None,
};
let v = Vec2::new(x, y);
if rel { last + frame.vec_to_wcs(v) } else { frame.to_wcs(v) }
// The UCS Z axis in world coordinates (straight up for the planar UCSs points are read in).
let dz = frame.z().z;
if rel {
(last.xy() + frame.vec_to_wcs(v)).to3(last.z + z.unwrap_or(0.0) * dz)
} else {
frame.to_wcs(v).to3(z.map_or(0.0, |z| frame.origin.z + z * dz))
}
};
p.is_finite().then_some(p)
}
@@ -617,6 +641,38 @@ mod tests {
assert_eq!(latin.match_keyword("Θ").as_deref(), Some("Undo"), "a Greek-layout shortcut still works");
}
#[test]
fn points_with_z() {
let last = Vec3::new(10.0, 10.0, 1.0);
let p3 = |t: &str| parse_point3_with(t, last, &crate::units::AngleSettings::default());
assert_eq!(p3("1,2"), Some(Vec3::new(1.0, 2.0, 0.0)));
assert_eq!(p3("1,2,3"), Some(Vec3::new(1.0, 2.0, 3.0)));
assert_eq!(p3("#10,20,30"), Some(Vec3::new(10.0, 20.0, 30.0)));
assert_eq!(p3("*1,2,3"), Some(Vec3::new(1.0, 2.0, 3.0)));
// Relative input adds to the last point's Z; without a third number Z stays.
assert_eq!(p3("@0,0,5"), Some(Vec3::new(10.0, 10.0, 6.0)));
assert_eq!(p3("@1,2"), Some(Vec3::new(11.0, 12.0, 1.0)));
assert_eq!(p3("@"), Some(last));
assert!(p3("@5<90").is_some_and(|p| (p - Vec3::new(10.0, 15.0, 1.0)).len() < 1e-9));
assert!(p3("5<0").is_some_and(|p| (p - Vec3::new(5.0, 0.0, 0.0)).len() < 1e-9));
// Hostile forms: rejected, no panic.
for t in ["1,2,3,4", "1,2,", "1,2,z", "1,2,inf", "1,2,NaN", ",,", "@,,1"] {
assert_eq!(p3(t), None, "{t}");
}
let far = Vec3::new(0.0, 0.0, f64::MAX);
assert_eq!(parse_point3_with("@0,0,1e308", far, &crate::units::AngleSettings::default()), None);
// The 2D form is unchanged.
assert_eq!(parse_point("3,4,5", Vec2::new(10.0, 10.0)), Some(Vec2::new(3.0, 4.0)));
// In a UCS: a typed Z is measured from its origin; `x,y` lies at z = 0; `@` adds to `last`.
let ucs = crate::ucs::UcsFrame::new(Vec3::new(5.0, 0.0, 2.0), Vec3::new(0.0, 1.0, 0.0), Vec3::new(-1.0, 0.0, 0.0)).unwrap();
let angles = crate::units::AngleSettings::default();
let u3 = |t: &str| parse_point3_in(t, Vec3::new(0.0, 0.0, 4.0), &angles, &ucs);
assert!(u3("1,0,3").is_some_and(|p| (p - Vec3::new(5.0, 1.0, 5.0)).len() < 1e-9));
assert!(u3("1,0").is_some_and(|p| (p - Vec3::new(5.0, 1.0, 0.0)).len() < 1e-9));
assert!(u3("@1,0,1").is_some_and(|p| (p - Vec3::new(0.0, 1.0, 5.0)).len() < 1e-9));
assert!(u3("*1,0,3").is_some_and(|p| (p - Vec3::new(1.0, 0.0, 3.0)).len() < 1e-9));
}
#[test]
fn keywords() {
let p = Prompt::new("Specify next point", Accept::POINT).kw(&["Undo", "Close"]);
+3 -1
View File
@@ -189,7 +189,9 @@ mod tests {
for b in cadcraft_doc::BUILTIN_PLOT_STYLE_TABLES {
assert!(e.contains(b), "{b}: {e}");
}
assert!(e.contains("and 490 more"), "{e}");
// At least the 490 of the drawing's own that are not listed (the user's plot style folder may add some).
let more = e.split(" and ").last().and_then(|t| t.split_whitespace().next()).and_then(|n| n.parse::<usize>().ok());
assert!(more.is_some_and(|n| n >= 490), "{e}");
assert!(e.len() < 1000, "{} bytes: {e}", e.len());
assert!(RenderLook::from_params(&d, &json!({"plot_style": d.plot_style_tables[7].name.clone()})).is_ok());
}
+121 -16
View File
@@ -262,9 +262,11 @@ fn in_text(d: &Drawing, e: &Entity, view: &ViewportBounds<'_>, p: Vec2) -> bool
// the text there, not the text the dimension's own geometry would place.
EntityKind::Dimension(dm) => match dm.block.as_ref().and_then(|n| d.block(n)) {
// The block draws translated by the insertion point (group 12): test there (#2634).
// A text the block does not draw, on a layer frozen for the drawing or turned off, is
// not there to pick (#3218).
Some(blk) => {
let p = p - dm.insertion_point.xy();
blk.entities.iter().filter(|be| !view.leaves_out(be)).any(|be| match &be.kind {
blk.entities.iter().filter(|be| !view.leaves_out(be) && block_object_drawn(d, e, be)).any(|be| match &be.kind {
EntityKind::MText(t) => in_box(cadcraft_render::layout_mtext_entity(d, t).strokes.into_iter().flatten(), t.rotation, p),
EntityKind::Text(_) => entity_bounds(d, be, 0).contains(p),
_ => false,
@@ -282,6 +284,18 @@ fn in_text(d: &Drawing, e: &Entity, view: &ViewportBounds<'_>, p: Vec2) -> bool
}
}
/// Whether a block's object `be` is drawn on its layer: its own visibility and its layer's, layer
/// "0" inside a block taking the layer of the reference `e` that draws it, as the renderer resolves
/// them (`crates/render/src/props.rs`). A layer frozen for the whole drawing, or turned off, draws
/// nothing there, so nothing there is picked.
fn block_object_drawn(d: &Drawing, e: &Entity, be: &Entity) -> bool {
if !be.common.visible {
return false;
}
let layer = if be.common.layer == "0" { e.common.layer.as_str() } else { be.common.layer.as_str() };
d.layer(layer).is_none_or(cadcraft_doc::Layer::visible)
}
/// Whether `p` is inside the box around `pts` turned by `angle` (the box of text set at `angle`).
fn in_box(pts: impl Iterator<Item = Vec2>, angle: f64, p: Vec2) -> bool {
let turn = |q: Vec2| q.rotate(-angle);
@@ -461,6 +475,58 @@ fn touch_box_in<'a>(d: &'a Drawing, e: &Entity, known: Option<Bounds2>, view: &m
outline_in(d, e, view, b)
}
/// The strokes and glyph outlines a top-level TEXT, ATTDEF or MTEXT draws, where the renderer
/// places them: turned with the text, at the size it draws at the current annotation scale (none
/// when that scale hides it), upright when it matches the layout's orientation. `None` for any
/// other entity, for a blank MTEXT, which is selected by its frame ([`blank_mtext_box`]), and for
/// text that draws nothing (hidden by the annotation scale, or with no finite point).
///
/// The document's box for text ([`entity_bounds`]) is an estimate from the number of characters
/// (and of lines). It differs from what the fonts draw, and on the side a justified line or an
/// attachment point leaves open it reaches past the text, so a window that held all of a text,
/// turned or not, missed it when it tested only that box (#3731). A selection that must hold the
/// text (a window, a window polygon) takes it when it holds the box, as before, or else when it
/// holds these. A selection that only has to touch the text tests the box alone.
fn drawn_text(d: &Drawing, e: &Entity) -> Option<Vec<Vec<Vec2>>> {
match &e.kind {
EntityKind::Text(_) | EntityKind::AttDef(_) => {}
EntityKind::MText(t) if !is_blank_mtext(t) => {}
_ => return None,
}
let scaled;
let e = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Plain => e,
cadcraft_doc::AnnoDraw::Hidden => return None,
cadcraft_doc::AnnoDraw::Scaled(f) => {
scaled = cadcraft_doc::anno_scaled(e, f);
&scaled
}
};
let line = |sh: cadcraft_fonts::Shaped| sh.strokes.into_iter().chain(sh.glyphs.into_iter().flatten()).collect::<Vec<_>>();
let strokes = match &e.kind {
EntityKind::Text(t) if e.common.matches_layout_orientation() => {
line(cadcraft_render::place_text_entity(d, &cadcraft_doc::Text { rotation: 0.0, ..t.clone() }, &t.value).0)
}
EntityKind::Text(t) => line(cadcraft_render::place_text_entity(d, t, &t.value).0),
EntityKind::AttDef(a) => line(cadcraft_render::place_text_entity(d, &a.text, &a.tag).0),
EntityKind::MText(t) => {
let upright;
let t = if e.common.matches_layout_orientation() && t.rotation != 0.0 {
upright = cadcraft_doc::MText { rotation: 0.0, ..t.clone() };
&upright
} else {
t
};
cadcraft_render::layout_mtext_entity(d, t).strokes
}
_ => return None,
};
// Points that aren't finite are left out; a text left with none draws nothing to hold.
let strokes: Vec<Vec<Vec2>> =
strokes.into_iter().map(|s| s.into_iter().filter(|p| p.is_finite()).collect::<Vec<_>>()).filter(|s| !s.is_empty()).collect();
(!strokes.is_empty()).then_some(strokes)
}
pub(crate) fn is_infinite(e: &Entity) -> bool {
matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_))
}
@@ -674,7 +740,14 @@ fn in_window_in<'a>(
if !infinite && bx.contains_box(&eb) {
return true;
}
if !crossing || (!infinite && !outline_in(d, e, view, eb).intersects(bx)) {
// A window also holds a text whose box it doesn't hold when it holds what the text draws
// ([`drawn_text`], #3731). Only a text whose box reaches into the window is shaped.
if !crossing {
return !infinite
&& eb.intersects(bx)
&& drawn_text(d, e).is_some_and(|strokes| bx.contains_box(&Bounds2::from_points(strokes.into_iter().flatten())));
}
if !infinite && !outline_in(d, e, view, eb).intersects(bx) {
return false;
}
let polys = hit_polylines_in(d, e, view, tol, true);
@@ -778,21 +851,26 @@ pub fn select_polygon_in(d: &Drawing, space: &Space, frozen: &[String], poly: &[
continue;
}
let eb = if crossing { touch_box_in(d, e, known, &mut view) } else { bounds_in(d, e, known, &mut view) };
if !infinite && if crossing { !eb.intersects(&pb) } else { !pb.contains_box(&eb) } {
continue;
}
let polys = hit_polylines_in(d, e, &mut view, tol, crossing);
let crosses = polys.iter().any(|pl| {
pl.windows(2).any(|w| {
w.first().zip(w.get(1)).is_some_and(|(p, q)| edges.iter().any(|f| cadcraft_geom::line_line(f, &Line::new(*p, *q)).is_some()))
})
});
let mut pts = polys.iter().flatten();
let hit = if crossing {
crosses || pts.any(|p| point_in_polygon(poly, *p))
} else {
!crosses && !polys.is_empty() && pts.all(|p| point_in_polygon(poly, *p))
let boxed = infinite || if crossing { eb.intersects(&pb) } else { pb.contains_box(&eb) };
let test = |polys: &[Vec<Vec2>]| {
let crosses = polys.iter().any(|pl| {
pl.windows(2).any(|w| {
w.first().zip(w.get(1)).is_some_and(|(p, q)| edges.iter().any(|f| cadcraft_geom::line_line(f, &Line::new(*p, *q)).is_some()))
})
});
let mut pts = polys.iter().flatten();
if crossing {
crosses || pts.any(|p| point_in_polygon(poly, *p))
} else {
!crosses && !polys.is_empty() && pts.all(|p| point_in_polygon(poly, *p))
}
};
let mut hit = boxed && test(&hit_polylines_in(d, e, &mut view, tol, crossing));
// A window polygon also holds a text whose box it doesn't hold when it holds what the text
// draws ([`drawn_text`], #3731).
if !hit && !crossing && eb.intersects(&pb) {
hit = drawn_text(d, e).is_some_and(|strokes| test(&strokes));
}
if hit {
out.push(e.handle);
}
@@ -950,6 +1028,33 @@ mod tests {
assert_eq!(pick(&d, &Space::Model, Vec2::new(41.3, 50.0), 1.0), Some(line));
}
/// A text whose points are all not finite (its insertion point is NaN) draws nothing a window
/// polygon could hold: no empty stroke list is passed on for it to hold by default.
#[test]
fn text_with_no_finite_point_draws_nothing_to_hold() {
let mut d = Drawing::new_metric();
let at = Vec3::new(f64::NAN, f64::NAN, 0.0);
let t = cadcraft_doc::Text {
insert: at,
align_pt: None,
height: 1.0,
value: "AB".into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: cadcraft_doc::HAlign::Left,
valign: cadcraft_doc::VAlign::Baseline,
backwards: false,
upside_down: false,
};
let h = d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap();
let e = d.entity(h).unwrap().as_ref().clone();
assert!(drawn_text(&d, &e).is_none());
let square = [Vec2::new(-1e6, -1e6), Vec2::new(1e6, -1e6), Vec2::new(1e6, 1e6), Vec2::new(-1e6, 1e6)];
assert!(select_polygon(&d, &Space::Model, &square, false).is_empty());
}
fn mtext_at(contents: &str, attach: u8, rotation: f64) -> EntityKind {
EntityKind::MText(cadcraft_doc::MText {
insert: Vec3::new(0.0, 0.0, 0.0),
+2 -2
View File
@@ -3,8 +3,8 @@ use super::error::{EngineError, Result};
use super::running::{PendingWindow, Running};
use super::view::View;
use super::{
Arc, Bounds2, Drag, Drawing, Entity, Handle, Input, Origin, Prompt, Session, Space, Step, Value, Vec2, assoc, cmd, find_command, guard, lisp,
pointmod, prompt, select, snap, sysvars, units,
Arc, Bounds2, Drag, Drawing, Entity, Handle, Input, Origin, Prompt, Session, Space, Step, Value, Vec2, Vec3, assoc, cmd, find_command, guard,
lisp, pointmod, prompt, select, snap, sysvars, units,
};
mod cmdline;
+37 -17
View File
@@ -1,10 +1,12 @@
use super::{EngineError, Input, Result, Session, Value, Vec2, cmd, lisp, prompt, snap, units};
use super::{EngineError, Input, Result, Session, Value, Vec2, Vec3, cmd, lisp, prompt, snap, units};
impl Session {
/// Process one line typed at the command line (Enter pressed). Spaces separate inputs as in a
/// script line (see [`Session::script`]), so `MOVE L 0,0 5,5` ends the selection with the
/// second space and `ERASE L ` with the trailing one. Input after the command ends is ignored.
pub fn cmdline(&mut self, text: &str) -> Result<()> {
// The line is typed at the prompt that follows the value the frames are working out.
self.lisp_settle_answer();
let t = text.trim_end_matches(['\r', '\n']);
// The command line types spaces literally at free-text prompts: the line is one input.
if self.current_prompt().is_some_and(|p| p.accept.text && !p.accept.point && !p.accept.number) {
@@ -44,6 +46,8 @@ impl Session {
// comes after that routine: carry it on first, as the window's frames would.
if script {
self.lisp_run_until_input();
} else {
self.lisp_settle_answer();
}
if self.running.is_none() {
if !script && !first {
@@ -122,20 +126,7 @@ impl Session {
return Ok(());
}
};
return match v {
lisp::value::Value::Nil => Ok(()),
lisp::value::Value::Int(i) => self.typed_token(&i.to_string(), false),
lisp::value::Value::Real(r) => self.typed_token(&format!("{r}"), false),
lisp::value::Value::Str(s) => self.typed_token(&s, false),
other => match other.as_point() {
// A point from LISP is in the current UCS, as typed coordinates are.
Some(p) => self.input(Input::Point(self.input_ucs().to_wcs(Vec2::new(p[0], p[1])))),
None => {
self.echo(format!("Invalid input: {}", lisp::value::to_text(&other, true)));
Ok(())
}
},
};
return self.lisp_answer(v);
}
// At "Select objects" prompts the selection modes (Previous, Last, ALL) win over a command
// keyword sharing the letter (HATCH's "picK internal point" against `P`). A word typed with
@@ -169,9 +160,12 @@ impl Session {
}
if prompt.accept.point {
self.note_tilted_ucs();
if let Some(p) = self.parse_typed_point(tt, self.last_point) {
if let Some(p) = self.parse_typed_point3(tt, self.last_point3()) {
self.last_polar = prompt::parse_polar_text(tt, &self.angle_settings());
return self.input(Input::Point(p));
self.point_z = p.z;
let r = self.input(Input::Point(p.xy()));
self.point_z = 0.0;
return r;
}
// Direct distance entry along the tracking path the cursor is on, from the point it
// comes from (an acquired or temporary tracking point needs no base point).
@@ -196,6 +190,32 @@ impl Session {
self.input(Input::Text(tt.to_string()))
}
/// Answer the running command's prompt with the value of a LISP expression typed at it.
pub(crate) fn lisp_answer(&mut self, v: lisp::value::Value) -> Result<()> {
match v {
lisp::value::Value::Nil => Ok(()),
lisp::value::Value::Int(i) => self.typed_token(&i.to_string(), false),
lisp::value::Value::Real(r) => self.typed_token(&format!("{r}"), false),
lisp::value::Value::Str(s) => self.typed_token(&s, false),
other => match other.as_point() {
// A point from LISP is in the current UCS, as typed coordinates are, and a 3D
// point keeps its Z, as a typed `x,y,z` does.
Some(p) => {
let ucs = self.input_ucs();
let xy = ucs.to_wcs(Vec2::new(p[0], p[1]));
self.point_z = p.get(2).copied().filter(|z| z.is_finite()).map_or(0.0, |z| ucs.to_wcs3(Vec3::new(p[0], p[1], z)).z);
let r = self.input(Input::Point(xy));
self.point_z = 0.0;
r
}
None => {
self.echo(format!("Invalid input: {}", lisp::value::to_text(&other, true)));
Ok(())
}
},
}
}
/// Run a script, as AutoCAD reads one: a space or a line end ends an input, and an empty
/// input (two spaces in a row, a space at the end of a line, an empty line) is Enter. At
/// free-text prompts spaces are part of the text. Lines starting with `;` are comments.
+72 -2
View File
@@ -2,7 +2,7 @@ use crate::DisplayOnly;
use super::{
Arc, Bounds2, Drag, Drawing, EngineError, Entity, Handle, Input, Origin, PendingWindow, Prompt, Result, Running, Session, Snapshot, Step, Value,
Vec2, assoc, cmd, find_command, guard, pointmod, select, snap, sysvars,
Vec2, Vec3, assoc, cmd, find_command, guard, pointmod, select, snap, sysvars,
};
impl Session {
@@ -43,12 +43,15 @@ impl Session {
/// Launch a non-nested interactive state machine through the standard command-start checks
/// (`enabled`, `refused_in_editor`, `commands_started`, `last_command`, `Guarded`, `feed`).
/// As in [`Session::start`], the value of an expression the frames are working out answers
/// its prompt before the command it was typed in is cancelled for this one.
pub(crate) fn launch_interactive(
&mut self,
id: &str,
enabled: fn(&Session) -> std::result::Result<(), String>,
machine: Box<dyn crate::Interactive>,
) -> Result<()> {
self.lisp_settle_answer();
self.last_polar = None;
self.pick_hint = None;
if self.running.is_some() {
@@ -78,6 +81,12 @@ impl Session {
self.command_origin
}
/// Whether the input now arriving is the person's own, not a script, LISP routine or
/// JSON/MCP call. Source only: it does not read Shift.
pub fn person_input(&self) -> bool {
self.command_origin == Origin::Person && !self.in_script && !self.program_input
}
/// Whether an AutoLISP routine is feeding the command line now: the `(command …)` call it makes,
/// or the token it types into a command that is already running. A script's own lines are the
/// program's input too ([`Session::start`] records [`Origin::Program`] for them), so this tells a
@@ -104,6 +113,7 @@ impl Session {
/// [`Session::start`] with the command's origin recorded for its whole life.
fn start_from(&mut self, name: &str, origin: Origin) -> Result<()> {
self.lisp_settle_answer();
self.last_polar = None;
self.pick_hint = None;
let name = name.trim();
@@ -217,17 +227,61 @@ impl Session {
/// Feed an object-snap pick, retaining its viewport origin for measurements. Point modifiers
/// that combine or constrain coordinates produce ordinary drawing-space points.
pub fn input_snapped(&mut self, hit: snap::SnapHit) -> Result<()> {
// The value of an expression the frames are working out comes before this pick, and is a
// typed one: it answers its prompt before the pick's origin is in place.
self.lisp_settle_answer();
let source = hit.viewport.filter(|_| self.point_mods.iter().all(|f| matches!(f, pointmod::Frame::Snap { mode } if *mode != 0)));
let previous = std::mem::replace(&mut self.picked_viewport, source);
// An object snap gives the Z of what it snapped to, as in AutoCAD: a survey point's
// level, a contour's elevation (OSNAPZ 1 uses the current elevation instead). A point
// picked through a layout viewport stays at z = 0.
self.point_z = if hit.viewport.is_none() && hit.mode != 0 { self.snap_z(&hit) } else { 0.0 };
let result = self.input(hit.input());
self.point_z = 0.0;
self.picked_viewport = previous;
result
}
/// The Z an object snap gives a point: the Z of the object it snapped to at that point (of
/// the object found there, [`cmd::inquiry::z_at`], when the snap doesn't say), or ELEVATION
/// with OSNAPZ on.
pub(crate) fn snap_z(&self, hit: &snap::SnapHit) -> f64 {
let elevation = self.doc().map(|d| d.header.f64("ELEVATION", 0.0)).unwrap_or(0.0);
let on_source = || {
let d = self.doc().ok()?;
let src = hit.source?;
let z = match src.leaf {
// An object inside a block reference: its Z where the snap lies, placed by the reference.
Some(l) => {
let e = d.blocks.values().find_map(|b| b.entities.get(l.handle))?;
cmd::inquiry::entity_z(e, l.to_block.apply(hit.point)).map(|z| l.z0 + l.zs * z)
}
None => cmd::inquiry::entity_z(d.entity(src.handle)?, hit.point),
};
z.filter(|z| z.is_finite())
};
let z = if self.settings.osnapz { elevation } else { on_source().unwrap_or_else(|| cmd::inquiry::z_at(self, hit.point)) };
if z.is_finite() { z } else { 0.0 }
}
/// LASTPOINT with its Z (z = 0 unless the last point was typed with one, or relative to one).
pub fn last_point3(&self) -> Vec3 {
let (p, z) = self.last_point_z;
self.last_point.to3(if p == self.last_point { z } else { 0.0 })
}
/// The Z of the point a command is being given ([`Input::Point`] carries only X and Y): the
/// third number of a typed `x,y,z` or `@dx,dy,dz` (relative forms add to LASTPOINT's Z), 0
/// for a picked point. Commands that build 3D geometry (3DPOLY) read it with the point.
pub fn point_z(&self) -> f64 {
self.point_z
}
/// Give an input to the running command. With no command running, `Enter` repeats the last
/// command (as in AutoCAD) and points do nothing. A LISP routine waiting in a `get…`
/// function takes the input instead; one paused in `command` carries on after it.
pub fn input(&mut self, input: Input) -> Result<()> {
self.lisp_settle_answer();
self.inputs = self.inputs.wrapping_add(1);
if self.lisp_input(input.clone()) {
return Ok(());
@@ -429,6 +483,7 @@ impl Session {
Some(i) => {
if let Input::Point(p) = &i {
self.last_point = *p;
self.last_point_z = (*p, self.point_z);
if let Some(b) = base.filter(|b| b.is_finite() && p.is_finite() && b.dist(*p) > 1e-12) {
self.last_segment = Some((b, *p));
}
@@ -478,6 +533,7 @@ impl Session {
}
Err(EngineError::Internal(id, m)) => {
// Restore and end the command.
self.lisp_host_ends(self.suspended.is_some());
if let Ok(st) = self.state_mut() {
st.restore_drawing(run.before.clone());
}
@@ -512,6 +568,9 @@ impl Session {
// A typed selection mode or SIngle never outlives its command.
self.select_mode = None;
self.select_single = false;
// The command an expression was typed at the prompt of ends inside that expression's
// routine (Esc, or the expression failed): it is no command of the routine's.
let host = self.lisp_host_ends(self.suspended.is_some());
if find_command(&run.id).is_some_and(|c| c.undoable)
&& let Err(e) = self.refuse_non_finite(None, &run.before, &run.selection_before, &run.id)
{
@@ -534,7 +593,7 @@ impl Session {
// A transparent command's changes belong to the command it ran inside, and a command a
// LISP routine ran belongs to the routine's single undo step (the routine keeps it for U
// inside it).
if self.suspended.is_some() || self.lisp_groups_undo() {
if self.suspended.is_some() || (self.lisp_groups_undo() && !host) {
if let Ok(st) = self.state_mut()
&& !Arc::ptr_eq(&run.before, &st.doc)
{
@@ -551,6 +610,10 @@ impl Session {
st.push_undo(Snapshot { label: label.to_string(), doc: run.before, selection: run.selection_before });
st.revision += 1;
}
// The routine's own undo step starts after the command it was started in.
if host {
self.lisp_rebase();
}
}
/// The post-command passes, in order, run after every command — by [`Session::execute`] and
@@ -740,6 +803,9 @@ impl Session {
/// Change the running array's live parameters. With no array running this does nothing; an
/// invalid value is refused and leaves the command as it was.
pub fn set_array_live(&mut self, v: &crate::ArrayLive) -> Result<()> {
// An edit in the array window comes after the value the frames are working out, which
// can change the array or end the command.
self.lisp_settle_answer();
if self.array_live().is_none() {
return Ok(());
}
@@ -752,12 +818,16 @@ impl Session {
/// Ask the running polar array for its centre as the next canvas point
/// ([`Interactive::array_pick_center`]).
pub fn array_pick_center(&mut self) -> bool {
// The value the frames are working out answers the prompt it was typed at, not the centre's.
self.lisp_settle_answer();
self.running.as_mut().is_some_and(|r| r.machine.array_pick_center())
}
/// Finish the running array: `Ok(true)` when the command ended, `Ok(false)` when there is no
/// array command or it is still selecting objects.
pub fn commit_array(&mut self) -> Result<bool> {
// The value the frames are working out is part of the array that is finished.
self.lisp_settle_answer();
if self.array_live().is_none() {
return Ok(false);
}
+11
View File
@@ -8,6 +8,9 @@ impl Session {
/// the next point, where the drag ends, closes it). Only while objects are being selected: no
/// command running, or a command asking for objects. Returns whether a window was opened.
pub fn begin_window(&mut self, corner: Vec2) -> bool {
// The drag comes after the value the frames are working out: that value answers its
// prompt first, and may be the corner of a window of its own or end the command.
self.lisp_settle_answer();
let during_command = self.running.is_some();
if !self.settings.pickdrag || !corner.is_finite() || (during_command && !self.current_prompt().is_some_and(|p| p.accept.select)) {
return false;
@@ -28,6 +31,8 @@ impl Session {
/// PICKADD on (the default): picks add to the selection and Shift removes. PICKADD off: each pick
/// replaces the selection and Shift adds (Shift+pick on a selected object removes it).
pub fn idle_click(&mut self, p: Vec2, shift: bool) -> Result<()> {
// A click comes after the value the frames are working out, as every input does.
self.lisp_settle_answer();
let space = self.space();
let pickadd = self.settings.pickadd;
if let Some(pw) = self.pending_window.take() {
@@ -114,6 +119,9 @@ impl Session {
/// Pick `h` from the selection cycling list, as a click on it alone would have: into the
/// command at "Select objects", else into the selection (Shift as for [`Self::idle_click`]).
pub fn pick_cycled(&mut self, h: Handle, shift: bool) -> Result<()> {
// Whether a command takes the pick is known once the value the frames are working out
// has answered its prompt: that value can end the command.
self.lisp_settle_answer();
// The list may be older than an undo or an erase.
if self.doc()?.entity(h).is_none() {
return Ok(());
@@ -144,6 +152,9 @@ impl Session {
/// only: a later pick at the same point finds what lies there. Other prompts take the object
/// as a pick.
pub fn input_object(&mut self, h: Handle, at: Option<Vec2>) -> Result<()> {
// What the prompt takes is read once the value the frames are working out has answered
// its own prompt: the object is for the prompt after it.
self.lisp_settle_answer();
let one = self.current_prompt().is_some_and(|p| p.accept.point && !p.accept.select && p.picks_objects());
let p = if one { at.or_else(|| self.doc().ok().and_then(|d| group_10(d, d.entity(h)?))) } else { None };
let Some(p) = p.filter(|p| p.is_finite()) else { return self.input(Input::Pick(vec![h])) };
+4
View File
@@ -16,6 +16,9 @@ pub struct Settings {
pub snapunit: Vec2,
/// OSNAPHATCH: object snaps find hatch objects (off by default, as in AutoCAD).
pub osnaphatch: bool,
/// OSNAPZ: an object snap gives the point the current elevation (on) instead of the Z of the
/// object it snapped to (off, the default, as in AutoCAD).
pub osnapz: bool,
/// GRIDUNIT in a drafting settings snapshot; zero components follow SNAPUNIT.
pub gridunit: Vec2,
/// Major grid line every N minor lines (GRIDMAJOR).
@@ -159,6 +162,7 @@ impl Default for Settings {
snapmode: false,
snapunit: Vec2::new(0.5, 0.5),
osnaphatch: false,
osnapz: false,
gridunit: Vec2::new(0.5, 0.5),
gridmajor: 5,
zoomfactor: 60,
+157 -38
View File
@@ -7,7 +7,7 @@ mod viewport;
pub use viewport::ViewportPoint;
use cadcraft_doc::{Drawing, EntityKind, Handle, Insert, MAX_BLOCK_DEPTH, Prim, Space};
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, Insert, MAX_BLOCK_DEPTH, Prim, Space};
use cadcraft_geom::{Bounds2, Circle, EPS, Ellipse, Mat3, PI, Segment, Vec2, intersect_ext};
use serde::Serialize;
@@ -62,6 +62,31 @@ pub struct SnapHit {
/// curve) until the other end of the line is known. See [`resolve_deferred`].
#[serde(skip_serializing_if = "Option::is_none")]
pub deferred: Option<Deferred>,
/// The entity the snap point lies on (for an intersection, the first of the two), whose Z
/// the picked point takes.
#[serde(skip)]
pub source: Option<SnapSource>,
}
/// What a snap point lies on: an object of the drawing and, for one inside a block reference,
/// the object in the block it came from.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SnapSource {
/// The drawing's object (for a block's contents, the reference).
pub handle: Handle,
pub leaf: Option<BlockLeaf>,
}
/// An object inside a block reference and how the reference places it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BlockLeaf {
/// The object, in its block.
pub handle: Handle,
/// From drawing coordinates to the block's, seen from above.
pub to_block: Mat3,
/// The drawing Z of a block Z `z` is `z0 + zs * z`.
pub z0: f64,
pub zs: f64,
}
impl SnapHit {
@@ -74,7 +99,7 @@ impl SnapHit {
}
fn plain(mode: u32, point: Vec2) -> SnapHit {
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None }
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None, source: None }
}
/// Where this hit sorts among the candidates near a cursor: specific snaps by distance
@@ -385,7 +410,7 @@ fn osnap_in_with_prims(
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?;
let (mut cands, near_prims, mut src) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?;
// Intersections between nearby primitives; Apparent Intersection also where their extensions
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
// that don't reach each other).
@@ -408,12 +433,14 @@ fn osnap_in_with_prims(
for x in intersect_ext(&fix_circle(a), &fix_circle(b), false) {
if x.dist(cursor) <= aperture {
cands.push((real, x));
src.cands.push(src.prims.get(i).copied().flatten());
}
}
if extend {
for x in intersect_ext(a, b, true) {
if x.is_finite() && x.dist(cursor) <= aperture {
cands.push((mode::APP, x));
src.cands.push(src.prims.get(i).copied().flatten());
}
}
}
@@ -422,7 +449,7 @@ fn osnap_in_with_prims(
}
}
}
let hits = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
let hits = finish(cands, &near_prims, src, cursor, aperture, osmode, base, deferred, clip);
Some((hits, near_prims))
}
@@ -475,7 +502,14 @@ pub(crate) fn gather(
aperture: f64,
osmode: u32,
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
gather_in(d, space, ix, cursor, aperture, osmode, &[], None)
gather_in(d, space, ix, cursor, aperture, osmode, &[], None).map(|(cands, prims, _)| (cands, prims))
}
/// The entity each gathered candidate and nearby primitive comes from (parallel to them).
#[derive(Default)]
struct Sources {
cands: Vec<Option<SnapSource>>,
prims: Vec<Option<SnapSource>>,
}
/// The point nearest `cursor` within `aperture` on the visible objects of `space` other than
@@ -492,7 +526,7 @@ pub(crate) fn nearest_with_direction(
skip: Handle,
) -> Option<(Vec2, Vec2)> {
let ix = crate::spatial::index(d, space);
let (_, prims) = gather_in(d, space, &ix, cursor, aperture, 0, frozen, Some(skip))?;
let (_, prims, _) = gather_in(d, space, &ix, cursor, aperture, 0, frozen, Some(skip))?;
let mut best: Option<(f64, Vec2, Vec2)> = None;
let mut consider = |at: Vec2, dir: Vec2| {
let dd = at.dist(cursor);
@@ -538,10 +572,11 @@ fn gather_in(
osmode: u32,
frozen: &[String],
skip: Option<Handle>,
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>, Sources)> {
let probe = Bounds2::new(cursor, cursor).expand(aperture);
let mut cands: Vec<(u32, Vec2)> = Vec::new();
let mut near_prims: Vec<Prim> = Vec::new();
let mut src = Sources::default();
let mut count = 0usize;
let mut budget = MAX_BLOCK_LEAVES;
for (e, known) in crate::select::candidates(d, space, ix, &probe.expand(aperture), true, false)? {
@@ -581,14 +616,17 @@ fn gather_in(
_ => {}
}
}
let own = Some(SnapSource { handle: e.handle, leaf: None });
let mut sink = Sink { osmode, aperture, probe, cands: &mut cands, near: &mut near_prims };
// A record kept as read snaps to its graphics one by one, below.
if !matches!(e.kind, EntityKind::Unknown(_)) {
sink.object(&e.kind, None);
}
// A block reference snaps to the objects inside it, placed by its transform.
// A block reference snaps to the objects inside it, placed by its transform; each snap
// remembers the object it came from, whose Z it takes.
if let EntityKind::Insert(ins) = &e.kind {
block_leaves(d, ins, &Mat3::IDENTITY, 0, &mut budget, frozen, &mut |k, m| sink.object(k, Some(m)));
let z = plan_z(&e.common, ins, (0.0, 1.0));
leaves_with_sources(d, ins, z, e.handle, &mut budget, frozen, &mut sink, &mut src);
}
if let EntityKind::Dimension(dm) = &e.kind {
sink.dimension(d, dm, &mut budget, frozen);
@@ -596,10 +634,43 @@ fn gather_in(
// A proxy snaps to what its graphics draw, and a dimension kept as read to the objects of
// the block it draws through a reference in them (#3438).
if let EntityKind::Unknown(u) = &e.kind {
graphics_leaves(d, u, &Mat3::IDENTITY, 0, &mut budget, frozen, &mut |k, m| sink.object(k, Some(m)));
let f = &mut |be: &Entity, m: &Mat3, z| leaf_with_source(be, m, z, e.handle, &mut sink, &mut src);
graphics_leaves(d, u, &Mat3::IDENTITY, Some((0.0, 1.0)), 0, &mut budget, frozen, f);
}
src.cands.resize(cands.len(), own);
src.prims.resize(near_prims.len(), own);
}
Some((cands, near_prims))
Some((cands, near_prims, src))
}
/// The snaps on the objects inside the block reference `ins` of the drawing's object `handle`
/// (`z`: how it maps its block's Z, [`plan_z`]), each remembering the object it came from.
#[allow(clippy::too_many_arguments)]
fn leaves_with_sources(
d: &Drawing,
ins: &Insert,
z: Option<(f64, f64)>,
handle: Handle,
budget: &mut usize,
frozen: &[String],
sink: &mut Sink<'_>,
src: &mut Sources,
) {
block_leaves(d, ins, &Mat3::IDENTITY, z, 0, budget, frozen, &mut |be, m, z| leaf_with_source(be, m, z, handle, sink, src));
}
/// The snaps on `be`, an object drawn inside the drawing's object `handle` and placed by `m` and
/// `z`, each remembering it.
fn leaf_with_source(be: &Entity, m: &Mat3, z: Option<(f64, f64)>, handle: Handle, sink: &mut Sink<'_>, src: &mut Sources) {
let own = Some(SnapSource { handle, leaf: None });
let (c0, p0) = (sink.cands.len(), sink.near.len());
sink.object(&be.kind, Some(m));
let leaf = z.zip(m.inverse()).map(|((z0, zs), to_block)| BlockLeaf { handle: be.handle, to_block, z0, zs });
let from = Some(SnapSource { handle, leaf });
src.cands.resize(c0, own);
src.cands.resize(sink.cands.len(), from);
src.prims.resize(p0, own);
src.prims.resize(sink.near.len(), from);
}
/// Ranks the gathered candidates within the aperture ([`ranked`]), adding the base-dependent
@@ -608,6 +679,7 @@ fn gather_in(
fn finish(
mut cands: Vec<(u32, Vec2)>,
near_prims: &[Prim],
mut src: Sources,
cursor: Vec2,
aperture: f64,
osmode: u32,
@@ -617,7 +689,7 @@ fn finish(
) -> Vec<SnapHit> {
// Perpendicular / tangent from the base point.
if let Some(bp) = base {
for p in near_prims {
for (p, from) in near_prims.iter().zip(&src.prims) {
if osmode & mode::PER != 0 {
match p {
Prim::Seg(Segment::Line(l)) => cands.push((mode::PER, l.project(bp))),
@@ -649,33 +721,38 @@ fn finish(
};
cands.extend(pts.into_iter().map(|t| (mode::TAN, t)));
}
src.cands.resize(cands.len(), *from);
}
}
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
let mut hits: Vec<SnapHit> =
cands.into_iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).map(|(m, p)| SnapHit::plain(m, p)).collect();
let mut hits: Vec<SnapHit> = cands
.into_iter()
.zip(src.cands.iter().copied().chain(std::iter::repeat(None)))
.filter(|((_, p), _)| visible(*p) && p.dist(cursor) <= aperture)
.map(|((m, p), from)| SnapHit { source: from, ..SnapHit::plain(m, p) })
.collect();
if base.is_none() && deferred {
hits.extend(deferred_hits(near_prims, cursor, aperture, osmode, clip));
hits.extend(deferred_hits(near_prims, &src.prims, cursor, aperture, osmode, clip));
}
if osmode & mode::NEA != 0 {
// The closest point of all nearby objects, whatever their drawing order.
let mut nb: Option<(f64, Vec2)> = None;
let mut consider = |c: Vec2| {
let mut nb: Option<(f64, Vec2, Option<SnapSource>)> = None;
let mut consider = |c: Vec2, from: Option<SnapSource>| {
let dd = c.dist(cursor);
if visible(c) && dd <= aperture && nb.is_none_or(|(bd, _)| dd < bd) {
nb = Some((dd, c));
if visible(c) && dd <= aperture && nb.is_none_or(|(bd, ..)| dd < bd) {
nb = Some((dd, c, from));
}
};
for p in near_prims {
for (p, from) in near_prims.iter().zip(&src.prims) {
for s in prim_segments(p) {
consider(fix_circle(&s).closest(cursor));
consider(fix_circle(&s).closest(cursor), *from);
}
if let Prim::Circle(c) = p {
consider(c.closest(cursor));
consider(c.closest(cursor), *from);
}
}
if let Some((_, p)) = nb {
hits.push(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
if let Some((_, p, source)) = nb {
hits.push(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None, source });
}
}
ranked(hits, cursor, aperture)
@@ -839,7 +916,9 @@ impl Sink<'_> {
fn dimension(&mut self, d: &Drawing, dm: &cadcraft_doc::Dimension, budget: &mut usize, frozen: &[String]) {
match dm.block.as_ref().and_then(|n| d.block(n)) {
Some(blk) => {
block_leaves(d, &dimension_reference(blk, dm), &Mat3::IDENTITY, 0, budget, frozen, &mut |k, m| self.object(k, Some(m)));
block_leaves(d, &dimension_reference(blk, dm), &Mat3::IDENTITY, None, 0, budget, frozen, &mut |be, m, _| {
self.object(&be.kind, Some(m))
});
}
None => {
let g = cadcraft_render::dimension_in(d, dm);
@@ -884,7 +963,19 @@ fn dim_def_points(dm: &cadcraft_doc::Dimension) -> Vec<Vec2> {
/// Calls `f` with each object drawn by a block reference and the transform placing it, nested
/// references expanded (within [`MAX_BLOCK_DEPTH`] levels and `budget` objects); objects that
/// aren't drawn (hidden, on a layer that is off or frozen, attribute definitions) are left out.
fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut usize, frozen: &[String], f: &mut dyn FnMut(&EntityKind, &Mat3)) {
/// The objects inside a block reference, each with its transform and, when every reference on
/// the way is in plan (`z`, from [`plan_z`]), how its Z maps to the drawing's.
#[allow(clippy::too_many_arguments)]
fn block_leaves(
d: &Drawing,
ins: &Insert,
m: &Mat3,
z: Option<(f64, f64)>,
depth: usize,
budget: &mut usize,
frozen: &[String],
f: &mut dyn FnMut(&Entity, &Mat3, Option<(f64, f64)>),
) {
if depth >= MAX_BLOCK_DEPTH {
return;
}
@@ -892,6 +983,7 @@ fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut
if blk.entities.is_empty() {
return;
}
let z = z.map(|(z0, zs)| (z0 - zs * blk.base.z, zs));
let (cols, rows) = (ins.cols.clamp(1, 10_000), ins.rows.clamp(1, 10_000));
for r in 0..rows {
for c in 0..cols {
@@ -912,19 +1004,38 @@ fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut
}
match &be.kind {
EntityKind::AttDef(_) => {}
EntityKind::Insert(inner) => block_leaves(d, inner, &mm, depth + 1, budget, frozen, f),
EntityKind::Insert(inner) => {
let zz = z.and_then(|z| plan_z(&be.common, inner, z));
block_leaves(d, inner, &mm, zz, depth + 1, budget, frozen, f);
}
// A dimension draws its block, as at the top level.
EntityKind::Dimension(dm) if let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n)) => {
block_leaves(d, &dimension_reference(blk, dm), &mm, depth + 1, budget, frozen, f);
let r = dimension_reference(blk, dm);
let zz = z.and_then(|z| plan_z(&be.common, &r, z));
block_leaves(d, &r, &mm, zz, depth + 1, budget, frozen, f);
}
EntityKind::Unknown(u) => graphics_leaves(d, u, &mm, depth + 1, budget, frozen, f),
k => f(k, &mm),
EntityKind::Unknown(u) => graphics_leaves(d, u, &mm, z, depth + 1, budget, frozen, f),
_ => f(be, &mm, z),
}
}
}
}
}
/// How a block reference in plan maps its block's Z to the drawing's, given `outer`, the map of
/// the coordinates it is placed in (`(z0, zs)`: drawing Z = `z0 + zs * z`); `None` for a
/// reference in a tilted or mirrored plane, whose contents keep the reference's own Z.
fn plan_z(common: &cadcraft_doc::Common, ins: &Insert, outer: (f64, f64)) -> Option<(f64, f64)> {
let n = common.extrusion;
if n.x.abs() > 1e-9 || n.y.abs() > 1e-9 || n.z <= 0.0 {
return None;
}
// The block's base point is taken off where the block is looked up, in `block_leaves`.
let (z0, zs) = outer;
let z = (z0 + zs * ins.insert.z, zs * ins.scale.z);
(z.0.is_finite() && z.1.is_finite()).then_some(z)
}
/// Whether `e`, inside a block reference or a record's graphics, is drawn: not hidden, and on
/// layer 0 (which takes the visible layer of what holds it) or a layer that is on and not frozen.
fn drawn_inside(d: &Drawing, e: &cadcraft_doc::Entity, frozen: &[String]) -> bool {
@@ -935,23 +1046,30 @@ fn drawn_inside(d: &Drawing, e: &cadcraft_doc::Entity, frozen: &[String]) -> boo
/// kept dimension's reference to its block, #3438) and the transform `m` placing it, as the
/// renderer draws them: like a block's contents, so graphics on a layer that is off or frozen
/// are left out. The fill hatches are too: each filled shape's outline is drawn as well, and the
/// hatch's sides would offer snaps inside it.
/// hatch's sides would offer snaps inside it. `z` is as in [`block_leaves`]; it is passed on only to
/// the contents of block references, as the graphics themselves carry the record's handle and
/// can't be looked up by it.
#[allow(clippy::too_many_arguments)]
fn graphics_leaves(
d: &Drawing,
u: &cadcraft_doc::Unknown,
m: &Mat3,
z: Option<(f64, f64)>,
depth: usize,
budget: &mut usize,
frozen: &[String],
f: &mut dyn FnMut(&EntityKind, &Mat3),
f: &mut dyn FnMut(&Entity, &Mat3, Option<(f64, f64)>),
) {
for g in &u.graphics {
if matches!(g.kind, EntityKind::Hatch(_)) || !drawn_inside(d, g, frozen) {
continue;
}
match &g.kind {
EntityKind::Insert(inner) => block_leaves(d, inner, m, depth, budget, frozen, f),
k => f(k, m),
EntityKind::Insert(inner) => {
let zz = z.and_then(|z| plan_z(&g.common, inner, z));
block_leaves(d, inner, m, zz, depth, budget, frozen, f);
}
_ => f(g, m, None),
}
}
}
@@ -1024,10 +1142,10 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
/// Every deferred tangent and perpendicular within `aperture` of `cursor`: one per curve and
/// mode, in drawing order (the caller ranks them), so Tab can cycle from the tangent to the
/// perpendicular on the same circle.
fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
/// perpendicular on the same circle. `sources` is parallel to `prims`.
fn deferred_hits(prims: &[Prim], sources: &[Option<SnapSource>], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
let mut hits = Vec::new();
for p in prims {
for (i, p) in prims.iter().enumerate() {
let curve = match p {
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
Prim::Seg(Segment::Arc { arc, .. }) => SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end },
@@ -1048,12 +1166,13 @@ fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip:
if !(at.is_finite() && clip.is_none_or(|c| c.contains(at)) && at.dist(cursor) <= aperture) {
continue;
}
let source = sources.get(i).copied().flatten();
let modes: &[(u32, &'static str)] = match curve {
SnapCurve::Circle { .. } | SnapCurve::Arc { .. } => &[(mode::TAN, "Deferred Tangent"), (mode::PER, "Deferred Perpendicular")],
SnapCurve::Line { .. } => &[(mode::PER, "Deferred Perpendicular")],
};
for &(m, name) in modes.iter().filter(|(m, _)| osmode & m != 0) {
hits.push(SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) });
hits.push(SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }), source });
}
}
hits
+7 -1
View File
@@ -12,6 +12,7 @@ const SESSION_VARS: &[&str] = &[
"ATTREQ",
"OSMODE",
"OSNAPHATCH",
"OSNAPZ",
"HPSPACE",
"HPDOUBLE",
"ANNOAUTOSCALE",
@@ -88,6 +89,7 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
let v = match n.as_str() {
"OSMODE" => json!(st.osmode),
"OSNAPHATCH" => json!(i32::from(st.osnaphatch)),
"OSNAPZ" => json!(i32::from(st.osnapz)),
"HPSPACE" => json!(s.last_used.hatch_spacing),
"HPDOUBLE" => json!(i32::from(s.last_used.hatch_double)),
// AutoCAD's values: positive on, negative off (4 = every annotative object).
@@ -156,7 +158,10 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
"MAXARRAY" => json!(st.maxarray),
"ZOOMFACTOR" => json!(st.zoomfactor),
"MEASUREINIT" => json!(i32::from(st.measureinit)),
"LASTPOINT" => json!([s.last_point.x, s.last_point.y, 0.0]),
"LASTPOINT" => {
let p = s.last_point3();
json!([p.x, p.y, p.z])
}
"AREA" => json!(s.area),
"PERIMETER" => json!(s.perimeter),
"DISTANCE" => json!(s.distance),
@@ -333,6 +338,7 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
// The `color` command's input: ByLayer, ByBlock, a name, an index or a true colour.
"CECOLOR" => crate::cmd::set_current_color_value(s, v).ok_or_else(bad)?,
"OSNAPHATCH" => st.osnaphatch = as_bool(v).ok_or_else(bad)?,
"OSNAPZ" => st.osnapz = as_bool(v).ok_or_else(bad)?,
"HPSPACE" => {
s.last_used.hatch_spacing = as_f64(v).filter(|f| is_supported_hatch_pattern_scale(*f)).ok_or_else(|| EngineError::BadParams {
cmd: "setvar".into(),
+15
View File
@@ -483,6 +483,21 @@ fn copy_and_rotate_drag_as_a_transform_of_the_selection() {
let EntityKind::Text(t) = &extra[1].kind else { panic!("expected the text") };
assert!(t.insert.xy().near(Vec2::new(-2.0, 2.0), 1e-9) && t.rotation.abs() < 1e-9, "mirrored, still reading left to right");
// At "Erase source objects?" the copy stays mirrored in the picked line, wherever the cursor
// goes, and the rubber band is gone (#2667).
s.cmdline("0,1").unwrap();
assert!(s.prompt_text().contains("Erase source objects?"));
let (d, extra) = s.drag(Vec2::new(7.0, -3.0)).expect("MIRROR still shows the mirrored copy");
assert_eq!(d.handles.len(), 1);
assert!(d.matrix.apply(Vec2::new(1.0, 0.0)).near(Vec2::new(-1.0, 0.0), 1e-9), "mirrored in the line from 0,0 to 0,1");
assert_eq!(extra.len(), 1, "only the text, no line to the cursor");
let preview = s.preview(Vec2::new(7.0, -3.0));
assert!(
preview.iter().any(|e| matches!(&e.kind, EntityKind::Line(l) if l.b.xy().near(Vec2::new(-1.0, 0.0), 1e-9))),
"the preview without a GPU shows the mirrored line too"
);
assert_eq!(preview.len(), 2, "the line and the text, no rubber band");
// PASTECLIP drags the clipboard.
let mut s = Session::new();
let l = s.execute("line", &json!({"points": [[0, 0], [1, 0]]})).unwrap();
+5
View File
@@ -244,6 +244,11 @@ impl Session {
crate::prompt::parse_point_in(text, last, &self.angle_settings(), &self.input_ucs())
}
/// [`Session::parse_typed_point`] keeping Z ([`crate::prompt::parse_point3_in`]).
pub fn parse_typed_point3(&self, text: &str, last: Vec3) -> Option<Vec3> {
crate::prompt::parse_point3_in(text, last, &self.angle_settings(), &self.input_ucs())
}
/// A world point in the coordinates shown to the user (the current UCS).
pub fn ucs_point(&self, p: Vec2) -> Vec2 {
self.input_ucs().to_ucs(p)
+69
View File
@@ -439,3 +439,72 @@ fn live_rect_excludes_levels_when_not_associative() {
s.set_array_live(&v).unwrap();
assert_eq!(s.array_live().unwrap().levels, 50);
}
/// How wide the drawing in model space is.
fn drawn_width(s: &Session) -> f64 {
let b = s.doc().unwrap().extents(&cadcraft_engine::doc::Space::Model);
b.max.x - b.min.x
}
/// OK in the array window while the frames work out a count typed at the command line: the count
/// answers its prompt first, as it has when it was worked out at once, and the array has it.
#[test]
fn commit_comes_after_a_pending_expressions_value() {
let committed = [false, true].map(|frames| {
let mut s = selected();
s.lisp_by_frames(frames);
s.start("arrayrect").unwrap();
s.cmdline("columns").unwrap();
s.cmdline(&super::lisp_answer_by_frames::slow("6")).unwrap();
assert_eq!(s.lisp_busy(), frames);
assert!(s.commit_array().unwrap(), "frames {frames}");
assert!(!s.lisp_running(), "frames {frames}: nothing of the expression is left");
drawn_width(&s)
});
let mut plain = selected();
plain.start("arrayrect").unwrap();
assert!(plain.commit_array().unwrap());
assert!(committed[0] > drawn_width(&plain), "six columns are wider than the default four");
assert_eq!(committed[1], committed[0], "over frames, and at once");
}
/// "Pick center" in the array window while the frames work out an item count: the count answers
/// the prompt it was typed at, then the command asks for the centre.
#[test]
fn pick_center_comes_after_a_pending_expressions_value() {
for frames in [false, true] {
let mut s = selected();
s.lisp_by_frames(frames);
s.start("arraypolar").unwrap();
s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap();
s.cmdline("items").unwrap();
s.cmdline(&super::lisp_answer_by_frames::slow("8")).unwrap();
assert_eq!(s.lisp_busy(), frames);
assert!(s.array_pick_center(), "frames {frames}");
assert_eq!(s.array_live().unwrap().items, 8, "frames {frames}: the count answered its own prompt");
assert!(s.current_prompt().unwrap().message.contains("center point of array"), "frames {frames}: {}", s.prompt_text());
}
}
/// An edit in the array window while the frames work out a column count typed at the command
/// line comes after that count, as it does when the count was worked out at once: the window's
/// values are the last ones given, so the array has them.
#[test]
fn an_edit_comes_after_a_pending_expressions_value() {
let lives = [false, true].map(|frames| {
let mut s = selected();
s.lisp_by_frames(frames);
s.start("arrayrect").unwrap();
let mut edited = s.array_live().unwrap();
edited.rows += 2;
s.cmdline("columns").unwrap();
s.cmdline(&super::lisp_answer_by_frames::slow("9")).unwrap();
assert_eq!(s.lisp_busy(), frames);
s.set_array_live(&edited).unwrap();
assert!(!s.lisp_running(), "frames {frames}: nothing of the expression is left");
let live = s.array_live().unwrap();
assert_eq!((live.cols, live.rows), (edited.cols, edited.rows), "frames {frames}");
live
});
assert_eq!(lives[1], lives[0], "over frames, and at once");
}
@@ -0,0 +1,78 @@
//! A dimension drawn from a block is picked on the text of that block only where the text is
//! drawn: text on a layer frozen for the whole drawing, or turned off, is not there to pick (#3218).
//! What the block draws on a drawn layer is still picked, and with the layer thawed or on the text
//! is picked as before.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{EntityKind, Handle};
use serde_json::{Value, json};
/// What the LISP `code` evaluates to, as LISP prints it.
fn lisp(s: &mut Session, code: &str) -> String {
let r = s.execute("lisp", &json!({ "code": code })).unwrap();
r["value"].as_str().unwrap().to_string()
}
/// Whether the pick at `p` finds an object.
fn picks(s: &mut Session, p: [f64; 2]) -> bool {
lisp(s, &format!("(ssget (list {} {}))", p[0], p[1])) != "nil"
}
fn handle(r: &Value) -> Handle {
r["handle"].as_str().or_else(|| r["handles"][0].as_str()).and_then(Handle::parse_hex).unwrap()
}
/// A drawing with a dimension drawn from the block "DT", as AutoCAD saves one: the block holds the
/// dimension's line and its text, and the text alone is on the layer "Hidden".
fn dimension_with_block_text() -> (Session, Handle) {
// Metric, as the issue draws it: the ISO-25 text height makes the dimension's box reach the
// block's text.
let mut s = Session::empty();
s.new_drawing(true);
s.execute("layer.new", &json!({ "name": "Hidden" })).unwrap();
let line = handle(&s.execute("line", &json!({ "points": [[0, 40], [40, 40]] })).unwrap());
s.execute("mtext", &json!({ "at": [20, 44], "text": "40", "height": 3, "attach": 5 })).unwrap();
let text = s.doc().unwrap().model.last().unwrap().handle;
s.execute("properties.set", &json!({ "handles": [text.hex()], "layer": "Hidden" })).unwrap();
assert_eq!(s.doc().unwrap().entity(text).unwrap().common.layer, "Hidden");
s.execute("block", &json!({ "name": "DT", "base": [0, 0], "handles": [line.hex(), text.hex()], "keep": "delete" })).unwrap();
let dim = handle(&s.execute("dimlinear", &json!({ "p1": [0, 5], "p2": [40, 15], "at": [20, 40] })).unwrap());
// The block the dimension draws from, as DXF group 2 of a dimension carries it.
s.doc_mut()
.unwrap()
.modify_entity(dim, |e| {
if let EntityKind::Dimension(dm) = &mut e.kind {
dm.block = Some("DT".into());
}
})
.unwrap();
(s, dim)
}
/// Sets the layer "Hidden" frozen or thawed, and off or on.
fn layer_state(s: &mut Session, frozen: bool, on: bool) {
s.execute("layer.set", &json!({ "name": "Hidden", "frozen": frozen })).unwrap();
s.execute("layer.set", &json!({ "name": "Hidden", "on": on })).unwrap();
}
#[test]
fn a_pick_inside_a_dimension_blocks_text_follows_the_text_layers_state() {
let (mut s, dim) = dimension_with_block_text();
// Thawed: the pick in the middle of the text finds the dimension, as the text is drawn.
layer_state(&mut s, false, true);
assert!(picks(&mut s, [20.0, 44.0]), "the text is drawn, so the pick inside it finds the dimension");
// Beside the text's box, and on the block's line, are as they were.
assert!(!picks(&mut s, [30.0, 44.0]), "the pick beside the text's box is on nothing");
assert!(picks(&mut s, [10.0, 40.0]), "the dimension line the block draws is picked");
// Frozen for the whole drawing: the text is not drawn, so the pick inside it finds nothing.
layer_state(&mut s, true, true);
assert!(!picks(&mut s, [20.0, 44.0]), "the text on a frozen layer is not picked");
assert!(picks(&mut s, [10.0, 40.0]), "the line the block draws on a drawn layer is still picked");
assert_eq!(s.doc().unwrap().entity(dim).unwrap().common.layer, "0", "the dimension itself stays on a drawn layer");
// Turned off: the same.
layer_state(&mut s, false, false);
assert!(!picks(&mut s, [20.0, 44.0]), "the text on a layer turned off is not picked");
assert!(picks(&mut s, [10.0, 40.0]), "the line the block draws on a drawn layer is still picked");
}
+17
View File
@@ -198,3 +198,20 @@ fn an_alignment_grip_aligns_with_the_line_at_the_cursor() {
let Some(cadcraft_engine::doc::EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| &e.kind) else { panic!("a reference") };
assert!((i.rotation.to_degrees() - 30.0).abs() < 1e-6 && i.insert.x.abs() < 1e-9 && (i.insert.y + 50.0).abs() < 1e-9);
}
/// A click on a dynamic grip while the frames work out a value typed at a command's prompt: the
/// value answers its prompt first, as it has when it was worked out at once, then the drag starts.
#[test]
fn a_grip_drag_comes_after_a_pending_expressions_value() {
for frames in [false, true] {
let (mut s, h) = session();
s.lisp_by_frames(frames);
s.cmdline("circle 0,0").unwrap();
s.cmdline(&super::lisp_answer_by_frames::slow("5")).unwrap();
assert_eq!(s.lisp_busy(), frames);
s.start_dyn_grip(h, 2, GripPart::End).unwrap();
assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("grip"), "frames {frames}");
let circles = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_engine::doc::EntityKind::Circle(_))).count();
assert_eq!(circles, 1, "frames {frames}: the radius ended CIRCLE first");
}
}
+62
View File
@@ -338,3 +338,65 @@ fn the_prompts_are_autocads_and_one_point_draws_nothing() {
let s = run("", "(command \"_.LEADER\" '(0.0 0.0) \"\")");
assert!(leaders(&s).is_empty() && mtexts(&s).is_empty());
}
/// A drawing whose current dimension style has an arrow size of 120 and whose header overrides it
/// with `SETVAR DIMASZ 1.5`, as the other DIM* variables of [`session`] are overrides too.
fn session_with_arrow_override() -> Session {
let mut s = session("");
for st in &mut s.doc_mut().unwrap().dim_styles {
st.arrow_size = 120.0;
}
s.execute("setvar", &json!({ "name": "DIMASZ", "value": 1.5 })).unwrap();
assert_eq!(s.doc().unwrap().dim_overrides().get("arrowSize"), Some(&json!(1.5)), "DIMASZ is a header override");
s
}
/// A new leader takes the drawing's DIM* overrides as a new dimension does, whichever command
/// draws it: its hook line and its arrowhead are then the same DIMASZ long.
#[test]
fn a_new_leader_takes_the_headers_dimension_overrides() {
type Draw = fn(&mut Session);
let ways: [(&str, Draw); 4] = [
("LEADER", |s| s.cmdline("(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) '(35.0 30.0) \"\" \"ABC\" \"\")").unwrap()),
("leader (JSON)", |s| drop(s.execute("leader", &json!({ "points": [[0, 0], [20, 15], [35, 30]], "text": "ABC" })).unwrap())),
("QLEADER", |s| {
for t in ["QLEADER", "0,0", "20,15", "35,30", "0", "ABC", ""] {
s.cmdline(t).unwrap();
}
}),
("qleader (JSON)", |s| drop(s.execute("qleader", &json!({ "points": [[0, 0], [20, 15], [35, 30]], "text": "ABC" })).unwrap())),
];
for (way, draw) in ways {
let mut s = session_with_arrow_override();
draw(&mut s);
assert!(s.running.is_none(), "{way}: {}", s.prompt_text());
let l = leaders(&s).remove(0);
// The hook line is the overriding DIMASZ long…
assert!(same_points(&vertices(&l), &[[0.0, 0.0], [20.0, 15.0], [33.5, 30.0], [35.0, 30.0]]), "{way}: {l:?}");
// …and the leader holds the overrides, so its arrowhead is too.
assert_eq!(l.overrides, s.doc().unwrap().dim_overrides(), "{way}");
assert_eq!(l.overrides.get("arrowSize"), Some(&json!(1.5)), "{way}");
let d = s.doc().unwrap();
let drawn = d.dim_style(&l.style).unwrap().with_overrides(&l.overrides);
assert!(near(drawn.arrow_size, 1.5), "{way}: the arrowhead is drawn {} long", drawn.arrow_size);
}
}
/// The overrides a new leader took from the header are saved as one DSTYLE list on it, and a
/// reopen reads them back.
#[test]
fn a_new_leaders_overrides_are_saved_as_one_dstyle_list() {
let mut s = session_with_arrow_override();
s.cmdline("(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) '(35.0 30.0) \"\" \"ABC\" \"\")").unwrap();
let want = leaders(&s).remove(0).overrides;
assert_eq!(want.get("arrowSize"), Some(&json!(1.5)));
let bytes = cadcraft_io::write(s.doc().unwrap(), "out.dxf").unwrap();
let text = String::from_utf8(bytes.clone()).unwrap();
assert_eq!(text.lines().filter(|l| l.trim() == "DSTYLE").count(), 1, "one DSTYLE list in the drawing, the leader's");
let back = cadcraft_io::read(&bytes, "out.dxf").unwrap();
let l = back.model.iter().find_map(|e| if let EntityKind::Leader(l) = &e.kind { Some(l.clone()) } else { None }).unwrap();
assert_eq!(l.overrides.get("arrowSize"), Some(&json!(1.5)));
let was = s.doc().unwrap().dim_style(&l.style).unwrap().with_overrides(&want);
let now = back.dim_style(&l.style).unwrap().with_overrides(&l.overrides);
assert_eq!(now, was, "the leader draws the same after a save and reopen");
}
@@ -0,0 +1,435 @@
//! An AutoLISP expression typed at a command's prompt, in a host that draws frames (#3666): it
//! runs a slice per frame, so Esc stops it, and nothing else about its answer changes.
use cadcraft_engine::doc::EntityKind;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::{Input, Session};
/// A loop that never ends within any allowance, counting in `i`.
const ENDLESS: &str = "(setq i 0) (while (< i 2000000000) (setq i (1+ i)))";
/// A session whose host draws frames, when `frames`.
fn session(frames: bool) -> Session {
let mut s = Session::new();
s.lisp_by_frames(frames);
s
}
/// How far the loop counted.
fn counted(s: &Session) -> f64 {
s.lisp_var("I").as_number().unwrap_or(0.0)
}
/// The radii of the drawing's circles.
fn radii(s: &Session) -> Vec<f64> {
let circle = |k: &EntityKind| if let EntityKind::Circle(c) = k { Some(c.radius) } else { None };
s.doc().unwrap().model.iter().filter_map(|e| circle(&e.kind)).collect()
}
/// The line that says the expression ran out of its allowance, if the log has one.
fn stopped_by_allowance(s: &Session) -> Option<&String> {
s.log.iter().find(|l| l.starts_with("; error:") && l.contains("steps"))
}
/// Draw frames until the routine needs no more; how many it took.
fn frames_to_the_end(s: &mut Session) -> usize {
let mut frames = 0;
while s.lisp_busy() && frames < 10_000 {
s.lisp_tick();
frames += 1;
}
assert!(!s.lisp_busy(), "the routine ended");
frames
}
/// How far [`ENDLESS`] counts as CIRCLE's radius before its allowance stops it, where no frame is
/// drawn.
fn counted_to_the_allowance() -> f64 {
let mut s = session(false);
s.cmdline(&format!("circle 0,0 (progn {ENDLESS} 5)")).unwrap();
assert!(stopped_by_allowance(&s).is_some(), "{:?}", s.log);
counted(&s)
}
/// Esc between two frames stops the expression well before its allowance does, and ends the
/// command it was typed in as a failed expression does. Without frames nothing can come between.
#[test]
fn esc_stops_an_expression_typed_at_a_prompt() {
let mut s = session(true);
s.cmdline("circle 0,0").unwrap();
s.cmdline(&format!("(progn {ENDLESS} 5)")).unwrap();
assert!(s.lisp_busy(), "the expression waits for the next frame: {:?}", s.log);
assert!(s.running.is_some(), "CIRCLE still waits for its radius");
s.lisp_tick();
assert!(s.lisp_busy(), "one more frame did not end it");
s.cancel();
assert!(!s.lisp_running(), "Esc stopped the expression");
assert!(s.running.is_none(), "and the command with it: {}", s.prompt_text());
assert_eq!(stopped_by_allowance(&s), None, "Esc stopped it, not the allowance");
assert!(counted(&s) < counted_to_the_allowance() / 2.0, "it stopped early");
assert!(radii(&s).is_empty(), "the stopped expression gave no radius");
// The command line takes the next command.
s.cmdline("circle 0,0 2").unwrap();
assert_eq!(radii(&s), [2.0]);
}
/// A value that takes several frames answers the prompt it was typed at, as one worked out at
/// once does.
#[test]
fn a_value_worked_out_over_frames_answers_the_prompt() {
let rounds = (counted_to_the_allowance() / 4.0) as i64;
let expr = format!("(progn (setq i 0) (while (< i {rounds}) (setq i (1+ i))) 5)");
let mut by_frames = session(true);
by_frames.cmdline(&format!("circle 0,0 {expr}")).unwrap();
assert!(radii(&by_frames).is_empty(), "no radius before the frames worked it out");
assert!(frames_to_the_end(&mut by_frames) > 1);
assert!(by_frames.running.is_none(), "the radius ended CIRCLE: {}", by_frames.prompt_text());
let mut at_once = session(false);
at_once.cmdline(&format!("circle 0,0 {expr}")).unwrap();
assert_eq!(radii(&by_frames), radii(&at_once));
assert_eq!(radii(&by_frames), [5.0]);
}
/// The allowance holds across frames too: an endless expression ends where it does without them,
/// with the same message, and takes its command with it.
#[test]
fn frames_do_not_lengthen_the_allowance() {
let mut s = session(true);
s.cmdline(&format!("circle 0,0 (progn {ENDLESS} 5)")).unwrap();
assert!(frames_to_the_end(&mut s) > 1);
let mut at_once = session(false);
at_once.cmdline(&format!("circle 0,0 (progn {ENDLESS} 5)")).unwrap();
assert!(stopped_by_allowance(&s).is_some(), "{:?}", s.log);
assert_eq!(stopped_by_allowance(&s), stopped_by_allowance(&at_once));
assert_eq!(counted(&s), counted(&at_once));
assert!(s.running.is_none() && radii(&s).is_empty());
}
/// What is typed while the frames work out a value comes after that value, as it did when the
/// prompt took nothing until the expression ended: LINE's second point is the expression's and the
/// typed point is its third.
#[test]
fn an_input_during_the_expression_comes_after_its_value() {
let rounds = (counted_to_the_allowance() / 4.0) as i64;
let mut s = session(true);
s.cmdline("line 0,0").unwrap();
s.cmdline(&format!("(progn (setq i 0) (while (< i {rounds}) (setq i (1+ i))) (list 5 5))")).unwrap();
assert!(s.lisp_busy(), "the expression waits for the next frame");
s.cmdline("10,0").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let ends: Vec<(Vec2, Vec2)> =
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None }).collect();
assert_eq!(ends, [(Vec2::new(0.0, 0.0), Vec2::new(5.0, 5.0)), (Vec2::new(5.0, 5.0), Vec2::new(10.0, 0.0))]);
}
/// A script's line is answered before its next line is read, in a host with frames too: nothing
/// would draw a frame inside the script.
#[test]
fn a_script_gets_the_value_before_its_next_line() {
let rounds = (counted_to_the_allowance() / 4.0) as i64;
let mut s = session(true);
s.script(&format!("circle 0,0 (progn (setq i 0) (while (< i {rounds}) (setq i (1+ i))) 5)\ncircle 0,0 2\n")).unwrap();
assert_eq!(radii(&s), [5.0, 2.0]);
}
/// An expression that takes several frames to work out `value`.
pub(super) fn slow(value: &str) -> String {
let rounds = (counted_to_the_allowance() / 4.0) as i64;
format!("(progn (setq i 0) (while (< i {rounds}) (setq i (1+ i))) {value})")
}
/// The ends of the drawing's lines, in draw order.
fn lines(s: &Session) -> Vec<(Vec2, Vec2)> {
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None }).collect()
}
/// A session with one circle, its own undo step, drawn before anything else.
fn session_with_a_circle(frames: bool) -> Session {
let mut s = session(frames);
s.cmdline("circle 50,50 1").unwrap();
s
}
/// The value of a routine that ended in an earlier frame is not the answer of an expression the
/// frames are still working out: the prompt gets that expression's own value, once.
#[test]
fn a_deferred_answer_is_not_an_earlier_routines_value() {
let mut s = session(true);
s.cmdline(&slow("(list 99 99)")).unwrap();
assert!(frames_to_the_end(&mut s) > 1, "the routine at Command: ended in a later frame");
s.cmdline("line 0,0").unwrap();
s.cmdline(&slow("(list 5 5)")).unwrap();
assert!(s.lisp_busy(), "the expression waits for the next frame: {:?}", lines(&s));
assert!(lines(&s).is_empty(), "nothing has answered the prompt yet");
frames_to_the_end(&mut s);
s.cmdline("").unwrap();
assert_eq!(lines(&s), [(Vec2::new(0.0, 0.0), Vec2::new(5.0, 5.0))]);
}
/// A routine that goes on in later frames has no value yet: the call that started it returns
/// none, whatever an earlier routine left.
#[test]
fn a_routine_that_goes_on_returns_no_earlier_value() {
let mut s = session(true);
s.cmdline(&slow("(list 99 99)")).unwrap();
frames_to_the_end(&mut s);
let started = s.lisp_eval(&slow("7"), false, false, Vec::new()).unwrap();
assert!(s.lisp_busy(), "the routine waits for the next frame");
assert!(started.is_none(), "{started:?}");
}
/// Esc in an expression the frames are working out ends its command as Esc at the prompt does:
/// what the command drew stays, as one undo step of its own.
#[test]
fn esc_in_an_expression_keeps_the_commands_undo_step() {
let mut s = session_with_a_circle(true);
s.cmdline("line 0,0 5,5").unwrap();
s.cmdline(&format!("(progn {ENDLESS} (list 9 9))")).unwrap();
assert!(s.lisp_busy(), "the expression waits for the next frame");
s.cancel();
assert!(s.running.is_none() && !s.lisp_running(), "{}", s.prompt_text());
let mut plain = session_with_a_circle(true);
plain.cmdline("line 0,0 5,5").unwrap();
plain.cancel();
assert_eq!(lines(&s), lines(&plain), "Esc keeps the segment");
for step in ["the segment", "the circle"] {
assert_eq!(s.undo().unwrap(), plain.undo().unwrap(), "U takes back {step}");
assert_eq!((lines(&s), radii(&s)), (lines(&plain), radii(&plain)), "U takes back {step}");
}
assert!(lines(&s).is_empty() && radii(&s).is_empty());
}
/// The same when the expression was typed at the prompt of a transparent command inside LINE:
/// Esc ends both, and LINE's segment is still LINE's undo step.
#[test]
fn esc_in_an_expression_at_a_transparent_prompt_keeps_the_outer_commands_undo_step() {
let mut s = session_with_a_circle(true);
s.cmdline("line 0,0 5,5").unwrap();
s.cmdline("'zoom").unwrap();
assert!(s.suspended.is_some(), "ZOOM runs inside LINE: {}", s.prompt_text());
s.cmdline(&format!("(progn {ENDLESS} 2)")).unwrap();
assert!(s.lisp_busy(), "the expression waits for the next frame: {}", s.prompt_text());
s.cancel();
assert!(s.running.is_none() && s.suspended.is_none() && !s.lisp_running(), "{}", s.prompt_text());
assert_eq!(lines(&s).len(), 1, "Esc keeps the segment");
s.undo().unwrap();
assert!(lines(&s).is_empty(), "U takes the segment back");
assert_eq!(radii(&s), [1.0], "and nothing before it");
}
/// An expression that fails ends its command, with frames (found out when the next input waits
/// for it) and without: what the command drew is still its own undo step.
#[test]
fn a_failed_expression_keeps_the_commands_undo_step() {
for frames in [false, true] {
let mut s = session_with_a_circle(frames);
s.cmdline("line 0,0 5,5").unwrap();
s.cmdline(&slow("(car 1)")).unwrap();
assert_eq!(s.lisp_busy(), frames);
if frames {
s.input(Input::Point(Vec2::new(9.0, 9.0))).unwrap();
}
assert!(s.running.is_none() && !s.lisp_running(), "frames {frames}: the failed expression ended LINE: {}", s.prompt_text());
assert_eq!(lines(&s).len(), 1, "frames {frames}: the segment stays");
s.undo().unwrap();
assert!(lines(&s).is_empty(), "frames {frames}: U takes the segment back");
assert_eq!(radii(&s), [1.0], "frames {frames}: and nothing before it");
}
}
/// A value the frames worked out leaves the command one undo step, as a value worked out at once
/// does: U takes back every segment of the LINE.
#[test]
fn a_command_answered_over_frames_is_one_undo_step() {
for frames in [false, true] {
let mut s = session_with_a_circle(frames);
s.cmdline("line 0,0 5,5").unwrap();
s.cmdline(&slow("(list 9 9)")).unwrap();
if frames {
assert!(frames_to_the_end(&mut s) > 1);
}
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s).len(), 2, "frames {frames}");
s.undo().unwrap();
assert!(lines(&s).is_empty(), "frames {frames}: one U takes back both segments");
assert_eq!(radii(&s), [1.0], "frames {frames}: and nothing before them");
}
}
/// A session with one circle where CIRCLE at 0,0 was given the expression `value` as its radius:
/// with frames the expression is still being worked out, without them it has answered.
fn circle_given(frames: bool, value: &str) -> Session {
let mut s = session_with_a_circle(frames);
s.cmdline("circle 0,0").unwrap();
s.cmdline(&slow(value)).unwrap();
assert_eq!(s.lisp_busy(), frames, "only frames leave the expression waiting");
s
}
/// A session with one circle where LINE, one segment drawn, was given the expression `value` as
/// its next point: with frames the expression is still being worked out.
fn line_given(frames: bool, value: &str) -> Session {
let mut s = session_with_a_circle(frames);
s.cmdline("line 0,0 5,5").unwrap();
s.cmdline(&slow(value)).unwrap();
assert_eq!(s.lisp_busy(), frames, "only frames leave the expression waiting");
s
}
/// The name of the command that waits for input.
fn running(s: &Session) -> Option<&str> {
s.running.as_ref().map(|r| r.id.as_str())
}
/// A table pasted from the clipboard starts its command after the value the frames are working
/// out has answered its prompt, as a command typed meanwhile does: a value that ends the waiting
/// command ends it, and one that leaves it running is in the drawing before that command is
/// cancelled for the paste.
#[test]
fn a_pasted_table_comes_after_a_pending_expressions_value() {
for frames in [false, true] {
let mut s = circle_given(frames, "5");
s.start_paste_table("a\tb\n1\t2", None).unwrap();
assert_eq!(radii(&s), [1.0, 5.0], "frames {frames}: the radius ended CIRCLE first");
assert_eq!(running(&s), Some("pastetable"), "frames {frames}");
let mut s = line_given(frames, "(list 9 9)");
s.start_paste_table("a\tb\n1\t2", None).unwrap();
assert_eq!(running(&s), Some("pastetable"), "frames {frames}");
assert!(!s.lisp_running(), "frames {frames}: nothing of the expression is left");
let (a, b, c) = (Vec2::new(0.0, 0.0), Vec2::new(5.0, 5.0), Vec2::new(9.0, 9.0));
assert_eq!(lines(&s), [(a, b), (b, c)], "frames {frames}: the point was LINE's before the paste cancelled it");
s.cancel();
s.undo().unwrap();
assert!(lines(&s).is_empty(), "frames {frames}: both segments are LINE's one undo step");
assert_eq!(radii(&s), [1.0], "frames {frames}: and nothing before them");
}
}
/// An expression that fails while a pasted table waits behind it ends its command as it does
/// without frames, and the paste starts.
#[test]
fn a_pasted_table_comes_after_a_pending_expression_that_fails() {
for frames in [false, true] {
let mut s = line_given(frames, "(car 1)");
s.start_paste_table("a\tb\n1\t2", None).unwrap();
assert_eq!(running(&s), Some("pastetable"), "frames {frames}");
assert!(!s.lisp_running(), "frames {frames}");
assert!(s.log.iter().any(|l| l.starts_with("; error: bad argument")), "frames {frames}: the failure is reported as it is: {:?}", s.log);
assert_eq!(lines(&s).len(), 1, "frames {frames}");
}
}
/// A click on a grip starts its edit after the pending value has answered its prompt.
#[test]
fn a_grip_edit_comes_after_a_pending_expressions_value() {
for frames in [false, true] {
let mut s = circle_given(frames, "5");
let first = s.doc().unwrap().model.iter().next().unwrap().handle;
s.start_grip_edit(&[(first, 0)]).unwrap();
assert_eq!(radii(&s), [1.0, 5.0], "frames {frames}: the radius ended CIRCLE first");
assert_eq!(running(&s), Some("grip"), "frames {frames}");
}
}
/// A programmatic undo or redo ends the running command first, and the command a pending value
/// ends has ended with that value: U takes back that command, not the step before it, and REDO
/// finds what it finds without frames.
#[test]
fn a_programmatic_undo_comes_after_a_pending_expressions_value() {
for frames in [false, true] {
let mut s = circle_given(frames, "5");
s.execute("u", &serde_json::json!({})).unwrap();
assert_eq!(radii(&s), [1.0], "frames {frames}: U took back the CIRCLE the value ended");
assert!(!s.lisp_running() && s.running.is_none(), "frames {frames}");
}
let redone = [false, true].map(|frames| {
let mut s = session_with_a_circle(frames);
s.cmdline("circle 0,0 2").unwrap();
s.execute("u", &serde_json::json!({})).unwrap();
s.cmdline("circle 0,0").unwrap();
s.cmdline(&slow("5")).unwrap();
s.execute("redo", &serde_json::json!({})).unwrap();
radii(&s)
});
assert_eq!(redone[1], redone[0], "REDO after a value worked out over frames, and at once");
assert!(redone[0].contains(&5.0), "{redone:?}");
}
/// An object picked from the selection-cycling list while the frames work out the value that
/// ends the command is picked with no command running, as it is without frames: it is selected.
#[test]
fn a_cycled_pick_comes_after_a_pending_expressions_value() {
for frames in [false, true] {
let mut s = circle_given(frames, "5");
let first = s.doc().unwrap().model.iter().next().unwrap().handle;
s.pick_cycled(first, false).unwrap();
assert_eq!(radii(&s), [1.0, 5.0], "frames {frames}");
assert_eq!(s.selection(), [first], "frames {frames}: the pick selected the object");
}
}
/// A line typed while the frames work out the value before a free-text prompt is that prompt's
/// text, spaces included, as it is when the value was worked out at once.
#[test]
fn a_line_typed_during_the_expression_is_the_text_of_the_prompt_after_it() {
for frames in [false, true] {
let mut s = session(frames);
s.cmdline("text 0,0 2.5").unwrap();
s.cmdline(&slow("0")).unwrap();
assert_eq!(s.lisp_busy(), frames);
s.cmdline("two words").unwrap();
s.cmdline("").unwrap();
let texts: Vec<String> =
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.value.clone()) } else { None }).collect();
assert_eq!(texts, ["two words"], "frames {frames}: {}", s.prompt_text());
}
}
/// Reading the drawing through `execute`, as panels do while they are open, is no input: the
/// expression goes on waiting for its frames, and Esc still stops it.
#[test]
fn a_read_through_execute_leaves_the_expression_to_its_frames() {
let mut s = session_with_a_circle(true);
s.cmdline("circle 0,0").unwrap();
s.cmdline(&format!("(progn {ENDLESS} 5)")).unwrap();
s.execute("drawing.inspect", &serde_json::json!({})).unwrap();
assert!(s.lisp_busy(), "the read did not run the expression to its allowance");
assert_eq!(stopped_by_allowance(&s), None);
s.cancel();
assert!(!s.lisp_running() && s.running.is_none());
assert_eq!(radii(&s), [1.0]);
}
/// The centres of the drawing's circles.
fn centres(s: &Session) -> Vec<Vec2> {
let circle = |k: &EntityKind| if let EntityKind::Circle(c) = k { Some(c.center.xy()) } else { None };
s.doc().unwrap().model.iter().filter_map(|e| circle(&e.kind)).collect()
}
/// A press-and-drag selection window started while the frames work out a point for ERASE's
/// "Select objects" comes after that point, as it does without frames: the drag's two corners
/// make the window, so the circle inside it is erased and the one between the expression's
/// point and the drag's first corner stays.
#[test]
fn a_dragged_window_comes_after_a_pending_expressions_point() {
let (kept, inside) = (Vec2::new(5.0, 5.0), Vec2::new(15.0, 15.0));
for frames in [false, true] {
let mut s = session(frames);
s.settings.pickdrag = true;
s.cmdline("circle 5,5 1").unwrap();
s.cmdline("circle 15,15 1").unwrap();
s.cmdline("erase").unwrap();
s.cmdline(&slow("(list 0 0)")).unwrap();
assert_eq!(s.lisp_busy(), frames, "only frames leave the expression waiting");
assert!(s.begin_window(Vec2::new(10.0, 10.0)), "frames {frames}: the drag opened a window");
assert!(!s.lisp_running(), "frames {frames}: nothing of the expression is left");
s.input(Input::Point(Vec2::new(20.0, 20.0))).unwrap();
assert!(s.pending_window.is_none(), "frames {frames}: the drag's end closed its window");
s.input(Input::Enter).unwrap();
assert!(s.running.is_none(), "frames {frames}: {}", s.prompt_text());
assert_eq!(centres(&s), [kept], "frames {frames}: only the circle at {inside:?} was in the window");
}
}
@@ -0,0 +1,202 @@
//! `getangle` and `getorient` answered from the `lisp` command's `inputs` return radians (#3398):
//! an input is read as the same answer at the prompt, a number as that number typed, so the
//! result works in `polar` and `cos`.
use std::f64::consts::{FRAC_PI_2, FRAC_PI_4, PI};
use cadcraft_engine::Session;
use serde_json::{Value, json};
/// How far two numbers may differ and still be the same angle or length.
const TOL: f64 = 1e-9;
/// The `lisp` command's result for `code` answered with `inputs`.
fn run(s: &mut Session, code: &str, inputs: Value) -> Value {
s.execute("lisp", &json!({ "code": code, "inputs": inputs })).unwrap()
}
/// The printed value of `code` answered with `inputs`.
fn value(s: &mut Session, code: &str, inputs: Value) -> String {
let r = run(s, code, inputs);
r["value"].as_str().unwrap_or_else(|| panic!("{code}: {r}")).to_string()
}
/// How far the number `code` gives is from `want`. LISP takes the difference, at full precision,
/// since a printed real keeps six digits.
fn off(s: &mut Session, code: &str, inputs: Value, want: f64) -> f64 {
let text = value(s, &format!("(- {code} {want:?})"), inputs);
text.parse::<f64>().unwrap_or_else(|_| panic!("{code}: {text}")).abs()
}
/// A number given as an input is read as that number typed: degrees by default, returned in
/// radians, as a whole number, a real and a string.
#[test]
fn a_number_given_to_getangle_is_degrees_typed_and_comes_back_in_radians() {
let mut s = Session::new();
// The report's case: 45 came back as 45.
assert!(off(&mut s, "(getangle '(0 0) \"Angle: \")", json!([45]), FRAC_PI_4) < TOL);
assert!(off(&mut s, "(getangle)", json!([22.5]), FRAC_PI_4 / 2.0) < TOL);
// The same answer as text came back as the string.
assert!(off(&mut s, "(getangle '(0 0) \"Angle: \")", json!(["45"]), FRAC_PI_4) < TOL);
}
/// The angle `getangle` returns can go straight to `polar`: 10 units along a typed 45 lands on
/// the 45 degree point.
#[test]
fn polar_takes_the_angle_getangle_returns() {
let mut s = Session::new();
let (x, y) = (10.0 * FRAC_PI_4.cos(), 10.0 * FRAC_PI_4.sin());
let code = format!("(distance (polar '(0 0) (getangle '(0 0) \"Angle: \") 10) (list {x:?} {y:?}))");
assert!(off(&mut s, &code, json!([45]), 0.0) < TOL, "10 units along 45 degrees");
}
/// Points given as inputs are points picked: two of them, or the base point and one, give the
/// angle of their line, the next call keeps its own input, and a lone first point gives nil.
#[test]
fn points_given_to_getangle_give_the_angle_of_their_line() {
let mut s = Session::new();
// Two points, without a base point.
assert!(off(&mut s, "(getangle)", json!([[1, 1], [2, 3]]), 2f64.atan2(1.0)) < TOL);
// The base point and one point.
assert!(off(&mut s, "(getangle '(1 1))", json!([[1, 2]]), FRAC_PI_2) < TOL);
// The call after it still gets its own answer.
assert_eq!(value(&mut s, "(list (equal (getangle) (/ pi 4) 1e-9) (getreal))", json!([[0, 0], [5, 5], 2.5])), "(T 2.5)");
// A first point with no second to follow: no angle.
assert_eq!(value(&mut s, "(getangle)", json!([[1, 1]])), "nil");
}
/// A null input is Enter: nil from both functions, and it answers one call only.
#[test]
fn enter_given_to_getangle_is_nil() {
let mut s = Session::new();
assert_eq!(value(&mut s, "(getangle '(0 0) \"Angle: \")", json!([null])), "nil");
assert_eq!(value(&mut s, "(getorient)", json!([null])), "nil");
// Enter answers one call only.
assert_eq!(value(&mut s, "(list (getangle) (equal (getangle) (/ pi 6) 1e-9))", json!([null, 30])), "(nil T)");
}
/// Text given as an input takes the unit forms the command line takes: radians, grads, degrees
/// and degrees with minutes.
#[test]
fn text_given_to_getangle_takes_the_unit_forms_the_command_line_takes() {
let mut s = Session::new();
for (text, want) in [("0.5r", 0.5), ("50g", FRAC_PI_4), ("45d", FRAC_PI_4), ("30d30'", 30.5f64.to_radians())] {
assert!(off(&mut s, "(getangle)", json!([text]), want) < TOL, "{text}");
}
}
/// A bare number is read in the drawing's angular units (AUNITS): radians and grads, while a
/// form that names its unit keeps it.
#[test]
fn a_number_given_to_getangle_is_read_in_aunits() {
let mut s = Session::new();
// Radians.
assert!(off(&mut s, "(progn (setvar \"AUNITS\" 3) (getangle))", json!([0.5]), 0.5) < TOL);
assert!(off(&mut s, "(getorient)", json!([0.5]), 0.5) < TOL);
// Grads.
assert!(off(&mut s, "(progn (setvar \"AUNITS\" 2) (getangle))", json!([50]), FRAC_PI_4) < TOL);
// A unit typed with the number still wins.
assert!(off(&mut s, "(getangle)", json!(["45d"]), FRAC_PI_4) < TOL);
}
/// With the zero direction turned north (ANGBASE), `getangle` measures from it and `getorient`
/// from east, for a typed angle and for a picked point.
#[test]
fn getorient_returns_radians_from_east_whatever_angbase_is() {
let mut s = Session::new();
assert!(off(&mut s, "(getorient '(0 0) \"Angle: \")", json!([45]), FRAC_PI_4) < TOL);
assert!(off(&mut s, "(getorient '(0 0))", json!([[-1, 0]]), PI) < TOL);
// ANGBASE north: 45 typed is 45 degrees from north. `getangle` returns the angle from
// ANGBASE, `getorient` the direction from east.
assert!(off(&mut s, "(setvar \"ANGBASE\" (/ pi 2))", json!([]), FRAC_PI_2) < TOL);
assert!(off(&mut s, "(getangle)", json!([45]), FRAC_PI_4) < TOL);
assert!(off(&mut s, "(getorient)", json!([45]), 3.0 * FRAC_PI_4) < TOL);
// A point west of the base: 90 degrees from north, 180 from east.
assert!(off(&mut s, "(getangle '(0 0))", json!([[-1, 0]]), FRAC_PI_2) < TOL);
assert!(off(&mut s, "(getorient '(0 0))", json!([[-1, 0]]), PI) < TOL);
}
/// An input the prompt would refuse is reported in the output and the next input is taken, as a
/// prompt asks again; `initget` bits and keywords apply.
#[test]
fn an_answer_getangle_refuses_is_reported_and_the_next_one_taken() {
let mut s = Session::new();
let r = run(&mut s, "(equal (getangle) (/ pi 6) 1e-9)", json!(["north-ish", 30]));
assert_eq!(r["value"], "T", "{r}");
let output = r["output"].as_array().unwrap();
assert!(output.iter().any(|l| l.as_str().is_some_and(|l| l.contains("angle"))), "the refusal is in the output: {r}");
// `initget` still applies: zero refused, then a keyword.
let code = "(progn (initget 2 \"Reference\") (getangle))";
assert_eq!(value(&mut s, code, json!([0, "r"])), "\"Reference\"");
}
/// Empty or blank text given as an input is Enter, as an empty line is at the prompt: nil, and
/// the next call keeps its own input. With `initget` bit 1 Enter is refused, and the next input
/// is the answer.
#[test]
fn empty_text_given_to_getangle_is_enter() {
let mut s = Session::new();
assert_eq!(value(&mut s, "(list (getangle) (getreal))", json!(["", 30])), "(nil 30)");
assert_eq!(value(&mut s, "(list (getorient '(0 0)) (getreal))", json!([" ", 30])), "(nil 30)");
// Enter is not allowed: the empty text is refused as Enter is, and 30 answers the call.
let r = run(&mut s, "(progn (initget 1) (list (equal (getangle) (/ pi 6) 1e-9) (getreal)))", json!(["", 30, 2.5]));
assert_eq!(r["value"], "(T 2.5)", "{r}");
let null = run(&mut s, "(progn (initget 1) (list (equal (getangle) (/ pi 6) 1e-9) (getreal)))", json!([null, 30, 2.5]));
assert_eq!(r["output"], null["output"], "refused with the words Enter is refused with");
}
/// Coordinates given as text are a point, as they are typed at the prompt: with the base point
/// they give the angle of the line, two of them do without one, and the next call keeps its own
/// input.
#[test]
fn coordinate_text_given_to_getangle_is_a_point() {
let mut s = Session::new();
assert_eq!(value(&mut s, "(list (equal (getangle '(0 0)) (/ pi 4) 1e-9) (getreal))", json!(["1,1", 2.5])), "(T 2.5)");
assert!(off(&mut s, "(getangle)", json!(["1,1", "2,3"]), 2f64.atan2(1.0)) < TOL);
assert!(off(&mut s, "(getorient '(1 1))", json!(["1,2"]), FRAC_PI_2) < TOL);
// The polar and relative forms are points as well (the last point is the origin here).
assert!(off(&mut s, "(getangle '(0 0))", json!(["1<45"]), FRAC_PI_4) < TOL);
assert!(off(&mut s, "(getangle '(0 0))", json!(["@1,1"]), FRAC_PI_4) < TOL);
// A keyword that also reads as a point (`@`, the last point) stays the keyword, as at the prompt.
assert_eq!(value(&mut s, "(progn (initget \"@\") (getangle '(1 1)))", json!(["@"])), "\"@\"");
}
/// The angle `text` gives when typed at the prompt of `call`, and how far the angle it gives as
/// an input is from that.
fn typed_and_given(s: &mut Session, call: &str, text: &str) -> (String, f64) {
s.cmdline(&format!("(setq typed {call})")).unwrap();
s.cmdline(text).unwrap();
let typed = value(s, "typed", json!([]));
let apart = value(s, &format!("(abs (- {call} typed))"), json!([text]));
let apart = apart.parse().unwrap_or_else(|_| panic!("{call} {text}: {apart} (typed: {typed})"));
(typed, apart)
}
/// Every form of point and angle text gives, as an input, the angle it gives typed at the
/// prompt: absolute, relative to the last point, polar, world coordinates, bare and unit-bearing
/// angles; also with the zero direction north and in a moved, turned UCS.
#[test]
fn text_given_to_getangle_is_read_as_the_same_text_typed_at_the_prompt() {
const TEXTS: [&str; 12] = ["1,1", "3,4,5", "@1,1", "@2<30", "@", "1<45", "2<<30", "#3,4", "*1,2", "*@1,2", "45", "0.5r"];
let mut s = Session::new();
s.last_point = cadcraft_geom::Vec2::new(5.0, 2.0);
for text in TEXTS {
for call in ["(getangle '(1 0))", "(getorient '(1 0))"] {
let (typed, apart) = typed_and_given(&mut s, call, text);
assert!(apart < TOL, "{call} {text}: typed {typed}, {apart} apart");
}
}
// The relative forms count from the last point, not the origin.
let (typed, _) = typed_and_given(&mut s, "(getangle '(5 2))", "@1,1");
assert_eq!(typed, value(&mut s, "(/ pi 4)", json!([])));
// North is zero, and the UCS sits at (100, 50) turned a quarter turn.
value(&mut s, "(setvar \"ANGBASE\" (/ pi 2))", json!([]));
s.execute("ucs", &json!({"option": "origin", "origin": [100, 50]})).unwrap();
s.execute("ucs", &json!({"option": "z", "angle": 90})).unwrap();
for text in TEXTS {
for call in ["(getangle '(1 0))", "(getorient '(1 0))"] {
let (typed, apart) = typed_and_given(&mut s, call, text);
assert!(apart < TOL, "ANGBASE and UCS, {call} {text}: typed {typed}, {apart} apart");
}
}
}
+81
View File
@@ -0,0 +1,81 @@
//! LISP `textbox` (#3676): the smallest box around a TEXT as drawn, relative to its insertion
//! point and unrotated.
use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{EntityCodec, set_entity_codec};
use cadcraft_engine::doc::Space;
use serde_json::json;
fn session() -> Session {
set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups });
Session::new()
}
/// The value of `code` as LISP prints it.
fn lisp(s: &mut Session, code: &str) -> String {
let r = s.execute("lisp", &json!({ "code": code })).unwrap();
r["value"].as_str().unwrap().to_string()
}
/// `(textbox …)` as [min x, min y, max x, max y]; None for nil.
fn textbox(s: &mut Session, elist: &str) -> Option<[f64; 4]> {
let v = lisp(s, &format!("(textbox {elist})"));
if v == "nil" {
return None;
}
let n: Vec<f64> = v.replace(['(', ')'], " ").split_whitespace().map(|x| x.parse().unwrap()).collect();
assert_eq!(n.len(), 6, "{v}");
Some([n[0], n[1], n[3], n[4]])
}
fn width(b: [f64; 4]) -> f64 {
b[2] - b[0]
}
#[test]
fn textbox_measures_text_as_drawn() {
let mut s = session();
let short = textbox(&mut s, "'((1 . \"AB\"))").expect("a list with only the string");
let long = textbox(&mut s, "'((1 . \"ABCDEFGH\"))").unwrap();
assert!(width(long) > width(short), "{long:?} {short:?}");
assert!(short[0] < short[2] && short[1] < short[3], "{short:?}");
// Height 40 against the default TEXTSIZE: every edge scales by their ratio.
let size: f64 = lisp(&mut s, "(getvar \"TEXTSIZE\")").parse().unwrap();
let tall = textbox(&mut s, "'((1 . \"AB\") (40 . 40.0))").unwrap();
for i in 0..4 {
assert!((tall[i] - short[i] * 40.0 / size).abs() <= 1e-6 * 40.0, "{tall:?} {short:?}");
}
let wide = textbox(&mut s, "'((1 . \"AB\") (41 . 2.0))").unwrap();
assert!((width(wide) - 2.0 * width(short)).abs() <= 1e-9 + 1e-6 * width(short), "{wide:?} {short:?}");
// The box is the drawn text's: letters that reach below the baseline lower its first corner,
// which capitals leave at about the insertion point.
let low = textbox(&mut s, "'((1 . \"gyp\"))").unwrap();
assert!(low[1] < short[1] && short[1] > -0.05 * size, "{low:?} {short:?}");
// A string that draws nothing still has its advance and height.
let blank = textbox(&mut s, "'((1 . \" \"))").expect("spaces");
assert!(blank[0] == 0.0 && blank[1] == 0.0 && blank[2] > 0.0 && blank[3] > 0.0, "{blank:?}");
// Not a text: nil.
assert_eq!(textbox(&mut s, "'((0 . \"LINE\") (10 0.0 0.0 0.0) (11 5.0 5.0 0.0) (1 . \"x\"))"), None);
assert_eq!(textbox(&mut s, "'((0 . \"TEXT\") (40 . 1.0))"), None, "no string");
assert_eq!(textbox(&mut s, "nil"), None);
// The box holds what the renderer draws for the text at the origin, control codes included.
lisp(&mut s, "(entmake '((0 . \"TEXT\") (10 0.0 0.0 0.0) (40 . 2.5) (51 . 0.3) (1 . \"%%uAgy%%d jQ\")))");
let drawn = textbox(&mut s, "(entget (entlast))").unwrap();
let list = cadcraft_engine::render::build(s.doc().unwrap(), &Space::Model, &Default::default());
let ink: Vec<_> = list.verts.iter().chain(&list.tris).collect();
assert!(!ink.is_empty());
let tol = 1e-6 * 2.5;
for p in ink {
assert!(p.x >= drawn[0] - tol && p.x <= drawn[2] + tol && p.y >= drawn[1] - tol && p.y <= drawn[3] + tol, "{p:?} outside {drawn:?}");
}
// Insertion point and rotation are not applied.
lisp(&mut s, "(entmake '((0 . \"TEXT\") (10 100.0 50.0 0.0) (40 . 2.5) (50 . 0.7) (51 . 0.3) (1 . \"%%uAgy%%d jQ\")))");
let moved = textbox(&mut s, "(entget (entlast))").unwrap();
for i in 0..4 {
assert!((moved[i] - drawn[i]).abs() <= tol, "{moved:?} {drawn:?}");
}
}
+7
View File
@@ -45,6 +45,7 @@ mod dash_block;
mod dash_units;
mod data_extraction;
mod dim_baseline_spacing;
mod dim_block_text_layer_pick;
mod dim_chain;
mod dim_commands;
mod dim_explode_text;
@@ -103,8 +104,11 @@ mod layout_prompts;
mod leader_command;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod leader_text_scale;
mod lisp_answer_by_frames;
mod lisp_corpus;
mod lisp_findfile;
mod lisp_getangle_inputs;
mod lisp_textbox;
mod lisp_undo_in_routine;
mod malformed_handles;
mod matchprop;
@@ -158,6 +162,7 @@ mod qdim_modes;
mod qleader;
mod query_entities;
mod quickcalc;
mod rays_xlines_trim_fillet;
mod recent_commands;
mod rectang_ortho;
mod rectang_polygon_order;
@@ -185,6 +190,7 @@ mod snap_intersections_aperture;
mod snap_nearest;
mod snap_overrides;
mod snap_tracking;
mod snap_z;
mod snaps_more;
mod solid_command;
mod space_is_enter;
@@ -215,6 +221,7 @@ mod viewport_frozen_selection;
mod viewport_ucs_copy;
mod vplayer_prompts;
mod vports;
mod window_rotated_text;
mod wipeout_grips;
mod xclip;
mod xdata_api;
+32
View File
@@ -136,3 +136,35 @@ fn matchprop_skips_locked_layers() {
assert_eq!(r["changed"], 0);
assert_eq!(props(&s, a).0, "L");
}
/// MATCHPROP between leaders copies the source's dimension style and its own style overrides
/// (the leader's DSTYLE data), as it does between dimensions (#3721).
#[test]
fn matchprop_copies_a_leaders_style_overrides() {
use cadcraft_engine::doc::{Common, Leader, Space};
use cadcraft_engine::geom::Vec3;
let leader = |y: f64, overrides: serde_json::Value| {
EntityKind::Leader(Leader {
vertices: vec![Vec3::new(0.0, y, 0.0), Vec3::new(10.0, y, 0.0)],
arrow: true,
spline: false,
style: "Standard".into(),
overrides: overrides.as_object().cloned().unwrap_or_default(),
})
};
let overrides_of = |s: &Session, h: Handle| match &s.doc().unwrap().entity(h).unwrap().kind {
EntityKind::Leader(l) => l.overrides.clone(),
_ => panic!("a leader"),
};
let mut s = Session::new();
let d = s.doc_mut().unwrap();
d.add(&Space::Model, Common::default(), leader(0.0, json!({ "arrowSize": 1.5, "leaderArrowBlock": "_ArchTick" }))).unwrap();
d.add(&Space::Model, Common::default(), leader(5.0, json!({}))).unwrap();
let handles: Vec<Handle> = s.doc().unwrap().model.iter().map(|e| e.handle).collect();
let (src, dst) = (handles[0], handles[1]);
assert_ne!(overrides_of(&s, dst), overrides_of(&s, src));
let r = s.execute("matchprop", &json!({ "source": src.hex(), "targets": [dst.hex()] })).unwrap();
assert_eq!(r["changed"], 1);
assert_eq!(overrides_of(&s, dst), overrides_of(&s, src));
assert!(!overrides_of(&s, dst).is_empty());
}
@@ -104,6 +104,32 @@ fn distance_uses_model_units_for_two_snaps_in_the_same_viewport() {
assert_eq!(s.state().unwrap().is_dirty(), before, "inquiry must not edit the drawing");
}
/// The `Distance` line DIST printed.
fn distance_line(s: &Session) -> Option<&String> {
s.log.iter().find(|l| l.starts_with("Distance = "))
}
/// A point an expression typed at the prompt worked out over frames (#3666) is a typed point: a
/// snapped click that comes while the frames work it out does not lend it its viewport origin.
#[test]
fn a_snapped_click_does_not_lend_its_origin_to_a_pending_expressions_point() {
let expression = super::lisp_answer_by_frames::slow("(list 95 50)");
let measure = |frames: bool| {
let (d, _) = drawing();
let mut s = session(d);
s.lisp_by_frames(frames);
s.start("dist").unwrap();
s.cmdline(&expression).unwrap();
assert_eq!(s.lisp_busy(), frames, "the expression waits for the next frame");
s.input_snapped(pick(&s, Vec2::new(100.0, 50.0), mode::INT)).unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
distance_line(&s).cloned().expect("DIST measured")
};
let at_once = measure(false);
assert!(at_once.starts_with("Distance = 5.0000,"), "paper units from the typed point: {at_once}");
assert_eq!(measure(true), at_once);
}
#[test]
fn typed_and_programmatic_points_are_measured_in_paper_units() {
let (d, _) = drawing();
@@ -0,0 +1,245 @@
//! TRIM, FILLET and CHAMFER on rays and xlines (#1235): what is left of a ray with a finite end
//! is a line, what is left of an xline is a ray, as in AutoCAD. EXTEND moves a ray's base (#1236).
use cadcraft_engine::Session;
use cadcraft_engine::doc::EntityKind;
fn r(v: f64) -> f64 {
(v * 1e6).round() / 1e6 + 0.0
}
/// Every object as text, sorted: lines with their ends in a fixed order, rays and xlines with
/// base and direction.
fn objects(s: &Session) -> Vec<String> {
let mut v: Vec<String> = s
.doc()
.unwrap()
.model
.iter()
.map(|e| match &e.kind {
EntityKind::Line(l) => {
let (a, b) = ((r(l.a.x), r(l.a.y)), (r(l.b.x), r(l.b.y)));
let (a, b) = if a <= b { (a, b) } else { (b, a) };
format!("LINE {a:?} {b:?}")
}
EntityKind::Ray(k) => format!("RAY {:?} {:?}", (r(k.base.x), r(k.base.y)), (r(k.dir.x), r(k.dir.y))),
EntityKind::XLine(k) => format!("XLINE {:?} {:?}", (r(k.base.x), r(k.base.y)), (r(k.dir.x), r(k.dir.y))),
EntityKind::Arc(_) => "ARC".to_string(),
k => format!("{k:?}"),
})
.collect();
v.sort();
v
}
/// A vertical line at x = 10 and, along y = 0, the ray or xline drawn by `cmd`.
fn session(cmd: &str) -> Session {
let mut s = Session::new();
s.cmdline("LINE 10,-2 10,12").unwrap();
s.cmdline("").unwrap();
s.script(&format!("{cmd}\n\n")).unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
s
}
fn run(cmd: &str, then: &str) -> Vec<String> {
let mut s = session(cmd);
s.script(then).unwrap();
assert!(s.running.is_none(), "{cmd} / {then}: {}", s.prompt_text());
objects(&s)
}
const EDGE: &str = "LINE (10.0, -2.0) (10.0, 12.0)";
/// The expected objects, sorted as `objects` sorts them.
fn want(v: &[&str]) -> Vec<String> {
let mut v: Vec<String> = v.iter().map(|s| s.to_string()).collect();
v.sort();
v
}
#[test]
fn trim_a_ray_leaves_a_line_or_a_ray() {
// The far side goes: the ray keeps its base and becomes a line.
assert_eq!(run("RAY 0,0 1,0", "TRIM 15,0\n\n"), want(&[EDGE, "LINE (0.0, 0.0) (10.0, 0.0)"]));
// The side with the base goes: what is left is still infinite, a ray from the edge.
assert_eq!(run("RAY 0,0 1,0", "TRIM 5,0\n\n"), want(&[EDGE, "RAY (10.0, 0.0) (1.0, 0.0)"]));
}
#[test]
fn trim_an_xline_leaves_a_ray() {
assert_eq!(run("XLINE H 0,0", "TRIM 15,0\n\n"), want(&[EDGE, "RAY (10.0, 0.0) (-1.0, 0.0)"]));
assert_eq!(run("XLINE H 0,0", "TRIM 5,0\n\n"), want(&[EDGE, "RAY (10.0, 0.0) (1.0, 0.0)"]));
}
#[test]
fn trim_between_two_edges_splits_a_ray_and_an_xline() {
let mut s = session("RAY -5,0 1,0");
s.cmdline("LINE 0,-2 0,12").unwrap();
s.cmdline("").unwrap();
s.script("TRIM 5,0\n\n").unwrap();
let edges = ["LINE (0.0, -2.0) (0.0, 12.0)", EDGE];
assert_eq!(objects(&s), want(&[&edges[..], &["LINE (-5.0, 0.0) (0.0, 0.0)", "RAY (10.0, 0.0) (1.0, 0.0)"]].concat()));
let mut s = session("XLINE H 0,0");
s.cmdline("LINE 0,-2 0,12").unwrap();
s.cmdline("").unwrap();
s.script("TRIM 5,0\n\n").unwrap();
assert_eq!(objects(&s), want(&[&edges[..], &["RAY (0.0, 0.0) (-1.0, 0.0)", "RAY (10.0, 0.0) (1.0, 0.0)"]].concat()));
}
#[test]
fn fillet_a_ray_or_an_xline_with_a_line() {
let corner = "LINE (10.0, 0.0) (10.0, 12.0)";
// The ray's base side kept: it becomes a line to the corner.
assert_eq!(run("RAY 0,0 1,0", "FILLET R 0 5,0 10,5\n"), want(&["LINE (0.0, 0.0) (10.0, 0.0)", corner]));
// Its infinite side kept: a ray from the corner.
assert_eq!(run("RAY 0,0 1,0", "FILLET R 0 15,0 10,5\n"), want(&["RAY (10.0, 0.0) (1.0, 0.0)", corner]));
// An xline becomes a ray running to the picked side, from the arc's tangent point.
assert_eq!(run("XLINE H 0,0", "FILLET R 1 5,0 10,5\n"), want(&["ARC", "LINE (10.0, 1.0) (10.0, 12.0)", "RAY (9.0, 0.0) (-1.0, 0.0)"]));
// Two xlines: two rays.
let mut s = Session::new();
s.script("XLINE H 0,0\n\nXLINE V 10,0\n\nFILLET R 0 5,0 10,5\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(objects(&s), want(&["RAY (10.0, 0.0) (-1.0, 0.0)", "RAY (10.0, 0.0) (0.0, 1.0)"]));
}
#[test]
fn chamfer_a_ray_and_an_xline() {
assert_eq!(
run("RAY 0,0 1,0", "CHAMFER D 2 2 15,0 10,5\n"),
want(&["LINE (10.0, 2.0) (10.0, 12.0)", "LINE (10.0, 2.0) (12.0, 0.0)", "RAY (12.0, 0.0) (1.0, 0.0)"])
);
assert_eq!(
run("XLINE H 0,0", "CHAMFER D 2 2 5,0 10,5\n"),
want(&["LINE (10.0, 2.0) (10.0, 12.0)", "LINE (8.0, 0.0) (10.0, 2.0)", "RAY (8.0, 0.0) (-1.0, 0.0)"])
);
}
#[test]
fn extend_a_ray_moves_its_base_back_to_the_edge() {
assert_eq!(run("RAY 15,0 16,0", "EXTEND 16,0\n\n"), want(&[EDGE, "RAY (10.0, 0.0) (1.0, 0.0)"]));
// The edge lies ahead of the base, not behind it: the ray is left alone.
let mut s = session("RAY 5,0 6,0");
s.script("EXTEND 6,0\n\n").unwrap();
assert_eq!(objects(&s), want(&[EDGE, "RAY (5.0, 0.0) (1.0, 0.0)"]));
}
/// An xline at 30 degrees through the origin and vertical lines at x = 123.456 and 200: values
/// that are not binary fractions, so a cut point computed from far away shows its error.
fn slanted(more: &str) -> Session {
let mut s = Session::new();
s.script(&format!("XLINE A 30 0,0\n\nLINE 123.456,-10 123.456,300\n\n{more}")).unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
s
}
/// The point of the 30 degree xline at `x`, as command-line text.
fn on_slant(x: f64) -> String {
format!("{x},{}", x * 30f64.to_radians().tan())
}
fn ray_base_x(s: &Session) -> f64 {
let rays: Vec<f64> = s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Ray(k) = &e.kind { Some(k.base.x) } else { None }).collect();
assert_eq!(rays.len(), 1, "{:?}", objects(s));
rays[0]
}
#[test]
fn an_xline_cut_keeps_the_cut_point_exact() {
let mut s = slanted("");
s.script(&format!("TRIM {}\n\n", on_slant(100.0))).unwrap();
assert!((ray_base_x(&s) - 123.456).abs() < 1e-10, "{}", ray_base_x(&s) - 123.456);
let mut s = slanted("");
s.script(&format!("FILLET R 0 {} 123.456,0\n", on_slant(200.0))).unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert!((ray_base_x(&s) - 123.456).abs() < 1e-10, "{}", ray_base_x(&s) - 123.456);
}
#[test]
fn a_ray_left_by_trim_does_not_see_its_own_edge_as_a_cut() {
// The ray left by the first TRIM starts on the edge: the second TRIM must cut only at x = 200,
// not also leave a sliver between the ray's base and the edge it was trimmed to.
let mut s = slanted("LINE 200,-10 200,300\n\n");
s.script(&format!("TRIM {}\n\nTRIM {}\n\n", on_slant(100.0), on_slant(160.0))).unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(objects(&s).len(), 3, "{:?}", objects(&s));
}
#[test]
fn preselected_xline_is_the_cutting_edge_in_both_modes() {
use cadcraft_engine::Input;
use serde_json::json;
for mode in [0, 1] {
let mut s = Session::new();
let edge = s.execute("xline", &json!({"base":[10,0], "through":[10,1]})).unwrap()["handle"].as_str().unwrap().to_owned();
let target = s.execute("xline", &json!({"base":[0,0], "through":[1,0]})).unwrap()["handle"].as_str().unwrap().to_owned();
// This unselected edge must not cut the target.
s.execute("xline", &json!({"base":[20,0], "through":[20,1]})).unwrap();
let edge = cadcraft_engine::doc::Handle::parse_hex(&edge).unwrap();
let target = cadcraft_engine::doc::Handle::parse_hex(&target).unwrap();
s.doc_mut().unwrap().header.set_i64("TRIMEXTENDMODE", mode);
s.set_selection(vec![edge]);
s.start("trim").unwrap();
assert!(s.prompt_text().contains("Select object to trim"), "{}", s.prompt_text());
s.input(Input::Point(cadcraft_engine::geom::Vec2::new(15.0, 0.0))).unwrap();
let d = s.doc().unwrap();
assert!(matches!(d.entity(edge).unwrap().kind, EntityKind::XLine(_)));
let EntityKind::Ray(ray) = &d.entity(target).unwrap().kind else { panic!("trim must preserve the target handle and leave a ray") };
assert!((ray.base.x - 10.0).abs() < 1e-9 && ray.dir.x < 0.0);
s.input(Input::Keyword("Undo".into())).unwrap();
assert!(matches!(s.doc().unwrap().entity(target).unwrap().kind, EntityKind::XLine(_)));
s.input(Input::Enter).unwrap();
assert!(s.running.is_none());
}
}
#[test]
fn ray_cutting_edge_does_not_cut_behind_its_base() {
use serde_json::json;
let mut s = Session::new();
let edge = s.execute("ray", &json!({"base":[10,5],"through":[10,6]})).unwrap()["handle"].clone();
let target = s.execute("line", &json!({"points":[[0,0],[20,0]]})).unwrap()["handles"][0].clone();
let error = s.execute("trim", &json!({"handle":target,"pick":[15,0],"edges":[edge]})).unwrap_err();
assert!(error.to_string().contains("No usable cutting-edge intersection"), "{error}");
let target = s.execute("line", &json!({"points":[[0,10],[20,10]]})).unwrap()["handles"][0].clone();
s.execute("trim", &json!({"handle":target,"pick":[15,10],"edges":[edge]})).unwrap();
assert_eq!(s.doc().unwrap().model.len(), 3);
}
#[test]
fn picking_the_cut_leaves_the_xline_unchanged() {
use serde_json::json;
let mut s = Session::new();
s.execute("line", &json!({"points":[[10,-10],[10,10]]})).unwrap();
let target = s.execute("xline", &json!({"base":[0,0],"through":[1,0]})).unwrap()["handle"].clone();
assert!(s.execute("trim", &json!({"handle":target,"pick":[10,0],"mode":"quick"})).is_err());
let h = cadcraft_engine::doc::Handle::parse_hex(target.as_str().unwrap()).unwrap();
assert!(matches!(s.doc().unwrap().entity(h).unwrap().kind, EntityKind::XLine(_)));
}
#[test]
fn pickfirst_off_asks_for_edges_in_standard_mode() {
let mut s = session("XLINE H 0,0");
let h = s.doc().unwrap().model.iter().next().unwrap().handle;
s.settings.pickfirst = false;
s.doc_mut().unwrap().header.set_i64("TRIMEXTENDMODE", 0);
s.set_selection(vec![h]);
s.start("trim").unwrap();
assert!(s.prompt_text().contains("Select objects"));
assert!(s.selection().is_empty());
}
#[test]
fn fillet_and_chamfer_no_trim_preserve_unbounded_sources() {
use serde_json::json;
for command in ["fillet", "chamfer"] {
let mut s = Session::new();
let h1 = s.execute("xline", &json!({"base":[0,0],"through":[1,0]})).unwrap()["handle"].clone();
let h2 = s.execute("ray", &json!({"base":[10,0],"through":[10,1]})).unwrap()["handle"].clone();
let before = objects(&s);
s.execute(command, &json!({"h1":h1,"h2":h2,"p1":[5,0],"p2":[10,5],"radius":1,"d1":1,"d2":1,"trim":false})).unwrap();
let after = objects(&s);
assert!(before.iter().all(|object| after.contains(object)));
assert_eq!(after.len(), before.len() + 1);
}
}
+268
View File
@@ -0,0 +1,268 @@
//! An object snap gives the point the Z of what it snapped to, as in AutoCAD (OSNAPZ 0): a line
//! drawn between a survey point and a contour runs from the point's level to the contour's
//! elevation instead of lying at z = 0. OSNAPZ 1 uses the current elevation; an unsnapped pick
//! stays at z = 0. LINE and POINT keep the Z of typed points too.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{EntityKind, LwPolyline, Point, Space};
use cadcraft_engine::geom::{PolyVertex, Vec2, Vec3};
use cadcraft_engine::snap::{self, mode};
fn survey(s: &mut Session) {
s.add_entity(EntityKind::Point(Point { p: Vec3::new(0.0, 0.0, 1880.0), angle: 0.0 })).unwrap();
s.add_entity(EntityKind::LwPolyline(LwPolyline {
vertices: vec![PolyVertex::new(Vec2::new(10.0, 0.0)), PolyVertex::new(Vec2::new(10.0, 10.0))],
closed: false,
const_width: 0.0,
elevation: 1881.0,
plinegen: false,
}))
.unwrap();
s.cmdline("zoom e").ok();
}
/// Click at `at` with the object snaps in `osmode`, as the canvas does.
fn click(s: &mut Session, at: Vec2, osmode: u32) {
let ap = s.pixel_size() * 20.0;
let hit = snap::osnap(s.doc().unwrap(), &Space::Model, at, ap, osmode, None, false).expect("a snap");
s.input_snapped(hit).unwrap();
}
fn lines(s: &Session) -> Vec<(Vec3, Vec3)> {
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a, l.b)) } else { None }).collect()
}
#[test]
fn a_line_snapped_to_a_survey_point_and_a_contour_keeps_their_levels() {
let mut s = Session::new();
survey(&mut s);
s.cmdline("line").unwrap();
click(&mut s, Vec2::new(0.01, 0.0), mode::NOD);
click(&mut s, Vec2::new(10.0, 0.01), mode::END);
s.input(cadcraft_engine::Input::Enter).unwrap();
assert_eq!(lines(&s), vec![(Vec3::new(0.0, 0.0, 1880.0), Vec3::new(10.0, 0.0, 1881.0))]);
}
#[test]
fn osnapz_on_uses_the_current_elevation_and_a_plain_pick_stays_flat() {
let mut s = Session::new();
survey(&mut s);
s.execute("setvar", &serde_json::json!({ "name": "OSNAPZ", "value": 1 })).unwrap();
s.doc_mut().unwrap().header.set_f64("ELEVATION", 5.0);
s.cmdline("line").unwrap();
click(&mut s, Vec2::new(0.01, 0.0), mode::NOD);
s.input(cadcraft_engine::Input::Point(Vec2::new(20.0, 20.0))).unwrap();
s.input(cadcraft_engine::Input::Enter).unwrap();
assert_eq!(lines(&s), vec![(Vec3::new(0.0, 0.0, 5.0), Vec3::new(20.0, 20.0, 0.0))]);
assert_eq!(s.execute("getvar", &serde_json::json!({ "name": "OSNAPZ" })).unwrap()["value"], 1);
}
#[test]
fn point_takes_a_snapped_z_and_line_a_typed_one() {
let mut s = Session::new();
survey(&mut s);
s.cmdline("point").unwrap();
click(&mut s, Vec2::new(10.0, 10.01), mode::END);
let pts: Vec<Vec3> = s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Point(p) = &e.kind { Some(p.p) } else { None }).collect();
assert!(pts.contains(&Vec3::new(10.0, 10.0, 1881.0)), "{pts:?}");
s.cmdline("line").unwrap();
s.cmdline("100,100,3").unwrap();
s.cmdline("@10,0,2").unwrap();
s.cmdline("").unwrap();
assert!(lines(&s).contains(&(Vec3::new(100.0, 100.0, 3.0), Vec3::new(110.0, 100.0, 5.0))), "{:?}", lines(&s));
}
/// M2P between two snapped points is midway in Z too: halfway between a survey point's level
/// and a contour's elevation.
#[test]
fn m2p_between_two_snapped_points_is_midway_in_z() {
let mut s = Session::new();
survey(&mut s);
s.cmdline("point").unwrap();
s.cmdline("m2p").unwrap();
click(&mut s, Vec2::new(0.01, 0.0), mode::NOD);
click(&mut s, Vec2::new(10.0, 0.01), mode::END);
let pts: Vec<Vec3> = s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Point(p) = &e.kind { Some(p.p) } else { None }).collect();
assert!(pts.contains(&Vec3::new(5.0, 0.0, 1880.5)), "{pts:?}");
}
/// A one-off snap typed for an M2P point gives that point the Z of what it snapped to, and
/// the next plain point is back at z = 0.
#[test]
fn m2p_with_a_typed_snap_for_each_point_takes_their_levels() {
let mut s = Session::new();
survey(&mut s);
s.cmdline("point").unwrap();
s.cmdline("m2p").unwrap();
s.cmdline("nod").unwrap();
s.input(cadcraft_engine::Input::Point(Vec2::new(0.01, 0.0))).unwrap();
s.cmdline("end").unwrap();
s.input(cadcraft_engine::Input::Point(Vec2::new(10.0, 0.01))).unwrap();
s.cmdline("point").unwrap();
s.input(cadcraft_engine::Input::Point(Vec2::new(50.0, 50.0))).unwrap();
let pts: Vec<Vec3> = s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Point(p) = &e.kind { Some(p.p) } else { None }).collect();
assert!(pts.contains(&Vec3::new(5.0, 0.0, 1880.5)), "{pts:?}");
assert!(pts.contains(&Vec3::new(50.0, 50.0, 0.0)), "{pts:?}");
}
/// A point a LISP expression gives at a point prompt keeps its Z, as a typed `x,y,z` does.
#[test]
fn a_lisp_point_keeps_its_z() {
let mut s = Session::new();
s.cmdline("line").unwrap();
s.cmdline("(list 1 2 7)").unwrap();
s.cmdline("(list 5 2)").unwrap();
s.cmdline("").unwrap();
assert!(lines(&s).contains(&(Vec3::new(1.0, 2.0, 7.0), Vec3::new(5.0, 2.0, 0.0))), "{:?}", lines(&s));
}
/// A LINE started with a deferred tangent keeps the Z typed for its next point, and the
/// segment after it starts there.
#[test]
fn a_deferred_tangent_start_keeps_the_next_points_z() {
let mut s = Session::new();
s.cmdline("circle 0,0 2").unwrap();
s.cmdline("zoom e").ok();
s.cmdline("line").unwrap();
s.cmdline("tan").unwrap();
s.input(cadcraft_engine::Input::Point(Vec2::new(-1.4, 1.4))).unwrap();
s.cmdline("10,10,5").unwrap();
s.cmdline("20,10,1").unwrap();
s.cmdline("").unwrap();
let ls = lines(&s);
assert_eq!(ls.len(), 2, "{ls:?}");
assert_eq!(ls[0].0.z, 0.0, "{ls:?}");
assert_eq!(ls[0].1, Vec3::new(10.0, 10.0, 5.0), "{ls:?}");
assert_eq!(ls[1], (Vec3::new(10.0, 10.0, 5.0), Vec3::new(20.0, 10.0, 1.0)), "{ls:?}");
}
fn points(s: &Session) -> Vec<Vec3> {
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Point(p) = &e.kind { Some(p.p) } else { None }).collect()
}
/// A center snap takes the circle's Z, though no object passes under the cursor there.
#[test]
fn a_center_snap_takes_the_circles_z() {
let mut s = Session::new();
s.add_entity(EntityKind::Circle(cadcraft_engine::doc::Circle { center: Vec3::new(0.0, 0.0, 5.0), radius: 10.0 })).unwrap();
s.cmdline("zoom e").ok();
s.cmdline("point").unwrap();
click(&mut s, Vec2::new(0.01, 0.01), mode::CEN);
assert_eq!(points(&s), vec![Vec3::new(0.0, 0.0, 5.0)]);
}
/// An intersection of two objects at different levels takes the Z of the first one drawn,
/// whichever is on top.
#[test]
fn an_intersection_takes_the_z_of_the_first_object() {
let mut s = Session::new();
s.add_entity(EntityKind::Line(cadcraft_engine::doc::Line { a: Vec3::new(-5.0, 0.0, 0.0), b: Vec3::new(5.0, 0.0, 0.0) })).unwrap();
s.add_entity(EntityKind::Line(cadcraft_engine::doc::Line { a: Vec3::new(0.0, -5.0, 3.0), b: Vec3::new(0.0, 5.0, 3.0) })).unwrap();
s.cmdline("zoom e").ok();
s.cmdline("point").unwrap();
click(&mut s, Vec2::new(0.01, 0.01), mode::INT);
assert_eq!(points(&s), vec![Vec3::new(0.0, 0.0, 0.0)]);
}
/// A reference to `block` at `at`, scaled by `z_scale` in Z only.
fn reference(block: &str, at: Vec3, z_scale: f64) -> EntityKind {
EntityKind::Insert(cadcraft_engine::doc::Insert {
block: block.into(),
insert: at,
scale: Vec3::new(1.0, 1.0, z_scale),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
})
}
/// Block B: a line rising from (0,0,0) to (10,0,10) and a point at (5,5,5). Block C: B placed
/// 3 units up.
fn blocks(s: &mut Session) {
let d = s.doc_mut().unwrap();
let mut b = cadcraft_engine::doc::Block::new("B");
let line = cadcraft_engine::doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 10.0) };
b.entities.push(cadcraft_engine::doc::Entity::new(d.new_handle(), EntityKind::Line(line)));
b.entities.push(cadcraft_engine::doc::Entity::new(d.new_handle(), EntityKind::Point(Point { p: Vec3::new(5.0, 5.0, 5.0), angle: 0.0 })));
d.blocks.insert("B".into(), std::sync::Arc::new(b));
let mut c = cadcraft_engine::doc::Block::new("C");
c.entities.push(cadcraft_engine::doc::Entity::new(d.new_handle(), reference("B", Vec3::new(0.0, 0.0, 3.0), 1.0)));
d.blocks.insert("C".into(), std::sync::Arc::new(c));
}
/// A snap on an object inside a block reference takes that object's Z, placed by the
/// reference (its insertion Z and Z scale), through nested references too.
#[test]
fn a_snap_inside_a_block_takes_the_z_of_the_object_there() {
let mut s = Session::new();
blocks(&mut s);
s.add_entity(reference("B", Vec3::new(100.0, 0.0, 2.0), 2.0)).unwrap();
s.add_entity(reference("C", Vec3::new(300.0, 0.0, 1.0), 1.0)).unwrap();
s.cmdline("zoom e").ok();
s.cmdline("point").unwrap();
click(&mut s, Vec2::new(110.01, 0.01), mode::END);
s.cmdline("point").unwrap();
click(&mut s, Vec2::new(105.01, 5.01), mode::NOD);
s.cmdline("point").unwrap();
click(&mut s, Vec2::new(310.01, 0.01), mode::END);
assert_eq!(points(&s), vec![Vec3::new(110.0, 0.0, 22.0), Vec3::new(105.0, 5.0, 12.0), Vec3::new(310.0, 0.0, 14.0)]);
}
/// Center and quadrant snaps on an ellipse take its Z.
#[test]
fn ellipse_snaps_take_the_ellipses_z() {
let mut s = Session::new();
let e = cadcraft_engine::doc::Ellipse {
center: Vec3::new(300.0, 0.0, 3.0),
major: Vec3::new(10.0, 0.0, 0.0),
ratio: 0.5,
start: 0.0,
end: std::f64::consts::TAU,
};
s.add_entity(EntityKind::Ellipse(e)).unwrap();
s.cmdline("zoom e").ok();
s.cmdline("point").unwrap();
click(&mut s, Vec2::new(300.01, 0.01), mode::CEN);
s.cmdline("point").unwrap();
click(&mut s, Vec2::new(310.01, 0.01), mode::QUA);
assert_eq!(points(&s), vec![Vec3::new(300.0, 0.0, 3.0), Vec3::new(310.0, 0.0, 3.0)]);
}
#[test]
fn closing_a_line_preserves_its_first_and_last_z() {
let mut s = Session::new();
survey(&mut s);
s.cmdline("line").unwrap();
click(&mut s, Vec2::new(0.01, 0.0), mode::NOD);
click(&mut s, Vec2::new(10.0, 0.01), mode::END);
s.cmdline("20,10,1885").unwrap();
s.cmdline("close").unwrap();
let a = Vec3::new(0.0, 0.0, 1880.0);
let b = Vec3::new(10.0, 0.0, 1881.0);
let c = Vec3::new(20.0, 10.0, 1885.0);
assert_eq!(lines(&s), vec![(a, b), (b, c), (c, a)]);
}
#[test]
fn undoing_a_line_segment_restores_the_previous_points_z() {
let mut s = Session::new();
survey(&mut s);
s.cmdline("line").unwrap();
click(&mut s, Vec2::new(0.01, 0.0), mode::NOD);
click(&mut s, Vec2::new(10.0, 0.01), mode::END);
s.cmdline("20,10,1885").unwrap();
s.cmdline("undo").unwrap();
let a = Vec3::new(0.0, 0.0, 1880.0);
let b = Vec3::new(10.0, 0.0, 1881.0);
assert_eq!(lines(&s), vec![(a, b)]);
s.cmdline("20,20,1889").unwrap();
s.input(cadcraft_engine::Input::Enter).unwrap();
assert_eq!(lines(&s), vec![(a, b), (b, Vec3::new(20.0, 20.0, 1889.0))]);
}
+42
View File
@@ -366,3 +366,45 @@ fn a_short_piece_far_from_the_origin_is_highlighted_and_removed_as_near_it() {
assert!((before - drawn(&s) - 0.5).abs() < 1e-3, "at {x0}: the click removes the same 0.5");
}
}
#[test]
fn a_script_extend_ignores_shift_and_extends() {
// A script's EXTEND step must ignore the live Shift key: with Shift held it still extends.
let mut s = Session::new();
line(&mut s, [4.0, -5.0], [4.0, 5.0]);
line(&mut s, [10.0, -5.0], [10.0, 5.0]);
let l = line(&mut s, [0.0, 0.0], [8.0, 0.0]);
s.zoom_extents().unwrap();
s.shift_down = true;
s.script("_.extend\n6,0\n\n").unwrap();
let EntityKind::Line(x) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!() };
assert_eq!((x.b.x, x.b.y), (10.0, 0.0), "a scripted extend ignores Shift and extends");
}
#[test]
fn a_script_trim_ignores_shift_and_trims() {
// A script's TRIM step must ignore the live Shift key: with Shift held it still trims.
let mut s = Session::new();
line(&mut s, [4.0, -5.0], [4.0, 5.0]);
line(&mut s, [10.0, -5.0], [10.0, 5.0]);
let l = line(&mut s, [0.0, 0.0], [8.0, 0.0]);
s.zoom_extents().unwrap();
s.shift_down = true;
s.script("_.trim\n6,0\n\n").unwrap();
let EntityKind::Line(x) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!() };
assert_eq!((x.b.x, x.b.y), (4.0, 0.0), "a scripted trim ignores Shift and trims");
}
#[test]
fn a_lisp_extend_ignores_shift_and_extends() {
// A LISP `(command …)` EXTEND must ignore the live Shift key: with Shift held it still extends.
let mut s = Session::new();
line(&mut s, [4.0, -5.0], [4.0, 5.0]);
line(&mut s, [10.0, -5.0], [10.0, 5.0]);
let l = line(&mut s, [0.0, 0.0], [8.0, 0.0]);
s.zoom_extents().unwrap();
s.shift_down = true;
s.cmdline("(command \"_.extend\" '(6.0 0.0) \"\")").unwrap();
let EntityKind::Line(x) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!() };
assert_eq!((x.b.x, x.b.y), (10.0, 0.0), "a LISP extend ignores Shift and extends");
}
@@ -0,0 +1,400 @@
//! A window selects a TEXT, ATTDEF or MTEXT when it holds what the text draws, turned with the
//! text or not (#3731). The document's box for text is an estimate from its number of characters
//! (and lines), which reaches past what the fonts draw on the side a justification or attachment
//! leaves open. A window that held all of a text tested that box, so it could miss the text. A
//! crossing window still selects the text by touching its box, as before.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Common, Entity, EntityKind, HAlign, MText, RawTag, Space, Text, VAlign, entity_bounds};
use cadcraft_engine::geom::{Bounds2, Vec2, Vec3};
use serde_json::{Value, json};
/// Rotations the tests turn the text by, in degrees: none, a right angle and an oblique angle.
const ROTATIONS: [f64; 3] = [0.0, 90.0, 30.0];
/// Justifications: left (baseline), centre, right and middle-centre.
const JUSTIFY: [&str; 4] = ["L", "C", "R", "MC"];
/// The points of what the renderer draws for `e` in model space (none when it draws nothing).
fn drawn_points(s: &Session, e: &Entity) -> Vec<Vec2> {
let list = cadcraft_engine::render::build(s.doc().unwrap(), &Space::Model, &Default::default());
list.prims.iter().filter(|p| p.handle == e.handle).flat_map(|p| list.points(p).to_vec()).collect()
}
/// The points of what the renderer draws for `e`, which draws something.
fn drawn(s: &Session, e: &Entity) -> Vec<Vec2> {
let pts = drawn_points(s, e);
assert!(!pts.is_empty(), "the text draws strokes");
pts
}
/// The last entity added, and the box of what it draws. The document's box for it must reach
/// past that box, or the case would not tell the two apart.
fn last_text(s: &Session) -> (Entity, Bounds2) {
let e = s.doc().unwrap().model.last().unwrap().as_ref().clone();
let ink = Bounds2::from_points(drawn(s, &e));
let estimate = entity_bounds(s.doc().unwrap(), &e, 0);
assert!(!ink.contains_box(&estimate), "the estimated box {estimate:?} reaches past the drawn text {ink:?}");
(e, ink)
}
/// A session holding one TEXT of narrow characters, which draw narrower than the estimate.
fn one_text(rotation: f64, justify: &str) -> (Session, Entity, Bounds2) {
let mut s = Session::new();
s.execute("text", &json!({"at": [3.0, 2.0], "text": "1.1", "height": 0.5, "rotation": rotation, "justify": justify})).unwrap();
let (e, ink) = last_text(&s);
(s, e, ink)
}
/// The handles the `entities` query (MCP `query_entities`) finds in window `w`.
fn query(s: &mut Session, w: Bounds2, crossing: bool) -> Vec<Value> {
let r = s.execute("entities", &json!({"window": [[w.min.x, w.min.y], [w.max.x, w.max.y]], "crossing": crossing})).unwrap();
r["entities"].as_array().unwrap().iter().map(|e| e["handle"].clone()).collect()
}
/// Whether a window dragged from `w.min` to `w.max` with no command running selects `e`.
fn dragged(s: &mut Session, w: Bounds2, e: &Entity) -> bool {
s.set_selection(Vec::new());
assert!(s.begin_window(w.min));
s.idle_click(w.max, false).unwrap();
s.state().unwrap().selection.contains(&e.handle)
}
/// Whether `input`, an ERASE ended by one more Enter, erases `e`; the erase is undone. A window
/// that finds nothing ends ERASE by itself, and that Enter then starts it again: it is cancelled.
fn erases(s: &mut Session, input: &str, e: &Entity) -> bool {
s.cmdline(input).unwrap();
s.cmdline("").unwrap();
if s.running.is_some() {
s.cancel();
}
assert!(s.running.is_none(), "{input}: the command ended");
let gone = s.doc().unwrap().entity(e.handle).is_none();
if gone {
s.undo().unwrap();
}
gone
}
/// Whether ERASE with the Window option from `w.min` to `w.max` erases `e`.
fn erased(s: &mut Session, w: Bounds2, e: &Entity) -> bool {
erases(s, &format!("ERASE W {},{} {},{}", w.min.x, w.min.y, w.max.x, w.max.y), e)
}
/// `w` with one side moved in by `by`: 0 left, 1 bottom, 2 right, 3 top.
fn nudged(w: Bounds2, side: usize, by: f64) -> Bounds2 {
let (mut min, mut max) = (w.min, w.max);
match side {
0 => min.x += by,
1 => min.y += by,
2 => max.x -= by,
_ => max.y -= by,
}
Bounds2::new(min, max)
}
#[test]
fn a_window_on_the_edges_of_a_turned_text_selects_it() {
for rotation in ROTATIONS {
for justify in JUSTIFY {
let (mut s, e, ink) = one_text(rotation, justify);
let case = format!("{rotation} degrees, {justify}");
let handle = json!(e.handle.hex());
assert_eq!(query(&mut s, ink, false), vec![handle.clone()], "query, {case}");
assert!(dragged(&mut s, ink, &e), "dragged window, {case}");
assert!(erased(&mut s, ink, &e), "ERASE W, {case}");
// A window that leaves out a sliver of the text on any side does not hold it.
for side in 0..4 {
let w = nudged(ink, side, 1e-3);
assert!(query(&mut s, w, false).is_empty(), "query, {case}, side {side}");
assert!(!dragged(&mut s, w, &e), "dragged window, {case}, side {side}");
assert!(!erased(&mut s, w, &e), "ERASE W, {case}, side {side}");
}
}
}
}
#[test]
fn a_crossing_window_still_selects_a_text_it_touches() {
for rotation in ROTATIONS {
for justify in JUSTIFY {
let (mut s, e, ink) = one_text(rotation, justify);
let handle = json!(e.handle.hex());
for w in [ink, nudged(ink, 0, 1e-3), nudged(ink, 1, 1e-3), nudged(ink, 2, 1e-3), nudged(ink, 3, 1e-3)] {
assert_eq!(query(&mut s, w, true), vec![handle.clone()], "{rotation} degrees, {justify}: {w:?}");
}
// One clear of the text's box selects nothing.
let b = entity_bounds(s.doc().unwrap(), &e, 0);
// Unturned, its box reaches right of the strokes; a crossing window there, touching
// the box and no stroke, still selects it, as before.
if rotation == 0.0 {
assert!(b.max.x > ink.max.x + 0.02, "{justify}: the box reaches right of the strokes");
let mid = (ink.min.y + ink.max.y) / 2.0;
let past = Bounds2::new(Vec2::new(ink.max.x + 0.01, mid), Vec2::new(b.max.x + 0.01, mid + 0.01));
assert_eq!(query(&mut s, past, true), vec![handle.clone()], "{justify}: crossing past the strokes");
}
let clear = Bounds2::new(Vec2::new(b.max.x + 0.1, b.min.y), Vec2::new(b.max.x + 1.0, b.max.y));
assert!(query(&mut s, clear, true).is_empty(), "{rotation} degrees, {justify}");
}
}
}
/// The reported case: three labels 0.09375 high, turned by a right angle, whose drawn text
/// starts at y = 11.277, inside the window (-1.25, 11.22)-(14.10, 21.60). Justified to their end,
/// they run up from there, and their estimated box hangs below the window's bottom edge (while
/// one down to y = 10.9 holds it).
#[test]
fn turned_labels_inside_a_window_are_selected() {
let mut s = Session::new();
let w = Bounds2::new(Vec2::new(-1.25, 11.22), Vec2::new(14.10, 21.60));
let lower = Bounds2::new(Vec2::new(-1.25, 10.9), Vec2::new(14.10, 21.60));
let mut labels = Vec::new();
for (x, value) in [(1.0, "1.1.1.1"), (5.0, "11.11.1"), (9.0, "1.11.11")] {
// Measure where the label draws, then place it so its drawn start is at y = 11.277.
let label = |s: &mut Session, y: f64| {
s.execute("text", &json!({"at": [x, y], "text": value, "height": 0.09375, "rotation": 90, "justify": "R"})).unwrap();
last_text(s)
};
let (probe, ink) = label(&mut s, 0.0);
s.execute("erase", &json!({"handles": [probe.handle.hex()]})).unwrap();
let (e, ink_at) = label(&mut s, 11.277 - ink.min.y);
let estimate = entity_bounds(s.doc().unwrap(), &e, 0);
assert!(w.contains_box(&ink_at), "{value} draws inside the window: {ink_at:?}");
assert!(!w.contains_box(&estimate) && lower.contains_box(&estimate), "{value}: the estimate {estimate:?} hangs below 11.22");
labels.push(e);
}
assert_eq!(query(&mut s, w, false).len(), 3);
s.script(&format!("ERASE W {},{} {},{}\n\n", w.min.x, w.min.y, w.max.x, w.max.y)).unwrap();
for e in &labels {
assert!(s.doc().unwrap().entity(e.handle).is_none(), "{e:?} erased");
}
}
/// The corners of the box of `pts` in the frame turned by `deg` about `o`, grown by `grow` on
/// each side but `side` (0 left, 1 bottom, 2 right, 3 top), which is pulled in by `grow` instead.
fn turned_box(pts: &[Vec2], o: Vec2, deg: f64, grow: f64, side: Option<usize>) -> [Vec2; 4] {
let r = deg.to_radians();
let local = Bounds2::from_points(pts.iter().map(|p| (*p - o).rotate(-r)));
let mut b = local.expand(grow);
if let Some(side) = side {
b = nudged(b, side, 2.0 * grow);
}
[b.min, Vec2::new(b.max.x, b.min.y), b.max, Vec2::new(b.min.x, b.max.y)].map(|c| o + c.rotate(r))
}
#[test]
fn a_window_polygon_turned_with_a_text_selects_it() {
for rotation in ROTATIONS {
for justify in JUSTIFY {
let (mut s, e, _) = one_text(rotation, justify);
let pts = drawn(&s, &e);
let o = Vec2::new(3.0, 2.0);
// The polygon ends with one Enter and the selection with the one `erases` gives.
let mut wp = |poly: [Vec2; 4]| {
let corners: Vec<String> = poly.iter().map(|p| format!("{},{}", p.x, p.y)).collect();
s.cmdline(&format!("ERASE WP {}", corners.join(" "))).unwrap();
erases(&mut s, "", &e)
};
let case = format!("{rotation} degrees, {justify}");
assert!(wp(turned_box(&pts, o, rotation, 1e-3, None)), "{case}");
for side in 0..4 {
assert!(!wp(turned_box(&pts, o, rotation, 1e-3, Some(side))), "{case}, side {side}");
}
}
}
}
#[test]
fn a_window_on_the_edges_of_an_attribute_definition_selects_it() {
for justify in ["L", "C", "R"] {
let mut s = Session::new();
s.execute("attdef", &json!({"tag": "I1", "at": [3.0, 2.0], "height": 0.5, "justify": justify})).unwrap();
let (e, ink) = last_text(&s);
assert_eq!(query(&mut s, ink, false), vec![json!(e.handle.hex())], "{justify}");
for side in 0..4 {
assert!(query(&mut s, nudged(ink, side, 1e-3), false).is_empty(), "{justify}, side {side}");
}
}
}
/// An annotative text draws at the current annotation scale, and not at all when that scale
/// hides it; a text that matches the layout's orientation draws upright whatever its rotation.
/// A window holds each as it draws.
#[test]
fn a_window_holds_annotative_and_upright_text_as_drawn() {
let held = |s: &mut Session, e: &Entity, ink: Bounds2, case: &str| {
assert_eq!(query(s, ink, false), vec![json!(e.handle.hex())], "{case}");
for side in 0..4 {
assert!(query(s, nudged(ink, side, 1e-3), false).is_empty(), "{case}, side {side}");
}
};
let mut s = Session::new();
s.execute("style", &json!({"name": "Notes", "annotative": true, "current": true})).unwrap();
s.execute("setvar", &json!({"name": "CANNOSCALE", "value": "1:50"})).unwrap();
s.execute("text", &json!({"at": [3.0, 2.0], "text": "1.1", "height": 0.5, "rotation": 30, "justify": "C"})).unwrap();
let (e, ink) = last_text(&s);
held(&mut s, &e, ink, "annotative at 1:50");
// At a scale the text doesn't support, with ANNOALLVISIBLE 0, it draws nothing.
s.execute("setvar", &json!({"name": "CANNOSCALE", "value": "1:20"})).unwrap();
s.execute("annovisible.current", &json!({})).unwrap();
let everything = Bounds2::new(Vec2::new(-1e3, -1e3), Vec2::new(1e3, 1e3));
assert!(query(&mut s, everything, false).is_empty(), "a hidden annotative text");
let mut s = Session::new();
let at = Vec3::new(3.0, 2.0, 0.0);
let text = Text {
insert: at,
align_pt: Some(at),
height: 0.5,
value: "1.1".into(),
rotation: std::f64::consts::FRAC_PI_2,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: HAlign::Center,
valign: VAlign::Baseline,
backwards: false,
upside_down: false,
};
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let common = Common { xdata: vec![tag(1001, "AcadAnnoPO"), tag(1070, "1")], ..Common::default() };
s.doc_mut().unwrap().add(&Space::Model, common.clone(), EntityKind::Text(text)).unwrap();
let (e, ink) = last_text(&s);
assert!(ink.width() > ink.height(), "drawn upright: {ink:?}");
held(&mut s, &e, ink, "upright");
let mut s = Session::new();
let note = MText {
insert: Vec3::new(3.0, 2.0, 0.0),
height: 0.5,
width: 0.0,
attach: 5,
rotation: std::f64::consts::FRAC_PI_2,
style: "Standard".into(),
contents: "1.1".into(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
};
s.doc_mut().unwrap().add(&Space::Model, common, EntityKind::MText(note)).unwrap();
let (e, ink) = last_text(&s);
assert!(ink.width() > ink.height(), "MTEXT drawn upright: {ink:?}");
held(&mut s, &e, ink, "upright MTEXT");
}
/// A TEXT of narrow characters at (3, 2), justified by `halign`/`valign`, added to `s`'s model.
fn add_text(s: &mut Session, value: &str, height: f64, rotation_deg: f64, halign: HAlign, valign: VAlign, edit: impl Fn(&mut Text)) {
let at = Vec3::new(3.0, 2.0, 0.0);
let mut t = Text {
insert: at,
align_pt: Some(at),
height,
value: value.into(),
rotation: rotation_deg.to_radians(),
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign,
valign,
backwards: false,
upside_down: false,
};
edit(&mut t);
s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap();
}
/// Mirrored text (backwards, upside down) and slanted text (an obliquing angle) are held by
/// what they draw too, turned or not.
#[test]
fn a_window_holds_mirrored_and_slanted_text_as_drawn() {
let variants: [(&str, fn(&mut Text)); 3] =
[("backwards", |t| t.backwards = true), ("upside down", |t| t.upside_down = true), ("slanted", |t| t.oblique = 20f64.to_radians())];
for (name, edit) in variants {
for rotation in ROTATIONS {
for (halign, valign) in [(HAlign::Left, VAlign::Baseline), (HAlign::Center, VAlign::Baseline), (HAlign::Right, VAlign::Top)] {
let mut s = Session::new();
add_text(&mut s, "1.1", 0.5, rotation, halign, valign, edit);
let (e, ink) = last_text(&s);
let case = format!("{name}, {rotation} degrees, {halign:?} {valign:?}");
assert_eq!(query(&mut s, ink, false), vec![json!(e.handle.hex())], "{case}");
assert!(erased(&mut s, ink, &e), "ERASE W, {case}");
for side in 0..4 {
assert!(query(&mut s, nudged(ink, side, 1e-3), false).is_empty(), "{case}, side {side}");
}
}
}
}
}
/// Text that draws nothing (blank) is never held. Text with no usable height draws at a height of
/// one, as the renderer draws it, and a window that holds that takes it.
#[test]
fn a_window_holds_blank_and_zero_height_text_as_drawn() {
let everything = Bounds2::new(Vec2::new(-1e3, -1e3), Vec2::new(1e3, 1e3));
let mut s = Session::new();
add_text(&mut s, " ", 0.5, 30.0, HAlign::Center, VAlign::Baseline, |_| ());
assert!(query(&mut s, everything, false).is_empty(), "blank text");
for height in [0.0, -1.0] {
let mut s = Session::new();
add_text(&mut s, "1.1", height, 30.0, HAlign::Center, VAlign::Baseline, |_| ());
let e = s.doc().unwrap().model.last().unwrap().as_ref().clone();
let ink = Bounds2::from_points(drawn(&s, &e));
assert!(ink.width() > 0.1, "height {height}: drawn at a usable height, {ink:?}");
assert_eq!(query(&mut s, ink, false), vec![json!(e.handle.hex())], "height {height}");
}
}
/// An MTEXT of narrow characters on two lines at (3, 2), attached by `justify`.
fn one_mtext(rotation: f64, justify: &str) -> (Session, Entity, Bounds2) {
let mut s = Session::new();
s.execute("mtext", &json!({"at": [3.0, 2.0], "text": r"1.1\P11", "height": 0.5, "rotation": rotation, "justify": justify})).unwrap();
let (e, ink) = last_text(&s);
(s, e, ink)
}
#[test]
fn a_window_on_the_edges_of_a_turned_mtext_selects_it() {
for rotation in ROTATIONS {
for justify in ["TL", "MC", "BR"] {
let (mut s, e, ink) = one_mtext(rotation, justify);
let case = format!("MTEXT {rotation} degrees, {justify}");
assert_eq!(query(&mut s, ink, false), vec![json!(e.handle.hex())], "query, {case}");
assert!(erased(&mut s, ink, &e), "ERASE W, {case}");
for side in 0..4 {
let w = nudged(ink, side, 1e-3);
assert!(query(&mut s, w, false).is_empty(), "query, {case}, side {side}");
assert!(!erased(&mut s, w, &e), "ERASE W, {case}, side {side}");
}
// A window polygon turned with it.
let pts = drawn(&s, &e);
let o = Vec2::new(3.0, 2.0);
let mut wp = |poly: [Vec2; 4]| {
let corners: Vec<String> = poly.iter().map(|p| format!("{},{}", p.x, p.y)).collect();
s.cmdline(&format!("ERASE WP {}", corners.join(" "))).unwrap();
erases(&mut s, "", &e)
};
assert!(wp(turned_box(&pts, o, rotation, 1e-3, None)), "WP, {case}");
assert!(!wp(turned_box(&pts, o, rotation, 1e-3, Some(1))), "WP, {case}, bottom");
}
}
}
/// A blank MTEXT draws nothing and is still selected by its frame; an MTEXT whose contents are
/// only formatting draws nothing either and keeps the document's box.
#[test]
fn mtext_that_draws_nothing_keeps_its_box() {
let mut s = Session::new();
s.execute("mtext", &json!({"at": [3.0, 2.0], "text": " ", "height": 0.5, "width": 4.0, "rotation": 30})).unwrap();
s.execute("mtext", &json!({"at": [20.0, 2.0], "text": r"{\L}", "height": 0.5, "rotation": 30})).unwrap();
let d = s.doc().unwrap();
let texts: Vec<Entity> = d.model.iter().map(|e| e.as_ref().clone()).collect();
for e in &texts {
assert!(drawn_points(&s, e).is_empty(), "{e:?} draws nothing");
}
// The blank one is held by its frame, around (3, 2).
let blank = Bounds2::new(Vec2::new(-5.0, -5.0), Vec2::new(10.0, 10.0));
assert_eq!(query(&mut s, blank, false), vec![json!(texts[0].handle.hex())]);
let b = entity_bounds(s.doc().unwrap(), &texts[1], 0);
assert!(!b.is_empty(), "the formatting-only MTEXT has a box");
assert_eq!(query(&mut s, b, false), vec![json!(texts[1].handle.hex())]);
}
+46
View File
@@ -244,3 +244,49 @@ fn acad_xdata_of_a_dimension_is_refused_and_kept_elsewhere() {
let dm = back.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).unwrap();
assert!(matches!(&dm.kind, EntityKind::Dimension(d) if !d.overrides.is_empty()), "the DSTYLE overrides survive");
}
/// A leader's DSTYLE list is its style overrides, written from the model: `properties.set`
/// refuses `ACAD` xdata that holds one (nothing changes), with or without overrides on the
/// leader, and takes other `ACAD` data, which a save keeps beside the overrides.
#[test]
fn a_dstyle_list_in_a_leaders_acad_xdata_is_refused_and_other_acad_data_kept() {
use cadcraft_engine::doc::{Common, Leader, Space};
use cadcraft_engine::geom::Vec3;
let overrides_of = |s: &Session| {
s.doc().unwrap().model.iter().find_map(|e| match &e.kind {
EntityKind::Leader(l) => Some(l.overrides.clone()),
_ => None,
})
};
for overrides in [json!({}), json!({"arrowSize": 1.5})] {
let want = overrides.as_object().cloned().unwrap();
let mut s = Session::new();
let leader = Leader {
vertices: vec![Vec3::ZERO, Vec3::new(10.0, 0.0, 0.0)],
arrow: true,
spline: false,
style: "Standard".into(),
overrides: want.clone(),
};
let h = s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Leader(leader)).unwrap().hex();
let before = entities(&mut s, json!({"xdata": true}));
let list = json!([[1000, "DSTYLE"], [1002, "{"], [1070, 41], [1040, 9.0], [1002, "}"]]);
let later = json!([[1000, "MINE"], [1000, "dstyle"], [1002, "{"], [1070, 41], [1040, 9.0], [1002, "}"]]);
for acad in [list, later] {
let r = s.execute("properties.set", &json!({"handles": [&h], "layer": "NEWLAYER", "xdata": {"ACAD": acad}}));
let msg = r.expect_err("a DSTYLE list on a leader is refused").to_string();
assert!(msg.contains("DSTYLE"), "the refusal names the list: {msg}");
assert_eq!(entities(&mut s, json!({"xdata": true})), before, "{overrides}");
assert_eq!(overrides_of(&s), Some(want.clone()));
assert!(s.doc().unwrap().layer("NEWLAYER").is_none(), "no layer is left behind");
}
// Other ACAD data, also a string that only reads DSTYLE, is foreign data and stays.
let other = json!({"ACAD": [[1000, "DSTYLE"], [1000, "MINE"], [1070, 42]]});
s.execute("properties.set", &json!({"handles": [&h], "xdata": other})).unwrap();
let bytes = cadcraft_io::write(s.doc().unwrap(), "leader.dxf").unwrap();
let mut back = Session::empty();
back.open_drawing(cadcraft_io::read_dxf(&bytes).unwrap(), "leader", None);
assert_eq!(entities(&mut back, json!({"xdata": "ACAD"}))[0]["xdata"], other, "{overrides}");
assert_eq!(overrides_of(&back), Some(want), "the overrides after a save and reopen");
}
}
+18
View File
@@ -210,3 +210,21 @@ fn hostile_support_files_never_panic() {
}
assert!(hatches(&s).is_empty());
}
#[test]
fn properties_set_pattern_keeps_a_user_patterns_definition() {
let mut s = Session::new();
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap();
s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "MYGRID", "patternText": PAT })).unwrap();
let hx = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle.hex();
// Setting the same name again keeps the definition the hatch carries.
s.execute("properties.set", &json!({ "handles": [hx], "pattern": "MYGRID" })).unwrap();
assert_eq!(hatches(&s).pop().unwrap().pattern_lines.len(), 2);
// Another loaded .pat pattern brings its own lines.
s.execute("properties.set", &json!({ "handles": [hx], "pattern": "MYSTEPS" })).unwrap();
let h = hatches(&s).pop().unwrap();
assert_eq!((h.pattern.as_str(), h.pattern_lines.first().map(|l| l.dashes.clone())), ("MYSTEPS", Some(vec![0.25, -0.25])));
// A library pattern is drawn from the library, with no lines of its own.
s.execute("properties.set", &json!({ "handles": [hx], "pattern": "ANSI31" })).unwrap();
assert!(hatches(&s).pop().unwrap().pattern_lines.is_empty());
}
+325
View File
@@ -0,0 +1,325 @@
//! The user's plot style folder: STYLESMANAGER keeps tables there for every drawing, and a layout
//! that chooses one takes a copy into the drawing, which no longer depends on the file.
//!
//! Its own test binary, like `plotters.rs`: the folder is process-wide and must be the in-memory
//! one before any session reads the real settings folder. Each test uses its own table names.
//! The folder here treats names as macOS and Windows disks do: `a.json` and `A.json` are one file.
#[path = "support/temp_dir.rs"]
mod temp_dir;
use cadcraft_doc::PlotStyleTable;
use cadcraft_engine::Session;
use cadcraft_engine::cmd::plotstyle_folder::{PlotStyleStore, set_plot_style_store};
use serde_json::{Value, json};
use temp_dir::TempDir;
static FILES: std::sync::Mutex<Vec<(String, String)>> = std::sync::Mutex::new(Vec::new());
/// A folder in memory whose names ignore case, as on a default macOS or Windows disk: writing
/// `a.json` over an existing `A.json` replaces that file and keeps its spelling.
fn folder() -> PlotStyleStore {
fn files() -> std::sync::MutexGuard<'static, Vec<(String, String)>> {
FILES.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
PlotStyleStore {
location: || None,
list: || Ok(files().iter().map(|(n, _)| n.clone()).collect()),
read: |n| files().iter().find(|(f, _)| f.eq_ignore_ascii_case(n)).map(|(_, t)| t.clone()).ok_or_else(|| format!("{n}: no such file")),
write: |n, t| {
let mut f = files();
match f.iter_mut().find(|(x, _)| x.eq_ignore_ascii_case(n)) {
Some(x) => x.1 = t.to_string(),
None => f.push((n.to_string(), t.to_string())),
}
Ok(())
},
delete: |n| {
// A file this folder refuses to remove, as a locked or read-only file would be.
if n.starts_with("stuck") {
return Err(format!("{n}: refused"));
}
let mut f = files();
let before = f.len();
f.retain(|(x, _)| !x.eq_ignore_ascii_case(n));
if f.len() == before { Err(format!("{n}: no such file")) } else { Ok(()) }
},
}
}
fn session() -> Session {
set_plot_style_store(folder());
Session::new()
}
fn tables(s: &mut Session) -> Vec<Value> {
s.execute("stylesmanager", &json!({})).unwrap()["tables"].as_array().unwrap().clone()
}
fn source(s: &mut Session, name: &str) -> Option<String> {
tables(s).iter().find(|t| t["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(name))).map(|t| t["source"].as_str().unwrap().to_string())
}
fn style_color(s: &Session, name: &str, aci: u8) -> Option<String> {
cadcraft_doc::plot_style_table(s.doc().unwrap(), name).and_then(|t| t.by_color(aci).and_then(|st| st.color).map(|c| c.hex()))
}
#[test]
fn a_folder_table_reaches_every_drawing() {
let mut a = session();
let r = a.execute("stylesmanager", &json!({"action": "new", "name": "every", "where": "folder", "from": "monochrome.ctb"})).unwrap();
assert_eq!(r["name"], "every.ctb", "the ending follows the kind");
assert_eq!(source(&mut a, "every.ctb").as_deref(), Some("folder"));
assert!(a.doc().unwrap().plot_style_tables.is_empty(), "the drawing itself is unchanged");
// A drawing opened later sees it too.
let mut b = Session::new();
assert_eq!(source(&mut b, "every.ctb").as_deref(), Some("folder"));
// The same name again is refused.
assert!(a.execute("stylesmanager", &json!({"action": "new", "name": "every.ctb", "where": "folder"})).is_err());
// Names a file can't have are refused.
assert!(a.execute("stylesmanager", &json!({"action": "new", "name": "../up", "where": "folder"})).is_err());
}
#[test]
fn a_layout_takes_a_copy_that_no_longer_depends_on_the_file() {
let mut s = session();
s.execute("stylesmanager", &json!({"action": "new", "name": "copied.ctb", "where": "folder"})).unwrap();
s.execute("pagesetup", &json!({"layout": "Layout1", "plotStyleTable": "copied.ctb"})).unwrap();
assert_eq!(source(&mut s, "copied.ctb").as_deref(), Some("drawing"), "the layout took the table into the drawing");
// Changing the folder's file leaves the drawing's copy as it is.
s.execute("stylesmanager", &json!({"action": "set", "name": "copied.ctb", "where": "folder", "style": {"name": "Color_1", "color": "#112233"}}))
.unwrap();
assert!(style_color(&s, "copied.ctb", 1).is_none(), "the drawing still plots with its own copy");
let file = cadcraft_doc::plot_style_folder_table("copied.ctb").unwrap();
assert!(file.by_color(1).and_then(|x| x.color).is_some(), "the file has the edit");
// Without `where`, an edit goes to the drawing's copy, and undo takes it back.
s.execute("stylesmanager", &json!({"action": "set", "name": "copied.ctb", "style": {"name": "Color_2", "color": "#445566"}})).unwrap();
assert!(style_color(&s, "copied.ctb", 2).is_some());
assert!(cadcraft_doc::plot_style_folder_table("copied.ctb").unwrap().by_color(2).and_then(|x| x.color).is_none(), "the file is untouched");
s.undo().unwrap();
assert!(style_color(&s, "copied.ctb", 2).is_none());
// Choosing the table again doesn't replace the drawing's copy with the file.
s.execute("pagesetup", &json!({"layout": "Layout2", "plotStyleTable": "copied.ctb"})).unwrap();
assert!(style_color(&s, "copied.ctb", 1).is_none());
}
#[test]
fn the_drawing_wins_over_a_folder_table_of_the_same_name() {
let mut s = session();
s.execute("stylesmanager", &json!({"action": "new", "name": "both.ctb", "where": "folder", "from": "monochrome.ctb"})).unwrap();
assert_eq!(source(&mut s, "both.ctb").as_deref(), Some("folder"));
s.execute("stylesmanager", &json!({"action": "new", "name": "both.ctb"})).unwrap();
assert_eq!(source(&mut s, "both.ctb").as_deref(), Some("drawing"));
assert!(style_color(&s, "both.ctb", 1).is_none(), "the drawing's version is the one used");
}
#[test]
fn renaming_the_file_leaves_the_drawing_alone() {
let mut s = session();
s.execute("stylesmanager", &json!({"action": "new", "name": "before.stb", "where": "folder"})).unwrap();
s.execute("pagesetup", &json!({"layout": "Layout1", "plotStyleTable": "before.stb"})).unwrap();
let r = s.execute("stylesmanager", &json!({"action": "rename", "name": "before.stb", "to": "after", "where": "folder"})).unwrap();
assert_eq!(r["name"], "after.stb");
assert_eq!(source(&mut s, "after.stb").as_deref(), Some("folder"));
assert_eq!(source(&mut s, "before.stb").as_deref(), Some("drawing"), "the drawing keeps its copy under the old name");
assert_eq!(s.doc().unwrap().layout("Layout1").unwrap().page.plot_style_table, "before.stb");
// Renaming the drawing's table moves this drawing's layouts with it.
let r = s.execute("stylesmanager", &json!({"action": "rename", "name": "before.stb", "to": "mine"})).unwrap();
assert_eq!(r["layouts"], 1);
assert_eq!(s.doc().unwrap().layout("Layout1").unwrap().page.plot_style_table, "mine.stb");
// A named table can't take a colour-dependent name, and built-in tables can't be renamed.
assert!(s.execute("stylesmanager", &json!({"action": "rename", "name": "after.stb", "to": "x.ctb"})).is_err());
assert!(s.execute("stylesmanager", &json!({"action": "rename", "name": "monochrome.ctb", "to": "mine"})).is_err());
}
#[test]
fn delete_from_the_folder_leaves_the_drawings_copy() {
let mut s = session();
s.execute("stylesmanager", &json!({"action": "new", "name": "gone.ctb", "where": "folder", "from": "monochrome.ctb"})).unwrap();
s.execute("pagesetup", &json!({"layout": "Layout1", "plotStyleTable": "gone.ctb"})).unwrap();
s.execute("stylesmanager", &json!({"action": "delete", "name": "gone.ctb", "where": "folder"})).unwrap();
assert_eq!(source(&mut s, "gone.ctb").as_deref(), Some("drawing"), "the layout still plots with its copy");
assert!(style_color(&s, "gone.ctb", 1).is_some());
assert!(s.execute("stylesmanager", &json!({"action": "delete", "name": "gone.ctb", "where": "folder"})).is_err());
}
#[test]
fn reload_reads_files_added_outside_and_skips_bad_ones() {
let mut s = session();
let store = folder();
let named = PlotStyleTable::named("whatever", "", Vec::new());
(store.write)("outside.json", &named.to_file_text()).unwrap();
(store.write)("wrongkind.ctb.json", &named.to_file_text()).unwrap();
(store.write)("broken.ctb.json", "not a table").unwrap();
let r = s.execute("stylesmanager", &json!({"action": "reload"})).unwrap();
let names: Vec<&str> = r["tables"].as_array().unwrap().iter().filter_map(|t| t["name"].as_str()).collect();
assert!(names.contains(&"outside.stb"), "named after the file, with its kind's ending: {names:?}");
assert!(!names.iter().any(|n| n.starts_with("wrongkind") || n.starts_with("broken")), "{names:?}");
let warnings = r["warnings"].as_array().unwrap();
assert!(
warnings.iter().any(|w| w.as_str().unwrap().contains("wrongkind")) && warnings.iter().any(|w| w.as_str().unwrap().contains("broken")),
"{warnings:?}"
);
}
/// File hooks for the tests that save or plot (the hooks are process-wide, so both share one set).
/// The writer refuses a drawing whose layout names a table the drawing doesn't carry.
fn with_io() -> Session {
cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks {
read: |_, _| Err("no reader in this test".into()),
write: |d, _| {
let missing = d.layouts.iter().any(|l| {
let n = l.page.plot_style_table.trim();
n.eq_ignore_ascii_case("carried.ctb") && !d.plot_style_tables.iter().any(|t| t.name.eq_ignore_ascii_case(n))
});
if missing { Err("the layout's table is not in the drawing".into()) } else { Ok(b"0\nEOF\n".to_vec()) }
},
plot: Some(|_, _, _| Ok(b"%PDF-1.4".to_vec())),
});
session()
}
#[test]
fn plotting_with_a_folder_table_takes_it_into_the_drawing() {
let mut s = with_io();
s.execute("stylesmanager", &json!({"action": "new", "name": "plotted.ctb", "where": "folder"})).unwrap();
// A preview (an image with no file) takes nothing.
s.execute("plot", &json!({"layout": "Model", "output": "png", "plotStyleTable": "plotted.ctb"})).unwrap();
s.execute("plot", &json!({"layout": "Model", "output": "png", "path": null, "plotStyleTable": "plotted.ctb"})).unwrap();
assert_eq!(source(&mut s, "plotted.ctb").as_deref(), Some("folder"));
assert!(s.doc().unwrap().model_page.is_none());
// A plot from Model takes a copy, and Model remembers the table for the next plot.
s.execute("plot", &json!({"layout": "Model", "plotStyleTable": "plotted.ctb"})).unwrap();
assert_eq!(source(&mut s, "plotted.ctb").as_deref(), Some("drawing"));
assert_eq!(model_table(&s), "plotted.ctb");
assert_eq!(cadcraft_render::paper::model_page(s.doc().unwrap()).plot_style_table, "plotted.ctb", "the next Model plot starts from it");
s.undo().unwrap();
assert_eq!(model_table(&s), "");
}
fn model_table(s: &Session) -> String {
s.doc().unwrap().model_page.as_ref().map(|m| m.plot_style_table.clone()).unwrap_or_default()
}
#[test]
fn model_keeps_only_its_plot_style_table() {
let mut s = session();
s.execute("pagesetup", &json!({"layout": "model", "plotStyleTable": "monochrome.ctb"})).unwrap();
assert_eq!(model_table(&s), "monochrome.ctb");
assert!(s.execute("pagesetup", &json!({"layout": "Model", "paper": "A3"})).is_err(), "Model keeps no paper");
s.execute("pagesetup", &json!({"layout": "Model", "plotStyleTable": "None"})).unwrap();
assert_eq!(model_table(&s), "");
}
#[test]
fn saving_puts_the_folder_tables_the_layouts_use_into_the_file() {
let mut s = with_io();
s.execute("stylesmanager", &json!({"action": "new", "name": "carried.ctb", "where": "folder"})).unwrap();
s.execute("pagesetup", &json!({"layout": "Layout1", "plotStyleTable": "carried.ctb"})).unwrap();
// A drawing whose layout names the folder table without a copy (one made before copies were kept).
s.execute("stylesmanager", &json!({"action": "delete", "name": "carried.ctb", "where": "drawing"})).unwrap();
assert_eq!(source(&mut s, "carried.ctb").as_deref(), Some("folder"));
let dir = TempDir::new("carried");
s.execute("saveas", &json!({"path": dir.path_str("carried.dxf")})).unwrap();
assert_eq!(source(&mut s, "carried.ctb").as_deref(), Some("drawing"), "the save took the table into the drawing");
}
#[test]
fn renaming_a_folder_table_by_case_keeps_it() {
let mut s = session();
s.execute("stylesmanager", &json!({"action": "new", "name": "Office.ctb", "where": "folder", "from": "monochrome.ctb"})).unwrap();
s.execute("stylesmanager", &json!({"action": "rename", "name": "Office.ctb", "to": "office.ctb", "where": "folder"})).unwrap();
let names: Vec<String> = tables(&mut s).iter().filter_map(|t| t["name"].as_str().map(str::to_string)).collect();
assert!(names.iter().any(|n| n == "office.ctb"), "the table is still there, spelt the new way: {names:?}");
assert!(style_color(&s, "office.ctb", 1).is_some(), "with its styles");
}
#[test]
fn a_file_named_without_its_kind_is_edited_and_deleted_in_place() {
let mut s = session();
(folder().write)("loose.json", &PlotStyleTable::named("whatever", "", Vec::new()).to_file_text()).unwrap();
s.execute("stylesmanager", &json!({"action": "reload"})).unwrap();
s.execute("stylesmanager", &json!({"action": "set", "name": "loose.stb", "where": "folder", "description": "edited"})).unwrap();
assert_eq!(cadcraft_doc::plot_style_folder_table("loose.stb").unwrap().description, "edited", "the edit is the table the folder holds");
s.execute("stylesmanager", &json!({"action": "delete", "name": "loose.stb", "where": "folder"})).unwrap();
assert!(source(&mut s, "loose.stb").is_none(), "no file holds it any more");
}
#[test]
fn renaming_the_drawings_table_moves_model_with_it() {
let mut s = session();
s.execute("stylesmanager", &json!({"action": "new", "name": "modelold.ctb"})).unwrap();
s.execute("pagesetup", &json!({"layout": "Model", "plotStyleTable": "modelold.ctb"})).unwrap();
s.execute("stylesmanager", &json!({"action": "rename", "name": "modelold.ctb", "to": "modelnew"})).unwrap();
assert_eq!(model_table(&s), "modelnew.ctb");
}
#[test]
fn a_pdf_of_model_alone_remembers_its_table_from_a_layout_tab() {
let mut s = with_io();
s.execute("stylesmanager", &json!({"action": "new", "name": "frompaper.ctb", "where": "folder"})).unwrap();
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.execute("plot", &json!({"layouts": ["Model"], "plotStyleTable": "frompaper.ctb"})).unwrap();
assert_eq!(model_table(&s), "frompaper.ctb", "Model is the sheet plotted");
}
#[test]
fn a_refused_plot_leaves_the_drawing_as_it_was() {
let mut s = with_io();
s.execute("stylesmanager", &json!({"action": "new", "name": "refused.ctb", "where": "folder"})).unwrap();
let dir = TempDir::new("refused");
let out = std::path::PathBuf::from(dir.path_str("out"));
std::fs::create_dir(&out).unwrap();
let roots = cadcraft_engine::file_access::AutomationRoots::new(None, Some(&out)).unwrap();
let undo = s.state().unwrap().undo.len();
cadcraft_engine::file_access::confine(roots.as_ref(), || {
let outside = dir.path_str("elsewhere.pdf");
assert!(s.execute("plot", &json!({"layout": "Model", "path": outside, "plotStyleTable": "refused.ctb"})).is_err());
assert!(s.execute("plot", &json!({"layout": "Layout1", "path": outside, "plotStyleTable": "refused.ctb"})).is_err());
});
assert_eq!(model_table(&s), "", "Model still has no table");
assert_eq!(source(&mut s, "refused.ctb").as_deref(), Some("folder"), "the drawing took no copy");
assert_eq!(s.state().unwrap().undo.len(), undo, "and no undo step");
}
#[test]
fn new_copies_the_table_from_the_place_chosen() {
let mut s = session();
s.execute("stylesmanager", &json!({"action": "new", "name": "twice.ctb", "where": "folder"})).unwrap();
s.execute("stylesmanager", &json!({"action": "set", "name": "twice.ctb", "where": "folder", "style": {"name": "Color_1", "color": "#ff0000"}}))
.unwrap();
s.execute("stylesmanager", &json!({"action": "new", "name": "twice.ctb"})).unwrap();
let from = |s: &mut Session, name: &str, place: &str| {
s.execute("stylesmanager", &json!({"action": "new", "name": name, "from": "twice.ctb", "fromWhere": place})).unwrap();
style_color(s, name, 1)
};
let folder = from(&mut s, "fromfolder.ctb", "folder");
let drawing = from(&mut s, "fromdrawing.ctb", "drawing");
assert!(folder.is_some(), "the folder's table, with its red Color_1");
assert_ne!(folder, drawing, "each copy is of the table chosen");
}
#[test]
fn plotting_model_again_with_its_table_leaves_no_undo_step() {
let mut s = with_io();
s.execute("stylesmanager", &json!({"action": "new", "name": "again.ctb", "where": "folder"})).unwrap();
let undo = |s: &Session| s.state().unwrap().undo.len();
let plot = |s: &mut Session, table: &str| s.execute("plot", &json!({"layout": "Model", "plotStyleTable": table})).unwrap();
let before = undo(&s);
plot(&mut s, "None");
assert_eq!(undo(&s), before, "no table, as before: nothing to undo");
plot(&mut s, "again.ctb");
let after_first = undo(&s);
assert!(after_first > before, "the first plot keeps the table, and can be undone");
plot(&mut s, "again.ctb");
assert_eq!(undo(&s), after_first, "the same table again: nothing to undo");
}
#[test]
fn a_folder_rename_that_cant_remove_the_old_file_keeps_one_copy() {
let mut s = session();
s.execute("stylesmanager", &json!({"action": "new", "name": "stuck.ctb", "where": "folder"})).unwrap();
assert!(s.execute("stylesmanager", &json!({"action": "rename", "name": "stuck.ctb", "to": "freed", "where": "folder"})).is_err());
assert_eq!(source(&mut s, "stuck.ctb").as_deref(), Some("folder"), "the table keeps its old name");
assert!(source(&mut s, "freed.ctb").is_none(), "and isn't held twice");
}
+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]));
}
+26
View File
@@ -23,3 +23,29 @@ fn purge_keeps_arrowhead_blocks_dimension_styles_name() {
let d = s.doc().unwrap();
assert!(d.block("_Dot").is_some() && d.block("MyArrow").is_some());
}
/// PURGE keeps the arrowhead block a leader's own override names (its DIMLDRBLK), as it keeps
/// the ones a dimension's overrides name (#3721).
#[test]
fn purge_keeps_the_arrowhead_block_a_leaders_override_names() {
use cadcraft_engine::doc::{Common, Leader, Space};
let mut s = Session::new();
let d = s.doc_mut().unwrap();
for (i, name) in ["MyArrow", "Unused"].into_iter().enumerate() {
let mut b = Block::new(name);
b.entities.push(Entity::new(Handle(0x9000 + i as u64), EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 0.5 })));
d.blocks.insert(name.into(), Arc::new(b));
}
let overrides = json!({ "leaderArrowBlock": "MyArrow" });
let leader = Leader {
vertices: vec![Vec3::ZERO, Vec3::new(10.0, 0.0, 0.0)],
arrow: true,
spline: false,
style: "Standard".into(),
overrides: overrides.as_object().cloned().unwrap_or_default(),
};
d.add(&Space::Model, Common::default(), EntityKind::Leader(leader)).unwrap();
let r = s.execute("purge", &json!({ "type": "blocks" })).unwrap();
assert_eq!(r["purged"]["blocks"], json!(["Unused"]), "{r}");
assert!(s.doc().unwrap().block("MyArrow").is_some());
}
+4
View File
@@ -67,6 +67,10 @@ impl Face {
FontRef::from_index(&bytes, index).ok()?;
Some(Face { bytes, index })
}
/// The font file's bytes and this face's index in it (a collection holds several faces).
pub fn data(&self) -> (&Arc<Vec<u8>>, u32) {
(&self.bytes, self.index)
}
pub(crate) fn font(&self) -> Option<FontRef<'_>> {
FontRef::from_index(&self.bytes, self.index).ok()
}
+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" }
+236 -15
View File
@@ -460,24 +460,101 @@ pub(crate) fn xdata<'a>(tags: &'a [Tag], app: &str) -> &'a [Tag] {
rest.get(..end).unwrap_or(&[])
}
/// The groups inside `1000 <name>` `1002 {` … `1002 }` of an xdata run (nested braces kept).
pub(crate) fn xdata_list<'a>(x: &'a [Tag], name: &str) -> &'a [Tag] {
let Some(at) = x.iter().position(|t| t.code == 1000 && t.str().trim().eq_ignore_ascii_case(name)) else { return &[] };
let Some(open) = x.get(at + 1).filter(|t| t.code == 1002 && t.str().trim() == "{") else { return &[] };
let _ = open;
let body = x.get(at + 2..).unwrap_or(&[]);
/// Whether xdata group `t` is the string `name` (any case): what names a list when a `1002 {`
/// follows it.
fn is_list_name(t: &Tag, name: &str) -> bool {
t.code == 1000 && t.str().trim().eq_ignore_ascii_case(name)
}
/// Whether xdata group `t` is the control string `brace` (`{` or `}`).
fn is_brace(t: &Tag, brace: &str) -> bool {
t.code == 1002 && t.str().trim() == brace
}
/// How many groups the body of a list takes at the start of `body` (the groups after its
/// `1002 {`), and whether a `1002 }` closes it there; a list left open runs to the end of the
/// run. Nested braces belong to the body.
fn xdata_list_body(body: &[Tag]) -> (usize, bool) {
let mut depth = 0usize;
for (i, t) in body.iter().enumerate() {
if t.code == 1002 {
match t.str().trim() {
"{" => depth += 1,
"}" if depth == 0 => return body.get(..i).unwrap_or(&[]),
"}" => depth -= 1,
_ => {}
if is_brace(t, "{") {
depth += 1;
} else if is_brace(t, "}") {
if depth == 0 {
return (i, true);
}
depth -= 1;
}
}
body
(body.len(), false)
}
/// The groups inside the first list `1000 <name>` `1002 {` … `1002 }` of an xdata run (nested
/// braces kept). The name and the opening brace are looked for together: a string that only
/// reads `<name>`, with no brace after it, starts no list and does not hide a list after it.
pub(crate) fn xdata_list<'a>(x: &'a [Tag], name: &str) -> &'a [Tag] {
let Some(at) = x.windows(2).position(|w| matches!(w, [n, open] if is_list_name(n, name) && is_brace(open, "{"))) else { return &[] };
let body = x.get(at + 2..).unwrap_or(&[]);
body.get(..xdata_list_body(body).0).unwrap_or(&[])
}
/// Move the name strings held at brace depth `depth` or deeper from `held` to the end of `kept`,
/// in the order they had. `held` is in order of depth, so those are its last ones: only they are
/// looked at, and a call that releases nothing costs one comparison.
fn release_held(held: &mut Vec<(usize, Tag)>, depth: usize, kept: &mut Vec<Tag>) {
let from = held.len() - held.iter().rev().take_while(|(d, _)| *d >= depth).count();
kept.extend(held.drain(from..).map(|(_, t)| t));
}
/// Remove every list `1000 <name>` `1002 {` … `1002 }` from an xdata run, each with its name
/// group and braces: the lists [`xdata_list`] reads, so what is modelled from one is not kept
/// raw beside it. Which groups make a list is read from the run as given: a name group with the
/// opening brace right after it. Every other group stays, a string that only reads `<name>` too.
///
/// What is left holds no such list. Where a removed list stood between a name string and an
/// opening brace, the two would read as a list once written next to each other; the string then
/// goes behind that group and the groups in braces right after it, to the first place where no
/// opening brace follows it. It stays inside the braces it stood in, so every group keeps its
/// nesting, and the groups in the braces stay where they are. One pass over the run.
pub(crate) fn remove_xdata_lists(x: &mut Vec<Tag>, name: &str) {
let mut kept: Vec<Tag> = Vec::with_capacity(x.len());
// Name strings that a removal left in front of an opening brace, each with the brace depth
// it stood at, until a group that is no opening brace comes at that depth.
let mut held: Vec<(usize, Tag)> = Vec::new();
// How many braces are open around the next group.
let mut depth = 0usize;
// Whether a list was removed right after the last group kept.
let mut joined = false;
let mut rest = x.as_slice();
while let Some((t, after)) = rest.split_first() {
rest = after;
let open = is_brace(t, "{");
if open && kept.last().is_some_and(|n| is_list_name(n, name)) {
if !joined {
kept.pop();
let (len, closed) = xdata_list_body(rest);
rest = rest.get(len + usize::from(closed)..).unwrap_or(&[]);
joined = true;
continue;
}
// The names were no list's in the run as given: keep them, away from the brace.
let names = kept.iter().rev().take_while(|n| is_list_name(n, name)).count();
held.extend(kept.drain(kept.len() - names..).map(|n| (depth, n)));
}
if open {
depth += 1;
} else {
// Before the brace that closes their group, or before any other group there.
release_held(&mut held, depth, &mut kept);
if is_brace(t, "}") {
depth = depth.saturating_sub(1);
}
}
kept.push(t.clone());
joined = false;
}
release_held(&mut held, 0, &mut kept);
*x = kept;
}
/// Owner handle of a record: the first 330 outside `102 {…}` groups.
@@ -494,14 +571,18 @@ pub(crate) fn owner(tags: &[Tag]) -> Option<String> {
None
}
/// Per-dimension overrides from the `ACAD` "DSTYLE" xdata: `1070 <code>` followed by the value.
/// The name of the list in a dimension's or leader's `ACAD` xdata that holds its overrides.
pub(crate) const DSTYLE_LIST: &str = "DSTYLE";
/// Per-dimension (and per-leader) overrides from the `ACAD` "DSTYLE" xdata: `1070 <code>`
/// followed by the value.
pub(crate) fn read_dstyle(
tags: &[Tag],
styles: &HashMap<String, String>,
blocks: &HashMap<String, String>,
ltypes: &HashMap<String, String>,
) -> serde_json::Map<String, Value> {
read_dimvar_list(xdata_list(xdata(tags, "ACAD"), "DSTYLE"), styles, blocks, ltypes)
read_dimvar_list(xdata_list(xdata(tags, "ACAD"), DSTYLE_LIST), styles, blocks, ltypes)
}
/// A style's [`NEWER_CODES`] variables from its `CADCRAFT` "DIMVARS" xdata.
@@ -1100,4 +1181,144 @@ mod tests {
assert!(is_named_frame(&unit, Vec3::ZERO, Vec3::new(1.0, 1e-12, 0.0), Vec3::new(-1e-12, 1.0, 0.0)));
assert!(!is_named_frame(&unit, Vec3::ZERO, Vec3::new(0.0, 1.0, 0.0), Vec3::new(-1.0, 0.0, 0.0)));
}
/// An xdata run from (code, value) pairs.
fn run(list: &[(i32, &str)]) -> Vec<Tag> {
list.iter().map(|(code, value)| Tag::s(*code, *value)).collect()
}
/// `x` without its DSTYLE lists.
fn without_dstyle(mut x: Vec<Tag>) -> Vec<Tag> {
remove_xdata_lists(&mut x, DSTYLE_LIST);
x
}
/// Whether a run still holds a list [`xdata_list`] would read: a DSTYLE name group followed
/// by an opening brace.
fn has_dstyle_list(x: &[Tag]) -> bool {
x.windows(2).any(|w| matches!(w, [a, b] if a.code == 1000 && a.str() == DSTYLE_LIST && b.code == 1002 && b.str() == "{"))
}
/// A string that only has a list's name starts no list: the list after it is still read,
/// and removing the lists takes that list and leaves the string.
#[test]
fn a_loose_name_string_does_not_hide_the_list_after_it() {
let list = [(1000, "DSTYLE"), (1002, "{"), (1070, "41"), (1040, "1.5"), (1002, "}")];
for before in [vec![(1000, "DSTYLE"), (1070, "7")], vec![(1000, "DSTYLE")]] {
let mut x = run(&before);
x.extend(run(&list));
x.push(Tag::s(1000, "TAIL"));
assert_eq!(xdata_list(&x, DSTYLE_LIST), run(&[(1070, "41"), (1040, "1.5")]), "{before:?}");
let mut want = run(&before);
want.push(Tag::s(1000, "TAIL"));
assert_eq!(without_dstyle(x), want, "{before:?}");
}
// A name string with no list anywhere is no list and stays.
let loose = run(&[(1000, "DSTYLE"), (1070, "7")]);
assert!(xdata_list(&loose, DSTYLE_LIST).is_empty());
assert_eq!(without_dstyle(loose.clone()), loose);
}
/// Removing takes each list whole: its nested braces with it, and a list left open to the
/// end of the run.
#[test]
fn removing_lists_takes_nested_braces_and_an_unclosed_list() {
let nested = [(1000, "DSTYLE"), (1002, "{"), (1002, "{"), (1070, "1"), (1002, "}"), (1070, "2")];
let mut closed = run(&[(1000, "A")]);
closed.extend(run(&nested));
closed.extend(run(&[(1002, "}"), (1000, "B")]));
assert_eq!(xdata_list(&closed, DSTYLE_LIST), run(&nested[2..]));
assert_eq!(without_dstyle(closed), run(&[(1000, "A"), (1000, "B")]));
let mut open = run(&[(1000, "A")]);
open.extend(run(&nested));
assert_eq!(xdata_list(&open, DSTYLE_LIST), run(&nested[2..]));
assert_eq!(without_dstyle(open), run(&[(1000, "A")]));
}
/// The groups of `x`, each with how many braces are open around it, in a fixed order: for
/// comparing what two runs hold and how deep, whatever their order.
fn sorted(x: &[Tag]) -> Vec<(i32, String, usize)> {
let mut depth = 0usize;
let mut out = Vec::with_capacity(x.len());
for t in x {
if t.code == 1002 && t.str() == "}" {
depth = depth.saturating_sub(1);
}
out.push((t.code, t.str(), depth));
if t.code == 1002 && t.str() == "{" {
depth += 1;
}
}
out.sort();
out
}
/// Removing takes the lists of the run as given and nothing else. Where a removed list stood
/// between a name string and an opening brace, the groups in those braces are no list's and
/// stay; every group kept is as deep in braces as it was; what is left still holds no list,
/// and removing again changes nothing (a file written from it reads the same).
#[test]
fn removing_lists_keeps_the_groups_that_become_adjacent() {
let list = [(1000, "DSTYLE"), (1002, "{"), (1070, "41"), (1040, "1.5"), (1002, "}")];
let group = [(1002, "{"), (1000, "KEEP"), (1002, "}")];
let loose = (1000, "DSTYLE");
let (open, close) = ((1002, "{"), (1002, "}"));
// Each case: the run, and how many groups its lists take.
let cases: Vec<(Vec<(i32, &str)>, usize)> = vec![
// One loose name string before the list, an unnamed group after it.
([&[loose][..], &list, &group, &[(1000, "B")]].concat(), list.len()),
// Two loose strings, in lower case too (names are read in any case).
([&[(1000, "dstyle"), loose][..], &list, &group].concat(), list.len()),
// Two lists, one after the other, between the string and the group.
([&[(1000, "A"), loose][..], &list, &list, &group, &group].concat(), 2 * list.len()),
// A list after the group as well: the string must not land in front of it.
([&[loose][..], &list, &group, &list, &group].concat(), 2 * list.len()),
// The string right before a group in the run as given is that list's name.
([&[(1000, "A")][..], &[loose], &group, &list, &group].concat(), 1 + group.len() + list.len()),
// All of it inside an outer group: the string must stay inside that group.
([&[open, loose][..], &list, &group, &[close, (1000, "B")]].concat(), list.len()),
// Two deep, with a second group after the first and one more string outside.
([&[open, open, loose][..], &list, &group, &group, &[close, close, loose]].concat(), list.len()),
// Strings held at three depths at once, each released inside its own group.
([&[loose, loose, open, close, open].repeat(3)[..], &group, &[(1000, "B"), close, close, close]].concat(), 9),
// An outer group that is never closed.
([&[open, (1000, "A"), loose][..], &list, &list, &group].concat(), 2 * list.len()),
];
for (case, removed) in cases {
let x = run(&case);
let left = without_dstyle(x.clone());
assert!(!has_dstyle_list(&left) && xdata_list(&left, DSTYLE_LIST).is_empty(), "{case:?}: {left:?}");
assert_eq!(left.len(), x.len() - removed, "{case:?}: only the lists' groups went: {left:?}");
assert!(left.windows(3).any(|w| w == run(&group)), "{case:?}: the unnamed group is whole: {left:?}");
let mut before = sorted(&x);
for g in sorted(&left) {
let at = before.iter().position(|b| *b == g);
assert!(at.is_some(), "{case:?}: {g:?} is new, or not as deep in braces as it was: {left:?}");
before.remove(at.unwrap_or_default());
}
assert_eq!(without_dstyle(left.clone()), left, "{case:?}: removing again changes nothing");
}
// The first case, group by group: the loose string is behind the braces it stood before.
let left = without_dstyle(run(&[&[loose][..], &list, &group, &[(1000, "B")]].concat()));
assert_eq!(left, run(&[(1002, "{"), (1000, "KEEP"), (1002, "}"), (1000, "DSTYLE"), (1000, "B")]));
// Inside an outer group it stays inside it, before the brace that closes that group.
let left = without_dstyle(run(&[&[open, loose][..], &list, &group, &[close, (1000, "B")]].concat()));
assert_eq!(left, run(&[open, open, (1000, "KEEP"), close, loose, close, (1000, "B")]));
}
/// Many lists one after another are all removed and the groups around and between them stay
/// in order (one pass over the run: the count here is far past what one object may hold).
#[test]
fn many_consecutive_lists_are_removed() {
const LISTS: usize = 60_000;
let mut x = run(&[(1000, "HEAD")]);
for i in 0..LISTS {
x.extend(run(&[(1000, "DSTYLE"), (1002, "{"), (1070, "41"), (1002, "}")]));
if i % 20_000 == 0 {
x.push(Tag::s(1070, i.to_string()));
}
}
x.push(Tag::s(1000, "TAIL"));
assert_eq!(without_dstyle(x), run(&[(1000, "HEAD"), (1070, "0"), (1070, "20000"), (1070, "40000"), (1000, "TAIL")]));
}
}
+50 -2
View File
@@ -68,9 +68,19 @@ fn modelled_xdict_key(key: &str, of_insert: bool) -> bool {
/// Applications whose xdata CADCraft reads and writes itself
/// ([`cadcraft_doc::RESERVED_XDATA_APPS`]). `ACAD` holds dimension overrides (DSTYLE) on
/// dimensions and dimension styles; elsewhere it is kept.
/// dimensions and dimension styles; elsewhere it is kept. On a leader only its DSTYLE list is
/// CADCraft's own (the leader's overrides, see [`leader_acad_rest`]); the rest of the run is kept.
const OWN_APPS: &[&str] = cadcraft_doc::RESERVED_XDATA_APPS;
/// A LEADER's `ACAD` run (`chunk`, from its `1001` group on) without its DSTYLE lists, which
/// are read into the leader's overrides and written from them. Empty when nothing else is in
/// the run: then there is nothing to keep.
fn leader_acad_rest(chunk: &[Tag]) -> Vec<Tag> {
let mut rest = chunk.to_vec();
crate::dxf_ext::remove_xdata_lists(&mut rest, crate::dxf_ext::DSTYLE_LIST);
if rest.len() < chunk.len() && rest.len() <= 1 { Vec::new() } else { rest }
}
/// Most objects kept from one file.
const MAX_OBJECTS: usize = 1_000_000;
/// Most xdata groups kept per record (AutoCAD allows 16 KB of xdata per object).
@@ -277,7 +287,10 @@ fn foreign_xdata(kind: &str, tags: &[Tag]) -> Vec<RawTag> {
i += 1 + len;
let app = first.str_ref().map(up).unwrap_or_default();
let own = OWN_APPS.contains(&app.as_str()) || (app == "ACAD" && matches!(kind, "DIMENSION" | "DIMSTYLE"));
if app.is_empty() || own || out.len() + chunk.len() > MAX_XDATA_GROUPS {
// A leader's DSTYLE list is modelled (its overrides); the rest of its `ACAD` run is kept.
let split = (app == "ACAD" && kind == "LEADER").then(|| leader_acad_rest(chunk));
let chunk = split.as_deref().unwrap_or(chunk);
if app.is_empty() || own || chunk.is_empty() || out.len() + chunk.len() > MAX_XDATA_GROUPS {
continue;
}
let mut depth = 0i32;
@@ -2307,8 +2320,14 @@ fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: Opti
rest.iter().position(|t| t.code == 102 && t.str().trim() == "}").map(|e| s + 1 + e)
});
let xdict_at = if h.has_reactors { reactors_end.or(handle_at) } else { handle_at };
// A leader's kept `ACAD` groups go at the end of the `ACAD` run written for its overrides.
let joined = x.filter(|_| r.kind == "LEADER" && own_apps.contains("ACAD")).map(|x| kept_acad_rest(map, x)).filter(|g| !g.is_empty());
let join_at = joined.as_ref().map(|_| acad_run_end(b));
let mut seen_owner = false;
for (i, t) in b.iter().enumerate() {
if Some(i) == join_at {
out.extend(joined.iter().flatten().cloned());
}
if i == props_at
&& let Some(x) = x
{
@@ -2358,6 +2377,9 @@ fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: Opti
map.handle_group(out, "ACAD_XDICTIONARY", 360, &[xd.hex()]);
}
}
if join_at == Some(b.len()) {
out.extend(joined.into_iter().flatten());
}
if let Some(x) = x {
if props_at == b.len() {
if let Some((want, book)) = &x.color_book
@@ -2427,6 +2449,32 @@ fn join_entries(map: &Map, b: &[Tag], kept: &ForeignObject, out: &mut Vec<Tag>)
}
}
/// The index after the last group of written record `b`'s `ACAD` xdata run (the end of the
/// record when it has none).
fn acad_run_end(b: &[Tag]) -> usize {
let Some(start) = b.iter().position(|t| t.code == 1001 && up(&t.str()) == "ACAD") else { return b.len() };
b.iter().skip(start + 1).position(|t| t.code == 1001).map_or(b.len(), |n| start + 1 + n)
}
/// The groups kept for a leader under `ACAD` (without the `1001` groups), handles remapped, for
/// the `ACAD` run the writer made from the leader's overrides: an application's data is one run
/// on a record, so [`xdata`] leaves these out there. A DSTYLE list among them is left out: the
/// run already holds the one the overrides give. (The reader keeps none, and `entmod`, `entmake`
/// and `properties.set` refuse one; this guards kept data that reached the leader another way.)
fn kept_acad_rest(map: &Map, x: &ForeignExtra) -> Vec<Tag> {
let mut out = Vec::new();
let mut inside = false;
for r in &x.xdata {
if r.code == 1001 {
inside = up(&r.value) == "ACAD";
} else if inside {
out.push(map.group(r));
}
}
crate::dxf_ext::remove_xdata_lists(&mut out, crate::dxf_ext::DSTYLE_LIST);
out
}
/// Kept xdata of applications the record doesn't already carry, handles remapped.
fn xdata(map: &Map, x: &ForeignExtra, own: &HashSet<String>, out: &mut Vec<Tag>) {
let mut skip = false;
+3 -2
View File
@@ -25,8 +25,8 @@ mod tables;
mod text;
use document::{
HandlePolicy, append, apply_sortents, count_skipped, dropped_paper_views, out_of_memory, outside_sections, parse_entities, place_blocks,
place_entities, read_blocks, read_objects, setup_layouts,
HandlePolicy, append, apply_sortents, count_skipped, drop_followed_attrib_layers, dropped_paper_views, out_of_memory, outside_sections,
parse_entities, place_blocks, place_entities, read_blocks, read_objects, setup_layouts,
};
#[cfg(test)]
use entities::acad_table;
@@ -299,6 +299,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize,
// are numbered above it and rebuilt on save, so following $HANDSEED would drift every save.
let own_seed = objs.xrecord_text(crate::dxf_ext::HANDSEED_KEY).and_then(|t| Handle::parse_hex(t.trim()));
let (paper_block_for, first_layout) = setup_layouts(&mut d, &mut layout_objs, &rx);
drop_followed_attrib_layers(&mut blocks, &mut entities);
place_blocks(&mut d, blocks, &mut rx, &paper_block_for, &first_layout)?;
place_entities(&mut d, entities, &rx, &paper_block_for, &first_layout)?;
draw_kept_dimensions_from_their_blocks(&mut d);

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