Compare commits

..
Author SHA1 Message Date
FredApps 63a4ee935c ci: pass only the dispatch token to the notify-services workflow
secrets: inherit hands the called workflow every repository secret, including
the signing credentials. The reusable workflow only reads
ARTCRAFT_SERVICES_DISPATCH_TOKEN, so map just that one.
2026-11-27 09:43:58 +01:00
Dylan M. Taylor fa0442a1d6 ci: notify artcraft-services on release state changes 2026-11-26 21:56:49 -05:00
443 changed files with 3558 additions and 49104 deletions
+5 -15
View File
@@ -4,10 +4,10 @@
"repository_id": 1408289866,
"producer_workflow_id": 429719786,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "main",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "main",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
@@ -83,9 +83,7 @@
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [
"github-actions[bot]"
],
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
@@ -97,15 +95,7 @@
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
},
"package_formats": [
"appimage",
"arch",
"deb",
"flatpak",
"oci",
"rpm"
]
}
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
-72
View File
@@ -1,72 +0,0 @@
name: Dispatch release-ref nightly
# Transport only, never authorization. No checkout, payload parsing or release environment.
on:
workflow_run:
workflows: [CADCraft unsigned nightly]
types: [completed]
branches: [main]
permissions: {}
jobs:
dispatch:
# Actual context guards: official repository and completed workflow_run only.
if: >-
github.repository == 'storytold/cadcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Dispatch only the exact completed producer run and attempt
shell: python
env:
GH_TOKEN: ${{ github.token }}
run: |
import json
import os
import urllib.request
def require(value, message):
if not value:
raise RuntimeError(message)
# These filters reduce noise; the protected signer-branch validator repeats admission
# against authenticated API metadata and required attestation/quality evidence.
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/cadcraft', 'wrong repository')
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
event = json.load(stream)
require(event.get('action') == 'completed', 'producer is not complete')
require(event.get('repository', {}).get('full_name') == 'storytold/cadcraft', 'wrong event repository')
producer = event.get('workflow_run', {})
require(producer.get('head_repository', {}).get('full_name') == 'storytold/cadcraft', 'foreign producer')
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
require(producer.get('head_branch') == 'main', 'wrong producer branch')
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
run_id, attempt = producer.get('id'), producer.get('run_attempt')
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
}}).encode('utf-8')
request = urllib.request.Request(
'https://api.github.com/repos/storytold/cadcraft/actions/workflows/nightly-sign.yml/dispatches',
data=body, method='POST', headers={
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'cadcraft-nightly-dispatch'
})
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise RuntimeError('dispatch redirects are forbidden')
# One bounded request, no retry: duplicate transport is not publication authority.
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
require(response.status == 204, 'dispatch was not accepted')
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
+2 -16
View File
@@ -34,26 +34,12 @@ jobs:
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: main
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: cadcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
+4 -7
View File
@@ -1,10 +1,8 @@
name: CADCraft unsigned nightly
# Automated nightly builds at 00:30 UTC (paired with nightly-dispatch.yml for automatic
# Stage 2 signer dispatch) plus supervised manual runs by the reviewed manual actors.
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
on:
schedule:
- cron: '30 0 * * *'
workflow_dispatch:
permissions:
@@ -24,9 +22,9 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: main
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: cadcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
@@ -34,4 +32,3 @@ jobs:
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
+1 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
concurrency:
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
group: sonarcloud-${{ github.ref }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
-2
View File
@@ -72,8 +72,6 @@ Layout:
Checks for the crates you changed: `cargo test -p <crate>`, `cargo clippy -p <crate> --all-targets -- -D warnings`, `cargo xtask layers`, `cargo xtask assets`, `cargo xtask wasm`, `cargo xtask parity` (regenerates `docs/parity-checklist.md`).
Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a covered menu item `headless: yes` because its command is in the engine registry that `cadcraft-cli` and the MCP server load. An uncovered item takes `no`/`partial` and a `reach` (`window`, `os`, `engine-gap`) from `HEADLESS` in `xtask/src/parity.rs` (a path ending in ` > ` covers its submenu), or reads `unknown`. Never write `yes` there. A covered leaf is `yes` whatever its marks say, so a submenu mark stays while any leaf under it is uncovered; drop a mark only once commands cover every leaf it matches (the check then fails on it as stale).
Paths and conventions:
- No crate allows `unsafe` (`unsafe_code = "forbid"` in the workspace).
+1 -9
View File
@@ -22,17 +22,10 @@ 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`. |
@@ -92,12 +85,11 @@ Generated-in-code assets are original and have no file to list:
| `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/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/tr.tsv` | @ogzhnklvz (AI-assisted) | Original Turkish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app reviewed by a native speaker |
| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted); 46 later rows: @V1dalTheAbidal with Claude Code (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the 46 later rows were read by their contributor, a native Greek speaker; independent native proofreading of the whole file pending |
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology 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
+8 -112
View File
@@ -26,29 +26,6 @@ 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"
@@ -401,9 +378,9 @@ dependencies = [
[[package]]
name = "async-executor"
version = "1.14.1"
version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
dependencies = [
"async-task",
"concurrent-queue",
@@ -759,7 +736,6 @@ dependencies = [
"cadcraft-ui-egui",
"chrono",
"clap",
"craft-nightly",
"craft-quit",
"craft-update",
"eframe",
@@ -878,7 +854,7 @@ dependencies = [
name = "cadcraft-io"
version = "0.21.0"
dependencies = [
"acadrust 0.6.6 (git+https://github.com/storytold/acadrust.git?rev=5d5c482b3fcb3dc77e8281474461760f32959436)",
"acadrust",
"cadcraft-color",
"cadcraft-doc",
"cadcraft-fonts",
@@ -982,7 +958,6 @@ dependencies = [
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-bindgen-test",
"web-sys",
]
@@ -1046,12 +1021,6 @@ 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"
@@ -1457,7 +1426,7 @@ name = "craft-dwg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"acadrust 0.6.6 (registry+https://github.com/rust-lang/crates.io-index)",
"acadrust",
"log",
]
@@ -1622,15 +1591,6 @@ dependencies = [
"encoding_rs",
]
[[package]]
name = "craft-nightly"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8945bdb09b36245a1d442438ce8876377ef430d0#8945bdb09b36245a1d442438ce8876377ef430d0"
dependencies = [
"uds_windows",
"winsafe",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
@@ -2763,9 +2723,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
[[package]]
name = "form_urlencoded"
version = "1.2.3"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [
"percent-encoding",
]
@@ -4094,16 +4054,6 @@ 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"
@@ -4303,15 +4253,6 @@ 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"
@@ -4847,12 +4788,6 @@ 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"
@@ -6664,9 +6599,9 @@ dependencies = [
[[package]]
name = "url"
version = "2.5.9"
version = "2.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
dependencies = [
"form_urlencoded",
"idna",
@@ -6879,45 +6814,6 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "wasm-bindgen-test"
version = "0.3.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae7499dfd45780a0a91d7ee6bb9ac51970a4479a41a89da443fdda5a39547d42"
dependencies = [
"async-trait",
"cast",
"js-sys",
"libm",
"minicov",
"nu-ansi-term",
"num-traits",
"oorandom",
"serde",
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-bindgen-test-macro",
"wasm-bindgen-test-shared",
]
[[package]]
name = "wasm-bindgen-test-macro"
version = "0.3.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b84b5ac638bfb168196a1a461fcc8f46a294a18b1b6be52133b4e0db122cc9f"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "wasm-bindgen-test-shared"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f692aa943ccd88363733b77063f32cfed5bc6cbea8e6e8b251b302f881606fe"
[[package]]
name = "wayland-backend"
version = "0.3.17"
-2
View File
@@ -19,7 +19,6 @@ craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "8945bdb09b36245a1d442438ce8876377ef430d0" }
cadcraft-color = { path = "crates/color" }
cadcraft-doc = { path = "crates/doc" }
cadcraft-constraints = { path = "crates/constraints" }
@@ -85,7 +84,6 @@ 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).
+2 -428
View File
@@ -10,435 +10,9 @@ 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) 0.6.6 is licensed under the
crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) 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. 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.
is available from crates.io and the repository above.
CADCraft's icons, drafting font, hatch patterns and linetypes are drawn or defined in code.
+4 -4
View File
@@ -94,9 +94,9 @@
untested, 2018 tested only on synthetic files) open through the open-source acadrust library
and save as 2000 through 2018. New drawings default to
2018 (AC1032) in both formats. In the app's Save dialog, File ▸ Default Save Format
(also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version Save As and
Export write, for opened drawings too; Save (QSAVE) of an opened file keeps its own version,
subject to supported-version mapping and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later
(also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version for untitled
drawings; drawings with a file keep their own version, subject to supported-version mapping
and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later
saves. Export to SVG and PNG today.
- **Fast and native.** Pure Rust and egui, no Electron, no web view. One binary on macOS
(universal), Windows, Linux and FreeBSD, plus a WebAssembly build for the browser.
@@ -120,7 +120,7 @@ numbers):
| Layers & properties | Layers palette and Layer Properties Manager (on/off, freeze, lock, plot, colour, linetype), layer tools (isolate, freeze, off, lock, match, previous), Properties palette with per-object editing, linetypes, lineweights, colour index and true colour |
| Annotation | All DIM* commands with full DIMSTYLE variables, overrides and every arrowhead, associative dimensions that follow geometry, MLEADER, TABLE, TrueType fonts (`.ttf`, `.otf`, `.ttc` collections), MTEXT formatting codes (fonts, heights, colours, stacked fractions), our own single-stroke drafting font |
| Hatch & blocks | Pick-point hatch boundaries with islands, pattern, solid and gradient fills from our own pattern library, BLOCK/INSERT, attributes and nested blocks |
| Files | DXF read (R12–2018, binary from R13) and write (2000–2018, ASCII and binary), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library; R13 and R14 untested, 2018 tested only on synthetic files) and write (2000–2018). New drawings save as 2018 (AC1032); opened drawings keep their supported version, except DWG defaults to at least 2004. In the app's Save dialog, File ▸ Default Save Format (also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version Save As and Export write, for opened drawings too; Save (QSAVE) of an opened file keeps its own version, subject to supported-version mapping and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later saves. DXF uses R2000 structure with the chosen `$ACADVER`. PDF plotting, SVG and PNG export. Entities CADCraft doesn't model yet are not kept on save: see [file-format parity](docs/file-format-parity.md) for version selection and fidelity |
| Files | DXF read (R12–2018, binary from R13) and write (2000–2018, ASCII and binary), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library; R13 and R14 untested, 2018 tested only on synthetic files) and write (2000–2018). New drawings save as 2018 (AC1032); opened drawings keep their supported version, except DWG defaults to at least 2004. In the app's Save dialog, File ▸ Default Save Format (also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version for untitled drawings; drawings with a file keep their own version, subject to supported-version mapping and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later saves. DXF uses R2000 structure with the chosen `$ACADVER`. PDF plotting, SVG and PNG export. Entities CADCraft doesn't model yet are not kept on save: see [file-format parity](docs/file-format-parity.md) for version selection and fidelity |
| Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF |
| Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit |
| Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror |
+12 -17
View File
@@ -2,7 +2,7 @@
**Stage: pre-alpha** · next: alpha, when the six rows of the [alpha gate](docs/roadmap.md#alpha-gate) pass (five fail today; the gate was revised on 2026-11-19 and its hours are not re-estimated yet)
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-12-01 · **Change:** minor (Upcoming updated for what merged from 2026-11-25 to 2026-12-01; previously minor: Upcoming updated for what merged from 2026-11-21 to 2026-11-25; previously minor: Upcoming updated for what merged on 2026-11-19 and 2026-11-20; previously major: alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-25 · **Change:** minor (Upcoming updated for what merged from 2026-11-21 to 2026-11-25; previously minor: Upcoming updated for what merged on 2026-11-19 and 2026-11-20; previously major: alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
CADCraft targets full parity with AutoCAD (2D drafting first, then annotation, layouts and
plotting, DWG, parametrics and 3D), plus what AutoCAD doesn't have: agent control over MCP, a
@@ -84,8 +84,8 @@ Hours are Opus 5.5 agent wall-clock hours, calibrated on this repo's own build:
## Languages
AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus twenty catalogs
(Ukrainian, Brazilian Portuguese, German, Spanish, Czech, Russian, French, Simplified Chinese, Italian, Korean, Swedish, Arabic, Greek, Hungarian, Turkish, Bosnian, Georgian, Vietnamese, Polish and Tamil; Tamil needs an installed Tamil font or a build with the craft-fonts face, and without one the interface stays in English). Detail: [localization-parity.md](docs/localization-parity.md).
AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus eighteen catalogs
(Ukrainian, Brazilian Portuguese, German, Spanish, Czech, Russian, French, Simplified Chinese, Italian, Korean, Swedish, Arabic, Greek, Hungarian, Turkish, Bosnian, Georgian and Vietnamese). Detail: [localization-parity.md](docs/localization-parity.md).
| Language | Status | UI translated |
|---|---|---:|
@@ -103,7 +103,7 @@ AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus tw
| Korean | partial | 1,235 catalog rows |
| Vietnamese | partial | 1,460 catalog rows (2026-11-07); native review pending |
Other languages shipped: Ukrainian (1,357 rows, the reference catalog, #36), Czech (1,215), Russian (1,005), Italian (1,352), Swedish (1,382), Hungarian (1,326) and Turkish (1,330), counted 2026-10-24; engine messages stay English. Since those counts Polish (#218) and Tamil (#3105) landed and the Russian (#3378), Czech (#1579) and Vietnamese (#3500) catalogs were brought up to date; the counts here are not redone. Every catalog but Ukrainian's has strings added since it landed that still fall back to English: 6 (Italian, Swedish) to 296 (French) per `cargo xtask i18n` ([localization-parity.md](docs/localization-parity.md)).
Other languages shipped: Ukrainian (1,357 rows, the reference catalog, #36), Czech (1,215), Russian (1,005), Italian (1,352), Swedish (1,382), Hungarian (1,326) and Turkish (1,330), counted 2026-10-24; engine messages stay English. Every catalog but Ukrainian's has strings added since it landed that still fall back to English: 6 (Italian, Swedish) to 296 (French) per `cargo xtask i18n` ([localization-parity.md](docs/localization-parity.md)).
## Upcoming
@@ -112,18 +112,16 @@ already written and waiting in a pull request lands before new work starts, whoe
and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
**1. Urgent: security fixes, leaks, crashes and lost work.**
- The open findings of the security audit (#1922, #1925, #1931, #1932 and #1935 of #1919–#1935; the others are closed): check each against the input limits that
- The open findings of the security audit (#1919–#1935): check each against the input limits that
landed on 2026-11-11, close what is fixed and fix the rest. A crafted handle that makes new entities
overwrite existing ones (#1921) is fixed by #1276.
- A saved file that crashes AutoCAD 2021 (#3303); dimension text lost on save (#3299) was fixed on 2026-11-20.
- Crashes and hangs with a reproduction: the web build on a large DXF (#1603; bounded by #3594 and
#3622, still open), a DWG with 3D content (#2174), startup on older graphics hardware (#1724, #1631,
#3222).
- Crashes and hangs with a reproduction: the web build on a large DXF (#1603), a DWG with 3D content
(#2174), startup on older graphics hardware (#1724, #1631, #3222).
**2. Parity with AutoCAD: the alpha gate rows, then the beta checklist (apart from its items named under tier 3).**
- It starts on common hardware: the automatic fallback renderer landed (#3685; `CADCRAFT_STENCIL=0`
is the manual switch since #3336); waiting for the reporters to confirm, and older Intel Macs (#1631,
#2146) are not covered.
- It starts on common hardware: an automatic fallback renderer (`CADCRAFT_STENCIL=0` is the manual
switch since #3336).
- It opens the DWG and DXF files people already have: large files (#3102, #2633, #1088), layouts and
paper units (#1672, #2836), and a corpus of real files run in CI.
- Saving loses nothing and other CAD programs open the result (#2904, #1687, #3234, #2632).
@@ -133,18 +131,16 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
- The prompt options that still say "not available yet" (gaps F1).
- Layouts print at scale on a system printer (#3216); the menu bar and panels can be restored since
#3308.
- 586 pull requests are open (2026-12-01; 602 on 2026-11-25). About 230 were mergeable, passed CI and were small; they are
- 602 pull requests are open (2026-11-25; 661 on 2026-11-20). About 230 were mergeable, passed CI and were small; they are
reviewed and landed in this order, the longest-waiting authors first within a row.
**3. Lower priority: affects fewer people and nothing breaks without it.**
- Dynamic-block authoring, the leftovers of editing an xref in place (landed in #3352), exact ellipse
and spline geometry, correct polyline offsets.
- Dynamic-block authoring, editing an xref in place, exact ellipse and spline geometry, correct
polyline offsets.
- Prompt options that need 3D (DVIEW's camera options, -RENAME Material); 3D itself comes after 1.0,
but a file with 3D content must open safely (tier 1).
- Menu breadth against AutoCAD for Mac as a headline number.
Done from 2026-11-25 to 2026-12-01: REFEDIT, REFSET and REFCLOSE on xrefs, writing the xref's drawing back in the version it was read in (#2355 in #3352; not on the web); an automatic fallback renderer when the graphics can't start (#3685 in #3692; not yet confirmed by the reporters, and older Intel Macs are not covered); TRIM highlights only the part a click removes and EXTEND what it adds, and EXTRIM (#3382, #2808 in #3471; follow-ups #3526 in #3690); SCALE Reference Points and Copy, and grip Scale of text heights (#3288 in #3472); QLEADER at the command line (#2740; its Settings dialog is not available yet); OFFSETGAPTYPE (#1506); FILLET and CHAMFER with two polylines and with middle, closed and arc segments (#1223); prompts and results of COPY, JOIN, PEDIT, RECTANG, STRETCH, PLINE, SPLINE, SPLINEDIT, ARRAY, ARRAYPATH, DIVIDE, INSERT and MINSERT brought closer to AutoCAD's (#2726, #2725, #2906, #2790, #2204, #2209, #2205, #2699, #2703, #2705, #2772, #2778, #2761, #2762, #2774, #2782, #2780, #2784, #2766, #2789); spreadsheet text pasted as a TABLE (#3290 in #3470), with wrapped cell text and Enter to repeat (#3584, #3587 in #3690); GROUPDISPLAYMODE, group copies and draw order across every layout (#2152); New Layout from Area (#2080); drawing locks and WHOHAS, which say when a drawing is open elsewhere (#1018, part of #540); REVCLOUD arcs that other readers recognise as a cloud (#1692); hatches by internal point that keep their arcs (#1474); `\X` dimension text below the line (#1084); JIS and Japanese paper sizes (#1810); a translucent fill in the AREA preview (#1303); selection through a viewport that leaves out block parts on its frozen layers (#3214 in #3692); saves that keep covered cell text, WIPEOUTFRAME, LAYOUT flags, VPORT group 72, attributes on layer 0 and DIMLFAC measurements (#3520, #3611, #3668, #3670, #3613 in #3689; #3540 in #3692), and RENAME that keeps foreign data (#1020); the web build's display list, selection highlight and plot style outlines bounded (#3594, #3622 in #3692; #1603 stays open); hostile-input fixes toward the security audit (#3482, #3491, #3536 for #1923; #3610, #3647 for #1922; #3588 for #1925; #3609 for #1935; #3484, #3539, #3562, #3590 for quadratic-time opens); LISP and script fixes (#3519, #3572, #3576, #3642, #3646, #3651); the move to the shared UI framework, with floating palettes as OS windows and Ctrl+= and Ctrl+- for the interface scale (#3449); the Tamil catalog (#3105 in #3470) and the Russian, Czech and Vietnamese catalogs brought up to date (#3378, #1579, #3500).
Done from 2026-11-21 to 2026-11-25: PDFIMPORT, a PDF page as editable lines, polylines, solid hatches and text (#3375 in #3419); dynamic block references that rotate, flip, array, scale, stretch polar, align and look up, with their grips (#963, #993, #1030, #1098, #1699, #1723, #1752 in #3424; authoring is still open); the proxy graphics of other applications' objects drawn (#2697, #3435, #3437) and dimensions kept as read drawn from their `*D` block (#3439); saves that keep layout plot settings (#3233, #3386, #3390), DXF 2007+ table cell text (#3392), hatch boundary flags (#3389), fit text (#3391) and registered applications (#2918); the Array window for ARRAYRECT and ARRAYPOLAR (#3394); ATTDIA and the Edit Attributes dialog on INSERT (#3411) and constant attribute values drawn (#3462); Edit > Paste from the system clipboard (#3366, #3460, #3461; #3320 open); opening from Finder and quit prompts on macOS (#1347 in #3344, not yet run on a Mac); an already-open drawing selects its tab when opened from the interface (#899 in #3422; the control channel, MCP, scripts and LISP still open a second copy); Tab through every object snap candidate (#1673); the Write Block dialog for WBLOCK (#1778); Generate Boundary (#2804); mitred wide polylines (#3453; the extents leave out the mitre tip, #3443); DIMASSOC 1 (#2977); crossing selection of block references by what they draw (#3445); an option to turn off the update check (#3097).
Done on 2026-11-19 and 2026-11-20: the hostile-input fixes #1276, #2820, #2821 and #2765 (#3304, #3305), clicks while the mouse moves and right-click or Space as Enter (#3307), the interface reset (#3308), paper units (#3309), the UCS command (#3310), -ATTEDIT, -RENAME and -LAYER options (#3311), TRIM/EXTEND depth (#3312), dimension values kept on save (#3335), the stencil switch (#3336), a typed OPEN path (#3343) and double-click text editing (#3345).
@@ -176,7 +172,6 @@ REFEDIT (#818), XCLIP (#2354), dynamic block references (#838–#883), and the D
| Date | Change | Summary |
|---|---|---|
| 2026-12-01 | minor | Upcoming updated for the merges of 2026-11-25 to 2026-12-01 (REFEDIT on xrefs, the automatic fallback renderer, TRIM/EXTEND highlight and EXTRIM, SCALE Reference, QLEADER, OFFSETGAPTYPE, FILLET/CHAMFER with polylines, spreadsheet paste as a TABLE, groups and draw order, New Layout from Area, drawing locks and WHOHAS, what saves keep, web display-list bounds, security-audit fixes, the shared UI framework); languages list now twenty catalogs (Polish, Tamil); pull-request count 602 → 586; percentages and hours not re-scored |
| 2026-11-25 | minor | Upcoming updated for the merges of 2026-11-21 to 2026-11-25 (PDF import, dynamic block reference actions, proxy graphics, what saves keep, Array window, ATTDIA, system clipboard paste, macOS opening from Finder, WBLOCK dialog, Generate Boundary); #3299 fixed; pull-request count 661 → 602; percentages and hours not re-scored |
| 2026-11-20 | minor | Upcoming updated for the merges of 2026-11-19 and 2026-11-20 (security stacks, input, interface reset, paper units, UCS, prompt options, TRIM/EXTEND, text editing in place); pull-request count 714 → 661; percentages and hours not re-scored |
| 2026-11-19 | major | Alpha gate revised from user reports (six rows, Windows first; block authoring, xref editing in place and exact curve geometry moved to beta); Upcoming re-ranked into three tiers: urgent (security, leaks, crashes, lost work), parity, lower priority; percentages and hours not re-scored |
+1 -1
View File
@@ -66,7 +66,7 @@ fn convert_long_about() -> &'static str {
/// cadcraft-cli: headless CADCraft
#[derive(Parser)]
#[command(name = "cadcraft-cli", version = cadcraft_engine::build_version(), propagate_version = true, arg_required_else_help = true)]
#[command(name = "cadcraft-cli", version = cadcraft_engine::build_version(), arg_required_else_help = true)]
pub(crate) struct Cli {
#[command(subcommand)]
pub(crate) command: Command,
-8
View File
@@ -45,12 +45,6 @@ fn install_io() {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
@@ -61,8 +55,6 @@ fn install_io() {
groups: cadcraft_io::entity_groups,
entity: cadcraft_io::entity_from_groups,
});
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record);
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
+1 -5
View File
@@ -145,14 +145,10 @@ pub(crate) fn export(s: &Session, out: &Path, io: &mut Streams) -> Result {
pub(crate) fn export_framed(s: &Session, out: &Path, window: Option<Bounds2>, io: &mut Streams) -> Result {
let d = s.doc()?;
let (bytes, notes) = cadcraft_io::write_framed_noted(d, out, window)?;
let bytes = cadcraft_io::write_framed(d, out, window)?;
let folder = write_atomic(out, &bytes)?;
report_new_folder(folder, io);
io.errln(format_args!("wrote {} ({} bytes)", out.display(), bytes.len()));
// What the image draws short of the drawing (dashed runs past a dash limit drawn continuous).
for note in notes {
io.errln(format_args!("{}: {note}", out.display()));
}
if cadcraft_engine::cmd::file::drops_unknown(out) {
let lost = cadcraft_engine::cmd::file::not_saved(d);
if let Some(m) = cadcraft_engine::cmd::file::not_saved_message(&lost) {
-2
View File
@@ -66,8 +66,6 @@ fn synthetic(n: usize, side: f64) -> Result<cadcraft_engine::doc::Drawing, cadcr
style: "Standard".into(),
halign: d::HAlign::Left,
valign: d::VAlign::Baseline,
backwards: false,
upside_down: false,
}),
};
dr.add(&Space::Model, Common::default(), kind)?;
@@ -1,406 +0,0 @@
//! An INSERT's ATTRIBs and SEQEND reached from AutoLISP through the CLI (`entnext`, `entget`,
//! `entmod`, `entdel`): the walk, a value edit (one Undo step), names that stop holding (erase,
//! ATTSYNC, Undo, a reinsert that reuses the parent handle), edits that are refused, and the
//! name bounds.
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use serde_json::{Value, json};
/// A scratch directory, removed on drop also when an assertion fails.
struct Dir(PathBuf);
impl Dir {
fn new(tag: &str) -> Dir {
let p = std::env::temp_dir().join(format!("cc-cli-attribs-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&p);
std::fs::create_dir_all(&p).expect("create scratch dir");
Dir(p)
}
fn path(&self, name: &str) -> PathBuf {
self.0.join(name)
}
}
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// One `cadcraft-cli run`: a fresh profile, an optional drawing to open, and the steps to run.
struct Run {
args: Vec<String>,
}
impl Run {
fn new(dir: &Dir, file: Option<&Path>) -> Run {
let mut args: Vec<String> = vec!["run".into(), "--config-dir".into(), dir.path("profile").to_string_lossy().into_owned()];
match file {
Some(f) => args.push(f.to_string_lossy().into_owned()),
None => args.push("--metric".into()),
}
Run { args }
}
fn cmd(&mut self, id: &str, params: Value) -> &mut Run {
self.args.push("--cmd".into());
self.args.push(format!("{id} {params}"));
self
}
fn lisp(&mut self, code: &str) -> &mut Run {
self.cmd("lisp", json!({ "code": code }))
}
fn save(&mut self, path: &Path) -> &mut Run {
self.args.push("--save".into());
self.args.push(path.to_string_lossy().into_owned());
self
}
fn output(&self) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(&self.args).output().expect("run cadcraft-cli")
}
/// Run it: the value each `lisp` step returned, in order (commands' own results are left out).
fn out(&self) -> Vec<Value> {
let out = self.output();
let err = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "{}: {}", self.args.join(" "), err);
let text = String::from_utf8_lossy(&out.stdout);
text.lines()
.map(|l| serde_json::from_str::<Value>(l).unwrap_or_else(|e| panic!("not a result: {l}: {e}")))
.filter(|v| v.get("value").is_some())
.collect()
}
}
/// The value a `lisp` step returned, as AutoLISP's `prin1` shows it.
fn value(results: &[Value], i: usize) -> String {
match results.get(i).and_then(|r| r.get("value")) {
Some(Value::String(s)) => s.clone(),
other => panic!("step {i}: no value: {other:?} in {results:?}"),
}
}
/// `value` without the quotes `prin1` puts round a string.
fn text(results: &[Value], i: usize) -> String {
value(results, i).trim_matches('"').to_string()
}
/// TAGBLK.dxf: block TAGBLK with a circle and four attribute definitions (TAG1 D1, TAG2 D2
/// verify, TAG3 P3 preset, TAG4 C4 constant). Opening the file again gives the drawing fresh
/// names.
const FIXTURE: &str = r#"(progn
(entmake '((0 . "BLOCK") (2 . "TAGBLK") (70 . 2) (10 0.0 0.0 0.0)))
(entmake '((0 . "CIRCLE") (10 -5.0 0.0 0.0) (40 . 2.0)))
(entmake '((0 . "ATTDEF") (10 0.0 0.0 0.0) (40 . 2.5) (1 . "D1") (3 . "P1") (2 . "TAG1") (70 . 0)))
(entmake '((0 . "ATTDEF") (10 0.0 5.0 0.0) (40 . 2.5) (1 . "D2") (3 . "P2") (2 . "TAG2") (70 . 4)))
(entmake '((0 . "ATTDEF") (10 0.0 10.0 0.0) (40 . 2.5) (1 . "P3") (3 . "P3") (2 . "TAG3") (70 . 8)))
(entmake '((0 . "ATTDEF") (10 0.0 15.0 0.0) (40 . 2.5) (1 . "C4") (3 . "P4") (2 . "TAG4") (70 . 2)))
(entmake '((0 . "ENDBLK"))))"#;
/// The first reference: INSERT TAGBLK at (10,10) with TAG1 "A1", TAG2 verified as "B1" and
/// TAG3 preset ("P3"); TAG4 is constant, so it is not asked.
const INSERT: &str = r#"(command "_.-INSERT" "TAGBLK" '(10 10) 1 1 0 "A1" "B1" "")"#;
fn fixture(dir: &Dir) -> PathBuf {
let file = dir.path("TAGBLK.dxf");
let mut run = Run::new(dir, None);
let out = run.lisp(FIXTURE).save(&file).out();
assert_eq!(text(&out, 0), "TAGBLK");
file
}
/// The walk from the entity named `i`: its records' tags and values, then the type of the record
/// that ends the run.
const WALK: &str = r#"(progn
(setq e (entnext i) n 0 ts nil ed nil)
(while (and e (= "ATTRIB" (cdr (assoc 0 (setq ed (entget e))))))
(setq ts (append ts (list (cdr (assoc 2 ed)) (cdr (assoc 1 ed)))) n (1+ n) e (entnext e)))
(list n ts (cdr (assoc 0 ed))))"#;
#[test]
fn the_walk_reaches_each_attrib_and_ends_at_the_seqend() {
let dir = Dir::new("walk");
let file = fixture(&dir);
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(&format!(
r#"(progn
{INSERT}
(setq i (entlast))
(setvar "ATTREQ" 0)
(command "_.-INSERT" "TAGBLK" '(60 10) 1 1 0)
(setvar "ATTREQ" 1)
(setq second (entlast))
"inserted")"#
))
// Three attributes, then the SEQEND owned by the reference, then the next main entity.
.lisp(&format!(
r#"(progn {WALK}
(list n ts (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i) (equal (entnext e) second) (cdr (assoc 0 (entget (entnext e))))))"#
))
// The second reference (no attribute answers, ATTREQ 0) took the definitions' values; its
// own run ends at its SEQEND, with nothing drawn after it.
.lisp(&format!(
r#"(progn (setq i second) {WALK}
(list n ts (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i) (entnext e)))"#
))
.out();
assert_eq!(text(&out, 0), "inserted");
assert_eq!(value(&out, 1), "(3 (\"TAG1\" \"A1\" \"TAG2\" \"B1\" \"TAG3\" \"P3\") \"SEQEND\" T T \"INSERT\")");
// Its record ends with its own SEQEND, and nothing is drawn after the reference.
assert_eq!(value(&out, 2), "(3 (\"TAG1\" \"D1\" \"TAG2\" \"D2\" \"TAG3\" \"P3\") \"SEQEND\" T nil)");
}
#[test]
fn a_value_edit_changes_group_one_only_and_is_one_undo_step() {
let dir = Dir::new("value");
let file = fixture(&dir);
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (list (cdr (assoc 2 (entget a))) (cdr (assoc 1 (entget a)))))"#))
.lisp(
r#"(progn
(setq d (entget a) r (entmod (subst (cons 1 "A2") (assoc 1 d) d)))
(list (cdr (assoc 0 r)) (cdr (assoc 1 r)) (cdr (assoc 1 (entget a))) (cdr (assoc 2 (entget a)))
(cdr (assoc 40 (entget a))) (cdr (assoc 8 (entget a))) (equal (cdr (assoc -2 (entget a))) i)))"#,
)
.cmd("undo", json!({ "count": 1 }))
// The edit is one Undo step: the value is back, and the name given before it holds no
// longer (the drawing it was given in was restored from another state).
.lisp(
r#"(list (entget a) (progn (setq e (entnext (entlast)))
(list (cdr (assoc 2 (entget e))) (cdr (assoc 1 (entget e))))))"#,
)
.out();
assert_eq!(value(&out, 0), "(\"TAG1\" \"A1\")");
assert_eq!(value(&out, 1), "(\"ATTRIB\" \"A2\" \"A2\" \"TAG1\" 2.5 \"0\" T)");
assert_eq!(value(&out, 2), "(nil (\"TAG1\" \"A1\"))");
// Redo brings the edit back; the name given before the Undo still names nothing.
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i) d (entget a)) (entmod (subst (cons 1 "A2") (assoc 1 d) d)))"#))
.cmd("undo", json!({ "count": 1 }))
.cmd("redo", json!({ "count": 1 }))
.lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))")
.out();
assert_eq!(value(&out, 1), "(nil \"A2\")");
}
#[test]
fn a_name_stops_holding_after_erase_attsync_and_undo() {
let dir = Dir::new("stale");
let file = fixture(&dir);
let mut run = Run::new(&dir, Some(&file));
let out = run.lisp(&format!(r#"(progn {INSERT} (setq i (entlast)) (cdr (assoc 5 (entget i))))"#)).out();
let handle = text(&out, 0);
// Erased: the reference's records are gone with it, and the name names nothing.
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (cdr (assoc 2 (entget a))))"#))
.cmd("erase", json!({ "handles": [handle] }))
.lisp("(list (entget a) (entnext a))")
// Undone: the reference is back, but a name given before the Undo does not come back with
// it: a walk gives its records new ones.
.cmd("undo", json!({ "count": 1 }))
.lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))")
// ATTSYNC rebuilds the reference's attributes: the name given before names nothing, and
// the rebuilt attribute keeps the value.
.lisp("(progn (setq b (entnext (entlast))) (cdr (assoc 2 (entget b))))")
.cmd("attsync", json!({ "name": "TAGBLK" }))
.lisp("(list (entget b) (cdr (assoc 1 (entget (entnext (entlast))))))")
.out();
assert_eq!(value(&out, 0), "\"TAG1\"");
assert_eq!(value(&out, 1), "(nil nil)");
assert_eq!(value(&out, 2), "(nil \"A1\")");
assert_eq!(value(&out, 3), "\"TAG1\"");
assert_eq!(value(&out, 4), "(nil \"A1\")");
// A reinsert after an Undo takes the parent handle back: the old name must not name its
// attribute.
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (list (cdr (assoc 5 (entget i))) (cdr (assoc 2 (entget a)))))"#))
.cmd("undo", json!({ "count": 1 }))
.lisp(&format!(r#"(progn {INSERT} (list (cdr (assoc 5 (entget (entlast)))) (entget a)))"#))
.lisp("(list (cdr (assoc 2 (entget (entnext (entlast))))) (cdr (assoc 1 (entget (entnext (entlast))))))")
.out();
assert_eq!(text(&out, 0), format!("(\"{handle}\" \"TAG1\")"));
// The same handle, and the old name names nothing in the new reference.
assert_eq!(value(&out, 1), format!("(\"{handle}\" nil)"));
assert_eq!(value(&out, 2), "(\"TAG1\" \"A1\")");
}
#[test]
fn an_edit_of_anything_but_the_value_is_refused() {
let dir = Dir::new("refused");
let file = fixture(&dir);
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(&format!(
r#"(progn {INSERT} (setq i (entlast) a (entnext i) s (entnext (entnext (entnext a))) p0 (cdr (assoc 10 (entget a)))) "named")"#
))
.lisp(
r#"(progn
(setq d (entget a))
(list
(entmod (subst (cons 2 "TAGX") (assoc 2 d) d))
(entmod (subst (cons 40 9.0) (assoc 40 d) d))
(entmod (subst (cons 0 "SEQEND") (assoc 0 d) d))
(entmod (entget s))
(entmod (subst (cons 410 "Layout2") (assoc 410 d) d))
(entmod (subst (cons 1 "A2") (assoc 1 d) (subst (cons 410 "Layout2") (assoc 410 d) d)))
(entdel a) (entdel s)))"#,
)
// Nothing changed: the same tag, value, height and place, and the name still holds.
.lisp(
r#"(progn (setq e (entnext (entlast)) d (entget e))
(list (cdr (assoc 2 d)) (cdr (assoc 1 d)) (cdr (assoc 40 d)) (equal p0 (cdr (assoc 10 d))) (equal (entget a) d)))"#,
)
.out();
assert_eq!(text(&out, 0), "named");
assert_eq!(value(&out, 1), "(nil nil nil nil nil nil nil nil)");
assert_eq!(value(&out, 2), "(\"TAG1\" \"A1\" 2.5 T T)");
}
/// A minimal drawing: `before` (records written as they are), then an INSERT with `attribs`
/// ATTRIBs (each tag T, value V) and its SEQEND, last in the file. A header `$HANDSEED` is
/// written when `handseed` is given (a hostile file can name any next handle).
fn insert_dxf_seed(attribs: usize, before: &str, handseed: Option<&str>) -> String {
let mut s = String::with_capacity(before.len().saturating_add(attribs.saturating_mul(96)));
if let Some(seed) = handseed {
s.push_str("0\nSECTION\n2\nHEADER\n9\n$HANDSEED\n5\n");
s.push_str(seed);
s.push('\n');
s.push_str("0\nENDSEC\n");
}
s.push_str("0\nSECTION\n2\nENTITIES\n");
s.push_str(before);
s.push_str("0\nINSERT\n5\n20\n8\n0\n66\n1\n2\nTAGBLK\n10\n0\n20\n0\n30\n0\n");
for _ in 0..attribs {
s.push_str("0\nATTRIB\n5\n21\n8\n0\n10\n0\n20\n0\n30\n0\n40\n1\n1\nV\n2\nT\n70\n0\n");
}
s.push_str("0\nSEQEND\n5\n22\n0\nENDSEC\n0\nEOF\n");
s
}
fn insert_dxf(attribs: usize, before: &str) -> String {
insert_dxf_seed(attribs, before, None)
}
/// The number of records a walk from `i` reaches, counting each `entnext`.
const COUNT: &str = r#"(progn (setq e (entnext i) n 0) (while e (setq n (1+ n) e (entnext e))) n)"#;
#[test]
fn a_walk_is_stable_and_its_names_are_no_handles() {
let dir = Dir::new("stable");
// A file's line one below the top of the handle range: it keeps its handle, and the
// records' names, which are no handles, never name it.
let before = "0\nLINE\n5\nFFFFFFFFFFFFFFFE\n8\n0\n10\n0\n20\n0\n30\n0\n11\n5\n21\n5\n31\n0\n";
let file = dir.path("hostile.dxf");
std::fs::write(&file, insert_dxf(2, before)).expect("write the DXF");
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(
r#"(progn
(setq i (handent "20") line (handent "FFFFFFFFFFFFFFFE") a (entnext i) b (entnext i))
(list (cdr (assoc 5 (entget line))) (equal (handent "FFFFFFFFFFFFFFFE") line)
(not (equal a line)) (cdr (assoc 0 (entget a))) (equal a b) (equal (entnext a) (entnext b))))"#,
)
.lisp(&format!(r#"(progn (setq i (handent "20")) {COUNT})"#))
.out();
assert_eq!(value(&out, 0), "(\"FFFFFFFFFFFFFFFE\" T T \"ATTRIB\" T T)");
// Two ATTRIBs and the SEQEND, then the line (it sorts last by its handle), then the end.
assert_eq!(value(&out, 1), "4");
}
#[test]
fn a_restored_reference_does_not_revive_an_old_name() {
let dir = Dir::new("restored");
let file = fixture(&dir);
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(&format!(
r#"(progn {INSERT} (setq i (entlast) a (entnext i))
(entdel i)
(setq gone (entget a))
(entdel i)
(list gone (entget a) (cdr (assoc 1 (entget (entnext i))))))"#
))
.out();
assert_eq!(value(&out, 0), "(nil nil \"A1\")", "the reference comes back, the old name does not");
// ERASE, then OOPS: the same. The old name never comes back with the reference.
let mut run = Run::new(&dir, Some(&file));
let handle = text(&run.lisp(&format!(r#"(progn {INSERT} (cdr (assoc 5 (entget (entlast)))))"#)).out(), 0);
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(&format!(r#"(progn {INSERT} (setq a (entnext (entlast))) "named")"#))
.cmd("erase", json!({ "handles": [handle] }))
.cmd("oops", json!({}))
.lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))")
.out();
assert_eq!(value(&out, 1), "(nil \"A1\")", "OOPS restores the reference, not the old name");
}
#[test]
fn a_new_line_is_never_a_record() {
let dir = Dir::new("handseed");
let file = dir.path("hostile.dxf");
// A file's $HANDSEED in the reserved band is the file's own handle and is not followed (#913),
// so the line made after the walk gets the drawing's seed. The record's name is no handle:
// the line is the line, and the name still names the attribute. The engine's
// `a_new_object_at_any_handle_is_never_a_record` puts the seed at the top of the range.
std::fs::write(&file, insert_dxf_seed(1, "", Some("FFFFFFFFFFFFFFFF"))).expect("write the DXF");
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(r#"(progn (setq i (handent "20") a (entnext i)) (list (cdr (assoc 0 (entget a))) (cdr (assoc 5 (entget (entlast))))))"#)
.lisp(r#"(progn (entmake '((0 . "LINE") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (cdr (assoc 5 (entget (entlast)))))"#)
.lisp(r#"(list (cdr (assoc 0 (entget a))) (entdel a))"#)
.out();
assert_eq!(value(&out, 0), "(\"ATTRIB\" \"20\")");
assert_eq!(value(&out, 1), "\"100\"");
assert_eq!(value(&out, 2), "(\"ATTRIB\" nil)");
}
#[test]
fn lines_at_the_top_of_the_handle_range_walk_as_lines() {
let dir = Dir::new("walkrange");
let file = dir.path("hostile.dxf");
let before = "0\nLINE\n5\nFFFFFFFFFFFFFFFE\n8\n0\n10\n0\n20\n0\n30\n0\n11\n5\n21\n5\n31\n0\n\
0\nLINE\n5\nFFFFFFFFFFFFFFFF\n8\n0\n10\n0\n20\n0\n30\n0\n11\n6\n21\n6\n31\n0\n";
std::fs::write(&file, insert_dxf_seed(1, before, Some("FFFFFFFFFFFFFFFF"))).expect("write the DXF");
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(r#"(progn (setq i (handent "20")) (entnext i))"#)
// The line at the top of the range is in the drawing. Without it, the walk from the line
// below would end in nil, and nil equals the nil `handent` gives for a handle not there.
.lisp(r#"(progn (setq top (handent "FFFFFFFFFFFFFFFF")) (list (cdr (assoc 0 (entget top))) (cdr (assoc 5 (entget top)))))"#)
.lisp(r#"(equal (entnext (handent "FFFFFFFFFFFFFFFE")) top)"#)
.lisp("(entnext top)")
.out();
assert_eq!(value(&out, 1), "(\"LINE\" \"FFFFFFFFFFFFFFFF\")");
assert_eq!(value(&out, 2), "T");
assert_eq!(value(&out, 3), "nil");
}
#[test]
fn the_session_names_at_most_65536_records() {
let dir = Dir::new("names");
let file = dir.path("many.dxf");
// One more attribute than the limit of names: the walk stops at the limit, and nothing in the
// drawing changed.
std::fs::write(&file, insert_dxf(65_537, "")).expect("write the DXF");
let mut run = Run::new(&dir, Some(&file));
let out = run.lisp(&format!("(progn (setq i (entlast)) {COUNT})")).lisp(&format!("(progn (setq i (entlast)) {COUNT})")).out();
assert_eq!(value(&out, 0), "65536");
// The names given by the first walk hold: the second walk is the same.
assert_eq!(value(&out, 1), "65536");
}
@@ -1,144 +0,0 @@
//! `convert` to an image says how many dashed runs it drew continuous because of a dash limit
//! (#1069): a line whose DASHED pattern repeats past what one run may be laid out over. A line of
//! 50,001 periods, which an export keeps dashed, gets no note.
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A DXF of one line `periods` DASHED (0.5, -0.25) periods long.
fn dashed_line(periods: f64) -> String {
format!(
"0
SECTION
2
TABLES
0
TABLE
2
LTYPE
70
1
0
LTYPE
2
DASHED
70
0
3
Dashed
72
65
73
2
40
0.75
49
0.5
74
0
49
-0.25
74
0
0
ENDTAB
0
ENDSEC
0
SECTION
2
ENTITIES
0
LINE
8
0
6
DASHED
10
0
20
0
11
{}
21
0
0
ENDSEC
0
EOF
",
periods * 0.75
)
}
#[test]
fn convert_to_an_image_notes_dashed_runs_drawn_continuous_past_the_dash_limit() {
let dir = std::env::temp_dir().join(format!("cc-cli-dash-limit-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
// (1,000,001 + 2) periods × 2 elements: past the two million one run may be laid out over.
let long = dir.join("long.dxf");
std::fs::write(&long, dashed_line(1_000_001.0)).unwrap();
let control = dir.join("control.dxf");
std::fs::write(&control, dashed_line(50_001.0)).unwrap();
let notes = |out: &Output| {
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stderr).lines().filter(|l| l.contains("drawn continuous")).map(str::to_string).collect::<Vec<_>>()
};
for ext in ["png", "svg", "pdf"] {
let image = dir.join(format!("long.{ext}"));
let image = image.to_str().unwrap();
let got = notes(&cli(&["convert", long.to_str().unwrap(), image]));
assert!(matches!(got.as_slice(), [note] if note.starts_with(&format!("{image}: 1 dashed run "))), "{ext}: {got:?}");
let got = notes(&cli(&["convert", control.to_str().unwrap(), dir.join(format!("control.{ext}")).to_str().unwrap()]));
assert!(got.is_empty(), "{ext}: {got:?}");
}
// A DXF copy draws nothing, so there is nothing to note.
assert!(notes(&cli(&["convert", long.to_str().unwrap(), dir.join("copy.dxf").to_str().unwrap()])).is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
/// The engine's commands that write an image say it too, on the command line and in the result's
/// `warnings`: EXPORT, PLOT (PDF, PNG, SVG, to a file or as data), QSAVE and SAVEAS to an image and
/// `document.bytes`.
#[test]
fn image_commands_warn_about_dashed_runs_drawn_continuous() {
let dir = std::env::temp_dir().join(format!("cc-cli-dash-limit-cmds-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let out = |name: &str| serde_json::to_string(dir.join(name).to_str().unwrap()).unwrap();
let cmds = [
format!("export {{\"path\": {}}}", out("export.png")),
format!("plot {{\"path\": {}}}", out("plot.pdf")),
format!("plot {{\"path\": {}, \"output\": \"png\", \"resolution\": 50}}", out("plot.png")),
format!("plot {{\"path\": {}, \"output\": \"svg\"}}", out("plot.svg")),
format!("saveas {{\"path\": {}}}", out("saved.svg")),
format!("qsave {{\"path\": {}}}", out("saved.pdf")),
"plot {\"output\": \"svg\"}".to_string(),
"document.bytes {\"format\": \"pdf\"}".to_string(),
format!("saveas {{\"path\": {}, \"version\": 2018}}", out("versioned.png")),
];
for (periods, warned) in [(1_000_001.0, true), (50_001.0, false)] {
let input = dir.join(format!("line-{periods}.dxf"));
std::fs::write(&input, dashed_line(periods)).unwrap();
let mut args = vec!["run".to_string(), input.to_str().unwrap().to_string()];
for c in &cmds {
args.extend(["--cmd".to_string(), c.clone()]);
}
let run = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(&args).output().unwrap();
assert!(run.status.success(), "{:?}: {}", run.status, String::from_utf8_lossy(&run.stderr));
let results: Vec<serde_json::Value> = String::from_utf8_lossy(&run.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(results.len(), cmds.len(), "{results:?}");
for (c, r) in cmds.iter().zip(&results) {
let notes: Vec<&str> = r["warnings"].as_array().into_iter().flatten().filter_map(|w| w.as_str()).collect();
let noted = matches!(notes.as_slice(), [n] if n.starts_with("1 dashed run ") && n.contains("drawn continuous"));
assert_eq!(noted, warned, "{periods} periods, {c}: {r}");
assert_eq!(r.get("warnings").is_some(), warned, "{periods} periods, {c}: {r}");
}
// Said on the command line once for each command.
let echoed = String::from_utf8_lossy(&run.stderr).lines().filter(|l| l.starts_with("1 dashed run ")).count();
assert_eq!(echoed, if warned { cmds.len() } else { 0 }, "{}", String::from_utf8_lossy(&run.stderr));
}
let _ = std::fs::remove_dir_all(&dir);
}
-43
View File
@@ -1,43 +0,0 @@
//! A LISP routine in a `run` script runs to its end before the script goes on and the drawing is
//! saved, however many slices it takes (#3635).
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A fresh scratch directory that is removed on drop, also when an assertion fails.
struct Scratch(std::path::PathBuf);
impl Scratch {
fn new(tag: &str) -> Self {
let dir = std::env::temp_dir().join(format!("cc-cli-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir(&dir).expect("create scratch dir");
Scratch(dir)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// The loop takes many slices: the circle drawn after it is in the saved drawing, and the next
/// line runs once the routine has ended.
#[test]
fn a_long_routine_in_a_script_draws_before_the_save() {
let scratch = Scratch::new("lisp-script");
let saved = scratch.0.join("out.dxf");
let saved = saved.to_str().unwrap();
let script = r#"(progn (repeat 1000000 (setq x 1)) (command "circle" "0,0" "5") (princ "done"))\n(princ (+ x 1))"#;
let out = cli(&["run", "--metric", "--script", script, "--save", saved]);
let err = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "{:?}: {err}", out.status);
assert!(err.lines().any(|l| l == "done") && err.lines().any(|l| l == "2"), "{err}");
let info = cli(&["info", saved]);
let v: serde_json::Value = serde_json::from_slice(&info.stdout).unwrap();
assert_eq!(v["counts"]["Circle"], 1, "{v}");
}
-3
View File
@@ -1,9 +1,6 @@
mod block_resources;
mod cli;
mod dash_limit_note;
mod drafting_spacing;
mod help;
mod lisp_script;
// DWG output needs craft-dwg's bridge.
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod ltype_dwg_note;
+2 -15
View File
@@ -188,25 +188,12 @@ fn subcommand_help_requests() {
),
case("help after an extra argument", &["info", "{b}", "extra", "-h"], 0, Line("Print a drawing's summary as JSON"), Empty),
case("--help after -- is a file name", &["run", "--", "--help"], 1, Empty, Starts("error: invalid parameters for `open`: --help:")),
case("run --version", &["run", "--version"], 2, Empty, Line("error: unexpected argument '--version' found")),
case("info --version", &["info", "--version"], 2, Empty, Line("error: unexpected argument '--version' found")),
],
);
}
/// RFC-0018 rule 1.1: `--version` and `-V` work on every subcommand, print one line on stdout and
/// return without running it (`mcp` would otherwise wait for a client).
#[test]
fn every_subcommand_prints_the_version() {
for sub in ["info", "convert", "run", "commands", "mcp", "perf", "sample", "roundtrip"] {
for flag in ["--version", "-V"] {
let top = invoke(&[flag]);
let release = top.stdout.strip_prefix("cadcraft-cli ").unwrap_or_else(|| panic!("{:?}", top.stdout));
let got = invoke(&[sub, flag]);
assert_eq!((got.code, got.stderr.as_str()), (0, ""), "{sub} {flag}");
assert_eq!(got.stdout, format!("cadcraft-cli-{sub} {release}"), "{sub} {flag}");
}
}
}
#[test]
fn unknown_flags_on_every_subcommand() {
run_cases(
-3
View File
@@ -37,6 +37,3 @@ 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
@@ -1,232 +0,0 @@
//! 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;
@@ -1,271 +0,0 @@
//! 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(())
}
-19
View File
@@ -15,8 +15,6 @@ 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))]
@@ -49,7 +47,6 @@ 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
@@ -85,7 +82,6 @@ mod web {
self.1.take_dropped(ui.ctx());
}
self.0.ui(ui);
crate::file_providers::publish(&self.0.file_providers);
}
}
@@ -124,12 +120,6 @@ mod web {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
@@ -140,8 +130,6 @@ mod web {
groups: cadcraft_io::entity_groups,
entity: cadcraft_io::entity_from_groups,
});
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record);
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
@@ -185,13 +173,6 @@ 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)) {
+3 -5
View File
@@ -24,16 +24,11 @@ serde_json = { workspace = true }
serde = { workspace = true }
log = { workspace = true }
clap = { workspace = true }
craft-nightly = { workspace = true }
thiserror = { workspace = true }
chrono = { workspace = true }
# Reads eframe's app.ron to tell whether a window state was saved (main.rs `saved_window`).
# Already in Cargo.lock through eframe; same version so nothing is built twice.
ron = "0.12"
# Waits for wgpu's answers while the graphics start (src/renderer.rs) and, on macOS, for the
# answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already in
# Cargo.lock through eframe.
pollster = "1"
[build-dependencies]
winresource = "0.1"
@@ -60,6 +55,9 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["std",
# The same winit eframe uses (the storytold fork, patched in the workspace).
# `rwh_06`: the window handle a file dialog shown as a sheet attaches to (src/sheet.rs).
winit = { version = "0.30", default-features = false, features = ["rwh_06"] }
# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already
# in Cargo.lock through eframe.
pollster = "1"
# Finder double-click, Open With, Dock drops and `open -a CADCraft plan.dxf` arrive as a
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle (#158). Keep the Objective-C
# handler behind a safe API, without relaxing the workspace's unsafe-code lint.
+29 -4
View File
@@ -1,11 +1,23 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
use std::ffi::OsString;
pub use craft_nightly::BuildFlavor;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub const COMPILED: BuildFlavor = if cfg!(cadcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open CADCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable CADCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
@@ -23,8 +35,7 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
#[cfg(test)]
mod tests {
use super::{BuildFlavor, needs_native_error, version, version_query};
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
@@ -33,6 +44,20 @@ mod tests {
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.23.1"), "0.23.1");
+4 -78
View File
@@ -4,9 +4,8 @@
//! The server only reads requests: a line that is not a JSON object with a string `method` (an
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
//! closed, so nothing sent after it runs. Every resource a client can hold is bounded
//! ([`Limits`]): simultaneous connections, request line length (shorter until a request on the
//! connection has carried the token), queued requests, and how long a socket may sit idle or
//! blocked on a write.
//! ([`Limits`]): simultaneous connections, request line length, queued requests, and how long a
//! socket may sit idle or blocked on a write.
use std::io::{BufRead, BufReader, ErrorKind, Write};
use std::net::{TcpListener, TcpStream};
@@ -25,9 +24,6 @@ struct Limits {
max_clients: usize,
/// Longest request line in bytes (newline excluded); a longer one closes the connection.
max_line: usize,
/// Longest request line until a request on the connection has carried the right token; a
/// longer one closes the connection (#1925).
preauth_line: usize,
/// Request-line bytes buffered at once across all connections; a request that would pass it
/// is refused with an error reply.
total_bytes: usize,
@@ -47,7 +43,6 @@ impl Default for Limits {
max_clients: 16,
// Generous, so requests that carry whole drawings or images as base64 still fit.
max_line: 256 * 1024 * 1024,
preauth_line: cadcraft_mcp::control_token::MAX_UNAUTHENTICATED_LINE,
// Room for one maximal request plus smaller ones, not `max_clients` maximal ones.
total_bytes: 512 * 1024 * 1024,
queue: 64,
@@ -349,21 +344,12 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
let mut reader = BufReader::new(read);
let mut buf = Vec::new();
let mut held = Held::new(budget);
// The token is checked only after the whole line is read, so until a request here has carried
// it a line is kept short: a peer without it can't make the app buffer `max_line` (#1925).
let mut authenticated = false;
loop {
let max = if authenticated { limits.max_line } else { limits.preauth_line.min(limits.max_line) };
let reject = match read_bounded_line(&mut reader, &mut buf, max, &mut held) {
let reject = match read_bounded_line(&mut reader, &mut buf, limits.max_line, &mut held) {
Ok(false) => break,
// Nothing of a line arrived (idle timeout, or the peer is gone): close without a word.
// A line nobody asked for would be read as the reply to the client's next request.
Err(_) if buf.is_empty() => break,
// Only an overlong line leaves more than `max` bytes buffered.
Err(_) if !authenticated && buf.len() > max => format!(
"request line longer than {max} bytes before a request with the control token on this connection; \
send a short request with the token (such as `ping`) first; closing the connection"
),
Err(e) => e,
Ok(true) => match parse_line(&buf) {
Line::Blank => continue,
@@ -380,7 +366,6 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
let _ = writeln!(out, "{r}");
break;
}
authenticated = true;
// Absent `params` is `{}`; ones that cannot be decoded (an unpaired surrogate escape) are an
// error, not a request run with defaults.
let params = match params.map(|r| serde_json::from_str::<Value>(r.get())) {
@@ -514,12 +499,7 @@ mod tests {
/// The control server on a loopback port, with a stand-in UI that echoes each method.
fn serve_echo() -> std::net::SocketAddr {
serve_echo_with(Limits::default())
}
/// [`serve_echo`] under `limits`.
fn serve_echo_with(limits: Limits) -> std::net::SocketAddr {
let (addr, rx) = serve_with(limits);
let (addr, rx) = serve_with(Limits::default());
std::thread::spawn(move || {
for req in rx {
let _ = req.reply.send(json!({"ok": true, "method": req.method}));
@@ -632,60 +612,6 @@ mod tests {
drop(first);
}
/// Small bounds for the pre-authentication tests: lines up to 1000 bytes until the connection
/// has shown the token, up to 100 000 after.
fn preauth() -> Limits {
Limits { max_line: 100_000, preauth_line: 1000, idle_timeout: Duration::from_secs(5), ..short() }
}
/// A request line carrying the test token whose parameters make it `len` bytes or longer.
fn long_req_line(id: i64, len: usize) -> String {
json!({"id": id, "method": "long", "params": {"text": "x".repeat(len)}, "token": TEST_TOKEN}).to_string() + "\n"
}
/// A peer without the token is refused once its line passes the pre-authentication bound,
/// while it is still sending: the app doesn't buffer the rest of the line to find the token
/// at its end (#1925).
#[test]
fn an_unauthenticated_long_line_is_refused_at_the_preauth_bound() {
let (addr, rx) = serve_with(preauth());
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
// Well under `max_line`, and unfinished: without the pre-authentication bound the server
// keeps reading and waiting for the rest of it. One write, so it all reaches the server's
// buffer at once and the close after the refusal leaves nothing unread to reset the reply.
let unfinished = format!(r#"{{"id":1,"method":"m","params":"{}"#, "x".repeat(5000));
c.write_all(unfinished.as_bytes()).unwrap();
let mut line = String::new();
BufReader::new(&mut c).read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!(v["ok"], json!(false));
assert!(v["error"].as_str().unwrap_or("").contains("longer than 1000 bytes before a request with the control token"), "{line}");
assert!(rx.try_recv().is_err(), "nothing was dispatched");
}
/// A long request with the token is taken once a shorter request with the token has been
/// answered on the same connection; as a connection's first line it is refused, since its
/// token comes only at the end.
#[test]
fn a_long_request_is_taken_once_the_connection_has_shown_the_token() {
let addr = serve_echo_with(preauth());
let long = long_req_line(2, 5000);
let first = exchange(addr, long.as_bytes());
assert_eq!(first.len(), 1, "{first:?}");
assert!(first[0]["error"].as_str().unwrap_or("").contains("before a request with the control token"), "{first:?}");
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
c.write_all(format!("{}{long}", req_line(1, "ping")).as_bytes()).unwrap();
let mut r = BufReader::new(c);
for (id, method) in [(1, "ping"), (2, "long")] {
let mut line = String::new();
r.read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!((v["id"].as_i64(), v["ok"].as_bool(), v["method"].as_str()), (Some(id), Some(true), Some(method)), "{line}");
}
}
#[test]
fn the_budget_is_given_back_when_the_connection_ends() {
let budget = Budget::new(100);
+3 -8
View File
@@ -23,10 +23,7 @@ pub(crate) const VARS: &[(&str, &str)] = &[
(CONFIG_DIR, "the settings folder (logs, autosave, workspace, plotters); empty means no settings folder"),
(LOCALE, "the interface language, instead of the system's"),
(VSYNC, "1 presents with vsync, 0 without it (default: without on Linux and BSD)"),
(
STENCIL,
"0 opens the window without a stencil buffer, 1 keeps it on every attempt; unset, a start that can't draw with it drops it (clipped layout viewports then draw unclipped)",
),
(STENCIL, "0 opens the window without a stencil buffer, for drivers that show a black window; clipped layout viewports then draw unclipped"),
(WAYLAND, "1 keeps the native Wayland backend instead of XWayland; 0 or unset is off"),
(NO_NATIVE_MENU, "macOS: 1 keeps the menus inside the window; 0 or unset is off"),
(SYSTEM_CURSOR, "1 uses the system cursor instead of the drawn crosshair; 0 or unset is off"),
@@ -49,10 +46,8 @@ pub(crate) struct Env {
pub(crate) locale: Option<String>,
/// Present with vsync (default: off on Linux and BSD, on elsewhere).
pub(crate) vsync: Switch,
/// Off: the window has no stencil buffer; on: it keeps one on every attempt at starting the
/// graphics. Default: it starts with one, and a start that can't draw with it drops it (see
/// `renderer`). Some old drivers (Mesa on Intel HD 4000, old Intel drivers on Windows) accept a
/// stencil pass and then present a black window.
/// Off: the window has no stencil buffer (default: on). Some old drivers (Mesa on Intel HD
/// 4000, old Intel drivers on Windows) accept a stencil pass and then present a black window.
pub(crate) stencil: Switch,
/// Keep the native Wayland backend instead of XWayland.
#[cfg_attr(not(all(unix, not(target_os = "macos"))), allow(dead_code))]
+174 -64
View File
@@ -1,101 +1,211 @@
//! Nightly-v1 bootstrap powered by `craft-nightly`: selected before logging, updates, fonts, or
//! saved state. Direct nightly launches self-isolate into `craft_nightly::canonical_profile_root`,
//! while explicit `--launch-profile nightly-v1 --profile-root <dir>` invocations keep their
//! launcher-supplied root. Stable launches retain their original arguments and directory policy.
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions};
pub const VERSION: &str = "nightly-v1";
pub fn current() -> &'static Profile {
craft_nightly::current().unwrap_or(&Profile::Stable)
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
pub fn prepare(flavor: BuildFlavor, args: impl IntoIterator<Item = OsString>) -> Result<Launch, ProfileError> {
craft_nightly::prepare_launch(flavor, &crate::profile_root::spec(), args, &StartupOptions::new())
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old portable/config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::portable::probe)
}
#[cfg(test)]
mod tests {
use std::ffi::OsString;
use std::path::PathBuf;
use craft_nightly::{BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup};
use crate::profile_root::{APP_ID, spec};
use super::*;
use std::cell::Cell;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\cadcraft" } else { "/nightly-data/profiles/cadcraft" }
}
#[test]
fn direct_nightly_launch_self_isolates_into_canonical_root_and_preserves_user_args() {
let expected_root = canonical_profile_root(APP_ID).unwrap();
let launch = parse_startup(BuildFlavor::NightlyV1, &spec(), args(&["--sample", "plan.dxf"]), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert!(launch.profile.is_nightly());
assert_eq!(launch.passthrough_args, args(&["--sample", "plan.dxf"]));
assert!(!launch.is_version_query());
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn explicit_launcher_flags_override_canonical_root_and_forward_passthrough_args() {
let argv = args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--", "drawing with spaces.dxf"]);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec(), argv, &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.passthrough_args, args(&["drawing with spaces.dxf"]));
assert!(!launch.is_version_query());
}
#[test]
fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() {
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["--new-window", "a.dxf"]), args(&["--", "--launch-profile", "file.dxf"])] {
let launch = parse_startup(BuildFlavor::Stable, &spec(), argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::Stable);
assert_eq!(launch.passthrough_args, argv);
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
}
let nightly = args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]);
assert!(matches!(parse_startup(BuildFlavor::Stable, &spec(), nightly, &StartupOptions::new()), Err(ProfileError::NightlyFlagsInStableBuild)));
}
#[test]
fn malformed_nightly_flags_are_refused() {
let s = spec();
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "drawing with spaces.dxf"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "drawing with spaces.dxf"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
args(&["--new-window", "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-window", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
] {
assert!(parse_startup(BuildFlavor::NightlyV1, &s, argv, &StartupOptions::new()).is_err());
assert!(parse(argv).is_err());
}
}
#[test]
fn launcher_and_direct_version_queries_are_recognized() {
let s = spec();
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
let direct = parse_startup(BuildFlavor::NightlyV1, &s, args(&[flag]), &StartupOptions::new()).unwrap();
assert!(direct.is_version_query(), "direct {flag}");
let launcher = parse_startup(
BuildFlavor::NightlyV1,
&s,
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), flag]),
&StartupOptions::new(),
)
.unwrap();
assert!(launcher.is_version_query(), "launcher {flag}");
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-window", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
let file_named_version = parse_startup(BuildFlavor::NightlyV1, &s, args(&["--", "--version"]), &StartupOptions::new()).unwrap();
assert!(!file_named_version.is_version_query());
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+58 -111
View File
@@ -33,7 +33,6 @@ mod nightly_session;
mod portable;
mod process_identity;
mod profile_root;
mod renderer;
#[cfg(target_os = "macos")]
mod sheet;
mod single_instance;
@@ -183,12 +182,6 @@ pub fn install_io() {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
@@ -199,8 +192,6 @@ pub fn install_io() {
groups: cadcraft_io::entity_groups,
entity: cadcraft_io::entity_from_groups,
});
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record);
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
@@ -221,34 +212,11 @@ fn services() -> Services {
pick_pgp: Some(Box::new(|dir: Option<&str>| {
file_dialog(&Pick::Pgp(dir.unwrap_or_default().into())).pick_file().map(|p| p.to_string_lossy().to_string())
})),
open_folder: Some(Box::new(|dir: &str| open_folder(dir).map_err(Into::into))),
// Set in `main` once the Nightly session record exists.
at_exit: None,
}
}
/// Why [`open_folder`] could not show a folder.
#[derive(Debug, thiserror::Error)]
enum OpenFolderError {
#[error("{dir}: {source}")]
Create { dir: String, source: std::io::Error },
#[error("{program}: {source}")]
Launch { program: &'static str, source: std::io::Error },
}
/// Show `dir` in the system's file manager (Finder, Explorer or the desktop's own), creating it
/// first so a folder nothing was saved in yet still opens.
fn open_folder(dir: &str) -> Result<(), OpenFolderError> {
std::fs::create_dir_all(dir).map_err(|source| OpenFolderError::Create { dir: dir.to_string(), source })?;
#[cfg(target_os = "macos")]
let program = "open";
#[cfg(target_os = "windows")]
let program = "explorer";
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
let program = "xdg-open";
std::process::Command::new(program).arg(dir).spawn().map(|_| ()).map_err(|source| OpenFolderError::Launch { program, source })
}
/// The file types `pick` offers: (label, extensions). Shared by the blocking dialogs and the
/// macOS sheets.
fn filters(pick: &Pick) -> Vec<(&'static str, Vec<&'static str>)> {
@@ -265,38 +233,9 @@ fn filters(pick: &Pick) -> Vec<(&'static str, Vec<&'static str>)> {
}
}
/// `Services::start_pick` for Linux and the BSDs: the blocking dialog runs on a thread of its
/// own, so the window keeps answering the desktop while the dialog is open; `ui` is woken when
/// it answers. If the thread cannot start, `done` is dropped unanswered and the app says the
/// dialog could not be shown.
#[cfg(all(unix, not(target_os = "macos")))]
fn start_pick(ui: egui::Context) -> cadcraft_ui_egui::StartPick {
Box::new(move |pick, done| {
let ui = ui.clone();
// Here, not on the thread: the interface language is this thread's
// (`i18n::with_language`), and the filter labels are translated.
let filters = filters(&pick);
let spawned = std::thread::Builder::new().name("file-dialog".into()).spawn(move || {
let dialog = file_dialog_with(&pick, &filters);
let picked = if matches!(pick, Pick::Save(_)) { dialog.save_file() } else { dialog.pick_file() };
done(picked.map(|p| p.to_string_lossy().to_string()));
ui.request_repaint();
});
if let Err(e) = spawned {
log::warn!("file dialog: {e}");
}
})
}
/// The blocking dialog for `pick` (Windows, Linux, FreeBSD).
fn file_dialog(pick: &Pick) -> rfd::FileDialog {
file_dialog_with(pick, &filters(pick))
}
/// [`file_dialog`] offering `filters`, the file types of `pick` ([`filters`]) as the caller's
/// thread names them.
fn file_dialog_with(pick: &Pick, filters: &[(&'static str, Vec<&'static str>)]) -> rfd::FileDialog {
let dialog = filters.iter().fold(rfd::FileDialog::new(), |d, (label, exts)| d.add_filter(*label, exts));
let dialog = filters(pick).iter().fold(rfd::FileDialog::new(), |d, (label, exts)| d.add_filter(*label, exts));
match pick {
Pick::Save(name) => dialog.set_file_name(name),
Pick::Lisp(dir) | Pick::Pgp(dir) if !dir.is_empty() => dialog.set_directory(dir),
@@ -361,7 +300,7 @@ const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
/// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state
/// saved by the last session is restored instead of opening centred. `stencil`: the stencil bits of
/// its render pass (each attempt at starting the graphics sets its own, see [`renderer::apply`]).
/// its render pass ([`stencil_bits`]).
fn window_options(restoring: bool, stencil: u8, frame: Option<&cadcraft_ui_egui::framework::Decision>) -> eframe::NativeOptions {
let viewport = egui::ViewportBuilder::default()
.with_title(os_window::name_for(os_window::identity()))
@@ -390,6 +329,17 @@ fn window_options(restoring: bool, stencil: u8, frame: Option<&cadcraft_ui_egui:
/// The key eframe saves the main window state under in its storage.
const WINDOW_KEY: &str = "window";
/// Stencil bits of the window's render pass (see `NativeOptions::stencil_buffer`).
const STENCIL_BITS: u8 = 8;
/// The stencil bits of the window's render pass: none when `CADCRAFT_STENCIL` is off. Some old
/// drivers (Mesa on Intel HD 4000, old Intel drivers on Windows) accept a stencil pass without an
/// error and then present a black window, so only an explicit opt-out drops it. Without a stencil
/// buffer, clipped layout viewports draw unclipped.
fn stencil_bits(stencil: Switch) -> u8 {
if stencil == Switch::Off { 0 } else { STENCIL_BITS }
}
#[cfg(target_os = "macos")]
const APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/cadcraft-macos-512.png");
#[cfg(not(target_os = "macos"))]
@@ -472,30 +422,35 @@ fn report_launch_profile_error(error: &str) {
/// should return success without opening a window.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// Plain `--version` or `-V`: answered before resolving a home directory, root validation,
// process identity, logging, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, logging, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
{
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "{}", nightly_version_line());
return None;
}
let launch = launch_profile::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| {
report_launch_profile_error(&error.to_string());
std::process::exit(2)
});
// Launcher's `--launch-profile nightly-v1 --profile-root <dir> --version` (or `-V`):
// `craft_nightly::prepare_launch` leaves the filesystem untouched and installs no profile.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && launch.is_version_query() {
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "{}", nightly_version_line());
return None;
}
let identity = if launch.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable };
if let Err(error) = initialize_nightly_process_identity().map_err(|e| e.to_string()).and_then(|()| os_window::select_identity(identity)) {
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| {
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
})
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable };
if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(launch.passthrough_args)
Some(early.args)
}
/// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe.
@@ -589,6 +544,12 @@ fn main() -> eframe::Result {
cadcraft_engine::fonts::ttf::set_fallback_fonts(list);
}
let surface = cadcraft_ui_egui::gpu::surface_config(vars.vsync, cfg!(all(unix, not(target_os = "macos"))));
// The window's render pass and the canvas's pipelines must agree on it; a mismatch is a wgpu
// validation error.
let stencil = stencil_bits(vars.stencil);
if stencil == 0 {
log::warn!("CADCRAFT_STENCIL is off: the window has no stencil buffer; clipped layout viewports draw unclipped");
}
// XWayland when it's there (see below), unless CADCRAFT_WAYLAND=1 keeps the native Wayland backend.
let forced_x11 = cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On;
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11);
@@ -601,7 +562,7 @@ fn main() -> eframe::Result {
// swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync).
wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface),
persistence_path: persistence_path.clone(),
..window_options(restores_window(persistence_path.as_deref()), renderer::STENCIL_BITS, frame.as_ref())
..window_options(restores_window(persistence_path.as_deref()), stencil, frame.as_ref())
};
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
@@ -638,13 +599,10 @@ fn main() -> eframe::Result {
let apple_events = &apple_events;
// The exit hook's own handle: the app creator is a `move` closure, so the watch is cloned before it.
let exit_watch = std::sync::Arc::clone(&nightly_watch);
// Each attempt at starting the graphics sets its backends, adapter and stencil buffer, and a
// failed one is followed by the next (see renderer.rs).
let result = renderer::run_native(
let result = eframe::run_native(
os_window::name_for(os_window::identity()),
options,
vars.stencil,
Box::new(move |cc, started| {
Box::new(move |cc| {
cadcraft_ui_egui::framework::install(&cc.egui_ctx, forced_x11, frame.clone())?;
let mut app = CadApp::new(Session::empty(), services());
// The exit hook runs in `on_exit`: macOS ends the process inside AppKit's terminate after
@@ -659,13 +617,6 @@ fn main() -> eframe::Result {
if let Some(window) = cc.winit_window().cloned() {
app.services.start_pick = Some(sheet::start_pick(window, cc.egui_ctx.clone()));
}
// On Linux and the BSDs the dialog is the desktop portal's, another process: waiting
// for it in the event handler leaves the window unanswered for as long as it is open,
// and the desktop then offers to force-quit the app.
#[cfg(all(unix, not(target_os = "macos")))]
{
app.services.start_pick = Some(start_pick(cc.egui_ctx.clone()));
}
let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref());
if let Some(ui) = restored {
app.ui = ui;
@@ -719,8 +670,9 @@ fn main() -> eframe::Result {
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
}
// On the GPU with the window's stencil buffer, or on the CPU when the GPU refuses the canvas.
started.install(&mut app, cc.wgpu_render_state.as_ref());
if let Some(rs) = &cc.wgpu_render_state {
app.set_wgpu(rs, eframe::egui_wgpu::depth_format_from_bits(0, stencil));
}
if let Some(port) = control_port {
let rx = control_server::start(port, cc.egui_ctx.clone());
app = app.with_control(rx);
@@ -778,8 +730,10 @@ fn main() -> eframe::Result {
#[cfg(test)]
mod tests {
use super::{filters_for_save, follow_desktop, nightly_version_line, saved_window, version_string, window_options, without_tiny_window};
use crate::renderer::STENCIL_BITS;
use super::{
STENCIL_BITS, filters_for_save, follow_desktop, nightly_version_line, saved_window, stencil_bits, version_string, window_options,
without_tiny_window,
};
#[test]
fn save_dialog_offers_dwg_with_the_drawing_format_first() {
@@ -814,25 +768,18 @@ mod tests {
}
/// `CADCRAFT_STENCIL=0` (also `no`, `false`, any case) opens the window without a stencil
/// buffer, and `1` keeps it on every attempt; unset, blank or anything else starts with one and
/// lets a failed start drop it.
/// buffer; unset, blank, `1` or anything else keeps it.
#[test]
fn the_stencil_buffer_follows_cadcraft_stencil() {
let stencils = |value: Option<&str>| {
fn the_stencil_buffer_is_dropped_only_when_asked() {
let bits = |value: Option<&str>| {
let vars = crate::env::Env::from_vars(|k| (k == "CADCRAFT_STENCIL").then_some(value).flatten().map(Into::into));
let attempts = crate::renderer::attempts(eframe::wgpu::Backends::DX12, false, vars.stencil);
attempts.iter().map(|a| a.stencil).collect::<std::collections::BTreeSet<_>>().into_iter().collect::<Vec<_>>()
stencil_bits(vars.stencil)
};
for off in ["0", "no", "NO", "false", "False", " 0 "] {
assert_eq!(stencils(Some(off)), [false], "{off:?}");
assert_eq!(bits(Some(off)), 0, "{off:?}");
}
for on in ["1", "yes", "On"] {
assert_eq!(stencils(Some(on)), [true], "{on:?}");
}
for unset in [None, Some(""), Some("8"), Some("maybe")] {
assert_eq!(stencils(unset), [false, true], "{unset:?}");
let vars = crate::env::Env::from_vars(|k| (k == "CADCRAFT_STENCIL").then_some(unset).flatten().map(Into::into));
assert!(crate::renderer::attempts(eframe::wgpu::Backends::DX12, false, vars.stencil)[0].stencil, "{unset:?}: the first has one");
for on in [None, Some(""), Some("1"), Some("yes"), Some("8"), Some("maybe")] {
assert_eq!(bits(on), STENCIL_BITS, "{on:?}");
}
}
+561 -172
View File
@@ -1,218 +1,607 @@
//! CADCraft's `craft-nightly` isolation specification: stable paths, environment fence,
//! portable-mode markers, folder-only entries, and platform-specific forbidden roots.
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
use std::ffi::OsString;
use std::path::PathBuf;
use craft_nightly::AppProfileSpec;
use crate::portable::{PORTABLE_DATA_DIR, portable_marker};
use std::path::{Component, Path, PathBuf};
use crate::portable::PORTABLE_MARKER;
pub const APP_ID: &str = "cadcraft";
/// The app id eframe derives stable's storage folder from (`main.rs` `persistence_path`).
const STABLE_PACKAGE_ID: &str = "ai.storyteller.cadcraft";
/// The app id of the nightly bundle (`packaging/linux/flatpak-bundle.sh`).
const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.cadcraft.nightly";
const STABLE_DIR_NAMES: &[&str] = &["CADCraft", "cadcraft"];
const FORBIDDEN_ENV_VARS: &[&str] = &["CADCRAFT_CONFIG_DIR"];
const PORTABLE_MARKERS: &[&str] = &[PORTABLE_MARKER];
const FOLDER_ONLY_ENTRIES: &[&str] = &["autosave", "logs", "support", "single-instance", "plotters", "crash-reports"];
/// Builds CADCraft's `craft-nightly` isolation specification from the current process environment.
pub fn spec() -> AppProfileSpec {
spec_with_env(|key| std::env::var_os(key))
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
fn spec_with_env(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
AppProfileSpec {
app_id: APP_ID,
display_name: "CADCraft",
stable_dir_names: STABLE_DIR_NAMES,
stable_package_id: STABLE_PACKAGE_ID,
nightly_package_id: NIGHTLY_PACKAGE_ID,
profile_root_env: None,
forbidden_env_vars: FORBIDDEN_ENV_VARS,
portable_markers: PORTABLE_MARKERS,
folder_only_entries: FOLDER_ONLY_ENTRIES,
extra_forbidden_roots: extra_forbidden_roots(&env),
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
// CADCraft also builds for the BSDs (packaging/freebsd): nightly-v1 is Windows, macOS and
// Linux only, as the shared nightlies publish.
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn extra_forbidden_roots(env: &impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
let mut roots = Vec::new();
#[cfg(target_os = "windows")]
{
// The MSI's per-machine install folder (`cadcraft.wxs`).
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = non_empty_abs(env, key) {
roots.push(base.join("ArtCraft").join("CADCraft"));
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
#[cfg(all(unix, not(target_os = "macos")))]
{
roots.extend(["/usr/bin/cadcraft", "/usr/local/bin/cadcraft", "/opt/cadcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
if let Some(home) = non_empty_abs(env, "HOME") {
roots.push(home.join(".var/app/ai.storyteller.cadcraft"));
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
#[cfg(target_os = "macos")]
{
if let Some(home) = non_empty_abs(env, "HOME") {
let library = home.join("Library");
roots.push(library.join("Preferences/ai.storyteller.cadcraft.plist"));
roots.push(library.join("Saved Application State/ai.storyteller.cadcraft.savedState"));
roots.push(home.join("Applications/CADCraft.app"));
}
roots.push(PathBuf::from("/Applications/CADCraft.app"));
}
roots
Ok(resolved)
}
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
let value = env(key).filter(|v| !v.is_empty())?;
let path = PathBuf::from(value);
path.is_absolute().then_some(path)
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
// A component that is not valid UTF-8 keeps its exact bytes: a lossy comparison would fold two
// different names into the same replacement character and call them one folder.
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str();
match (platform.ignores_case(), value.to_str()) {
(true, Some(text)) => OsString::from(text.to_lowercase()),
_ => value.to_os_string(),
}
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
/// Every stable CADCraft data root of this platform, plus the install folders and the running
/// install ([`installation_boundary`]).
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("CADCraft")))
.collect::<Result<Vec<_>, _>>()?;
// Stable's eframe storage folder (`eframe::storage_dir`: `app.ron` under
// `%APPDATA%\ai.storyteller.cadcraft\data`), outside the roaming `CADCraft` folder.
roots.push(required_base(env, "APPDATA")?.join(EFRAME_APP_ID));
// The MSI's per-machine folder (cadcraft.wxs). A custom install folder is not known
// here; the executable's own folder is fenced below.
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("CADCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("cadcraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.extend(["/usr/bin/cadcraft", "/usr/local/bin/cadcraft", "/opt/cadcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.cadcraft"));
// Stable's eframe storage folder (`eframe::storage_dir`: window state, Options profile,
// UI and autosave prefs in `app.ron`), which is not the XDG settings folder above.
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(EFRAME_APP_ID));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/CADCraft"),
library.join("Caches/CADCraft"),
library.join("Caches/ai.storyteller.cadcraft"),
// Stable's eframe storage folder (`eframe::storage_dir`: `app.ron` in Application
// Support), beside the settings folder env.rs uses.
library.join("Application Support").join(EFRAME_APP_ID),
library.join("Preferences/CADCraft"),
library.join("Preferences/ai.storyteller.cadcraft.plist"),
library.join("Saved Application State/ai.storyteller.cadcraft.savedState"),
home.join("Applications/CADCraft.app"),
PathBuf::from("/Applications/CADCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
// A regular file in a folder's place is not a folder: the readers and sweepers that follow would
// fail halfway, so refuse it while the profile is still being validated.
match std::fs::symlink_metadata(&child) {
Ok(metadata) if !metadata.file_type().is_dir() => {
return Err(format!("the nightly {label} must be a directory, not a file or an alias"));
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
}
Ok(child)
}
/// Every existing entry directly in the profile (logs, settings and so on) must resolve inside it,
/// so a link there cannot point Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
Ok(())
}
/// Recognise the shared portable data namespace in both the supplied and resolved path.
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
// A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a
// marker only counts beside a CADCraft executable, so an unrelated portable.txt higher up
// (in a user folder or at a drive root) does not refuse the profile.
path.ancestors().enumerate().any(|(depth, ancestor)| {
portable_marker(ancestor).is_some() && (depth == 0 || ["cadcraft.exe", "cadcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
}) || path.components().any(|component| match component {
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
Component::Normal(name) => name == PORTABLE_DATA_DIR,
_ => false,
})
}
/// The writable hook is the app's existing exclusive probe (`portable::probe`). Keeping it injected
/// lets filesystem boundary tests exercise the real policy without starting the app or changing
/// global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
let chosen = canonical_future(root)?;
// The deb/rpm CLI wrapper exports CADCRAFT_CONFIG_DIR at the folder this launch already owns (the
// GUI wrappers name the profile through `--profile-root` instead), so that value is inert:
// `env::apply_profile` sets the settings folder from the profile, not from the variable. Any
// other value would redirect Nightly's settings folder, so it is refused.
if let Some(configured) = env("CADCRAFT_CONFIG_DIR").filter(|v| !v.is_empty()) {
let configured = canonical_future(&absolute(PathBuf::from(configured), "CADCRAFT_CONFIG_DIR")?)?;
if !configured.starts_with(&chosen) {
return Err("nightly-v1 cannot be combined with CADCRAFT_CONFIG_DIR outside its own profile".into());
}
}
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
{
// A Flatpak's data folder and runtime socket namespace belong to its app id. The nightly
// bundle has an id of its own ([`NIGHTLY_FLATPAK_ID`], named by
// `packaging/linux/flatpak-bundle.sh`), so its profile is already the sandbox's own; any
// other instance is the stable app's (or another app's), whose socket this profile must
// not inherit.
if id.to_string_lossy() != NIGHTLY_FLATPAK_ID {
return Err("nightly-v1 cannot inherit another Flatpak app's instance; launch through the native Launcher".into());
}
}
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
return Err("the nightly root must not use a portable CADCraft installation or its CADCraftData settings folder".into());
}
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
entries_stay_inside(&chosen)?;
// Drawing Recovery reads, adopts, overwrites and sweeps entries. Never let its alias leave this
// private profile, including toward a stable portable directory not in our known roots.
private_subdirectory(&chosen, AUTOSAVE, "recovery folder")?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
private_subdirectory(&confirmed, AUTOSAVE, "recovery folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
/// The app id of the nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`): the one Flatpak
/// instance whose sandbox is this channel's own. The window identity ([`crate::os_window`]) and the
/// bundle id differ on purpose, as they do for stable.
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.cadcraft.nightly";
/// The app id eframe derives stable's storage folder from ([`crate::main`]'s `persistence_path`).
/// A profile that sits there would overwrite stable's `app.ron`, so its folder is fenced too.
const EFRAME_APP_ID: &str = "ai.storyteller.cadcraft";
/// The subfolder autosave and Drawing Recovery write ([`crate::main`], `<settings>/autosave`).
pub const AUTOSAVE: &str = "autosave";
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use craft_nightly::{ProfileError, validate_and_prepare_root};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
use super::{
APP_ID, FOLDER_ONLY_ENTRIES, FORBIDDEN_ENV_VARS, NIGHTLY_PACKAGE_ID, PORTABLE_MARKERS, STABLE_DIR_NAMES, STABLE_PACKAGE_ID, spec,
spec_with_env,
};
struct TempDir(PathBuf);
impl TempDir {
fn new(label: &str) -> Self {
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate = std::env::temp_dir().join(format!(
"cadcraft-profile-spec-{}-{}-{label}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let candidate =
std::env::temp_dir().join(format!("cadcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create temp dir: {error}"),
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
Self(root)
let home = root.join("home");
let exe = root.join("install/cadcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
|dir| {
let probe = dir.join("exclusive-test-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
},
)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
}
impl Drop for TempDir {
impl Drop for Fixture {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
fn spec_preserves_cadcraft_isolation_constants_and_extra_forbidden_roots() {
let mut env = BTreeMap::<String, OsString>::new();
#[cfg(target_os = "windows")]
env.insert("ProgramFiles".into(), OsString::from(r"C:\Program Files"));
#[cfg(not(target_os = "windows"))]
env.insert("HOME".into(), OsString::from("/home/tester"));
let s = spec_with_env(|key| env.get(key).cloned());
assert_eq!(s.app_id, APP_ID);
assert_eq!(s.display_name, "CADCraft");
assert_eq!(s.stable_dir_names, STABLE_DIR_NAMES);
assert_eq!(s.stable_package_id, STABLE_PACKAGE_ID);
assert_eq!(s.nightly_package_id, NIGHTLY_PACKAGE_ID);
assert_eq!(s.profile_root_env, None);
assert_eq!(s.forbidden_env_vars, FORBIDDEN_ENV_VARS);
assert_eq!(s.portable_markers, PORTABLE_MARKERS);
assert_eq!(s.folder_only_entries, FOLDER_ONLY_ENTRIES);
#[cfg(target_os = "windows")]
assert!(s.extra_forbidden_roots.contains(&PathBuf::from(r"C:\Program Files\ArtCraft\CADCraft")));
#[cfg(all(unix, not(target_os = "macos")))]
{
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/usr/bin/cadcraft")));
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/usr/local/bin/cadcraft")));
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/opt/cadcraft")));
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/.var/app/ai.storyteller.cadcraft")));
fn portable_settings_from_another_install_are_refused_before_any_probe() {
let fixture = Fixture::new();
let stable_install = fixture.root.join("stable portable install");
let stable_data = stable_install.join(PORTABLE_DATA_DIR);
std::fs::create_dir_all(&stable_data).unwrap();
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "a different portable install is not a private Nightly profile");
assert!(!probed.get(), "reject portable data before a writable probe");
assert!(!stable_data.join("nested nightly").exists());
assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change");
assert_eq!(std::fs::read_dir(&stable_data).unwrap().count(), 1);
}
}
#[cfg(target_os = "macos")]
{
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/Library/Preferences/ai.storyteller.cadcraft.plist")));
assert!(
s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/Library/Saved Application State/ai.storyteller.cadcraft.savedState"))
);
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/Applications/CADCraft.app")));
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/Applications/CADCraft.app")));
}
}
#[test]
fn nightly_profile_reopens_with_saved_state_and_enforces_folder_only_entries() {
let temp = TempDir::new("reopen");
let private = temp.0.join("nightly-profile");
let s = spec();
let canonical = validate_and_prepare_root(&private, &s).unwrap();
assert_eq!(canonical, private);
for name in ["app.ron", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in FOLDER_ONLY_ENTRIES {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(validate_and_prepare_root(&private, &s).unwrap(), private);
for name in ["app.ron", "nightly-session.lock", "nightly-session.json"] {
assert_eq!(std::fs::read(private.join(name)).unwrap(), b"saved profile data", "{name} changed when reopening");
}
for name in FOLDER_ONLY_ENTRIES {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(matches!(validate_and_prepare_root(&private, &s), Err(ProfileError::ExpectedDirectoryEntry(_))), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
#[test]
fn a_non_directory_profile_stops_startup_without_installing_a_profile() {
let temp = TempDir::new("invalid-root");
let root = temp.0.join("ordinary-file");
std::fs::write(&root, b"existing file").unwrap();
let argv = craft_nightly::launch_arguments(&root, &[]);
assert!(craft_nightly::current().is_none());
let result = crate::launch_profile::prepare(craft_nightly::BuildFlavor::NightlyV1, argv);
assert!(matches!(result, Err(ProfileError::NotADirectory(_))));
assert!(craft_nightly::current().is_none());
assert_eq!(std::fs::read(root).unwrap(), b"existing file");
let private = fixture.root.join("CADCraftData-backup-name/nightly");
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component");
}
#[cfg(unix)]
#[test]
fn symlinks_inside_profile_root_are_refused() {
let temp = TempDir::new("symlink");
let outside = temp.0.join("outside");
let private = temp.0.join("nightly-profile");
std::fs::create_dir_all(&outside).unwrap();
std::fs::create_dir_all(&private).unwrap();
std::os::unix::fs::symlink(outside.join("target"), private.join("autosave")).unwrap();
fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
let fixture = Fixture::new();
let stable = fixture.home().join(".local/state/cadcraft/autosave");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join(AUTOSAVE)).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "autosave must not escape the private profile or follow a dangling alias");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-self");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&private, private.join(AUTOSAVE)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_err(), "autosave cannot treat all profile settings as recovery entries");
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
}
let err = validate_and_prepare_root(&private, &spec()).unwrap_err();
assert!(matches!(err, ProfileError::SymlinkEntry(_)), "unexpected error: {err}");
#[cfg(unix)]
#[test]
fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let recovery = private.join("private-recovery");
std::fs::create_dir_all(&recovery).unwrap();
std::os::unix::fs::symlink(&recovery, private.join(AUTOSAVE)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
assert_eq!(std::fs::canonicalize(private.join(AUTOSAVE)).unwrap(), recovery);
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/cadcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join(AUTOSAVE), platform));
assert!(overlaps(&root.join(AUTOSAVE), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("cadcraft-other"), platform));
}
}
#[test]
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("cadcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
// Stable's eframe storage folder holds `app.ron`, so a profile may not sit at or inside it.
let storage = data.join(EFRAME_APP_ID);
std::fs::create_dir_all(&storage).unwrap();
std::fs::write(storage.join("app.ron"), b"stable window state").unwrap();
for candidate in [storage.clone(), storage.join("nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"), "{}", candidate.display());
}
assert_eq!(std::fs::read(storage.join("app.ron")).unwrap(), b"stable window state");
let nightly = data.join("ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/CADCraft Nightly.app/Contents/MacOS/CADCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/CADCraft",
"Application Support/ai.storyteller.cadcraft",
"Caches/CADCraft",
"Caches/ai.storyteller.cadcraft",
"Preferences/CADCraft",
"Saved Application State/ai.storyteller.cadcraft.savedState",
] {
let stable = library.join(suffix);
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
// The bundle path and the Library fences fold case on macOS.
let cased = library.join("application support/cadcraft/nightly");
assert!(fixture.check(Platform::Mac, &cased).is_err());
}
#[test]
fn windows_fences_roaming_local_and_both_install_folders() {
let mut fixture = Fixture::new();
fixture.env.insert("ProgramFiles".into(), fixture.root.join("program files").into_os_string());
for stable in [
fixture.root.join("roaming/CADCraft"),
fixture.root.join("roaming/ai.storyteller.cadcraft"),
fixture.root.join("local/CADCraft"),
fixture.root.join("program files/ArtCraft/CADCraft"),
] {
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly")] {
assert!(fixture.check(Platform::Windows, &candidate).unwrap_err().contains("overlap"), "{}", candidate.display());
}
// Windows folder names ignore case.
assert!(fixture.check(Platform::Windows, &stable.with_file_name("cadcraft")).is_err());
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let valid = fixture.root.join("local/ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Windows, &valid).unwrap(), valid);
}
#[test]
fn config_dir_and_flatpak_are_refused() {
let mut fixture = Fixture::new();
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), fixture.root.join("custom").into_os_string());
let private = fixture.root.join("nightly-config");
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("CADCRAFT_CONFIG_DIR"));
assert!(!private.exists());
fixture.env.remove("CADCRAFT_CONFIG_DIR");
for inherited in ["ai.storyteller.cadcraft", "org.freedesktop.other"] {
fixture.env.insert("FLATPAK_ID".into(), inherited.into());
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("Flatpak"), "{inherited}");
assert!(!private.exists());
}
}
/// The nightly bundle runs under an app id of its own, so its sandbox data folder is this
/// channel's data root; that one instance is accepted, and its profile stays inside it.
#[test]
fn the_nightly_flatpaks_own_instance_accepts_its_own_profile() {
let mut fixture = Fixture::new();
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
let private = fixture.home().join(".var/app/ai.storyteller.cadcraft.nightly/data/cadcraft-nightly");
assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private);
// Stable's Flatpak folder is still fenced even inside the nightly instance.
let stable = fixture.home().join(".var/app/ai.storyteller.cadcraft");
assert!(fixture.check(Platform::Linux, &stable).unwrap_err().contains("overlap"));
}
/// A Linux Launcher wrapper exports `CADCRAFT_CONFIG_DIR` at the profile it launches; that is
/// the folder this launch already owns, so it must not refuse the profile. Anything else is
/// still a redirect.
#[test]
fn a_wrapper_naming_the_profile_in_config_dir_is_accepted() {
let mut fixture = Fixture::new();
let private = fixture.root.join("nightly-wrapper");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), private.clone().into_os_string());
assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private);
let inside = private.join("nested");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), inside.clone().into_os_string());
assert!(fixture.check(Platform::Linux, &inside).is_ok(), "a folder inside the profile is the profile's own");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), fixture.root.join("elsewhere").into_os_string());
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("CADCRAFT_CONFIG_DIR"));
}
#[test]
fn a_profile_that_cannot_be_written_is_refused_without_a_stable_fallback() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-unwritable");
let result = validate_for(Platform::Linux, &private, |key| fixture.get(key), Some(&fixture.exe), |_| Err(std::io::Error::other("read-only")));
assert!(result.unwrap_err().contains("not writable"));
assert!(private.exists(), "the profile was created before the probe, and nothing was written into stable");
assert!(!fixture.home().join(".config/cadcraft").exists());
}
#[cfg(unix)]
#[test]
fn a_dangling_entry_inside_the_profile_is_refused_before_writes() {
let fixture = Fixture::new();
let outside = fixture.root.join("outside");
std::fs::create_dir_all(&outside).unwrap();
let private = fixture.root.join("nightly-dangling");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(outside.join("missing"), private.join("logs")).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err());
assert!(!probed.get());
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
}
}
-660
View File
@@ -1,660 +0,0 @@
//! Which renderer draws the window, and what the app does when one can't start.
//!
//! The window draws with wgpu (eframe is built with its `wgpu` renderer only). Where a start fails
//! decides what is tried next:
//!
//! - The adapter, the device or the window's surface can't be made (no adapter for the backends, a
//! device the driver refuses or loses): eframe returns `Error::Wgpu` before the app exists. The
//! stencil buffer plays no part, so another adapter is tried.
//! - The window's surface can't be configured, or egui's pipelines are refused: also before the app
//! exists. The stencil buffer is part of both, so the same adapter is tried without it first.
//! - The driver takes the stencil buffer and then draws nothing, with no error: Mesa's OpenGL on Ivy
//! Bridge refuses `glTexStorage2D(GL_STENCIL_INDEX8)`, the frame buffer is incomplete and every
//! frame comes out black (#1724). egui makes the window's stencil buffer a texture it can also
//! sample, which wgpu's OpenGL backend stores with that call. Before the app is created, [`check`]
//! clears a small target, without and then with a stencil buffer made the same way, and reads it
//! back.
//! - The canvas's own pipelines are refused: the canvas draws on the CPU ([`Started::install`]).
//!
//! Not caught: a driver that crashes the process or hangs, a black window whose offscreen check
//! passes (a fault in presenting to the window), a failure after the app was created (an error
//! then ends the start as before), and a panic inside eframe or egui-wgpu.
//!
//! The attempts, in order ([`attempts`]): the start as it always was (DirectX 12 alone on Windows,
//! see `graphics.rs`; eframe's backends elsewhere); OpenGL alone, where those backends have it
//! beside another; then those backends with a software adapter only (WARP, llvmpipe). Each is tried
//! with a stencil buffer, then without. No attempt creates a backend the first one did not, so no
//! driver code runs that the start did not run before: on Windows, where OpenGL is left out because
//! an AMD driver crashes inside it (#31), the fallback is WARP. A start that works today makes only
//! the first attempt, and the check.
//!
//! `WGPU_BACKEND` limits every attempt to its backends, and `CADCRAFT_STENCIL` fixes the stencil
//! buffer. Nothing is remembered between starts: a failed attempt costs a fraction of a second, and
//! a remembered choice would keep a lesser renderer after a failure that happened once.
use std::sync::Arc;
use std::time::Duration;
use cadcraft_ui_egui::CadApp;
use cadcraft_ui_egui::switch::Switch;
use eframe::egui_wgpu::{self, NativeAdapterSelectorMethod, WgpuError, WgpuSetup};
use eframe::wgpu::{self, Backends, DeviceType};
/// Stencil bits of the window's render pass when an attempt has a stencil buffer (see
/// `NativeOptions::stencil_buffer`).
pub(crate) const STENCIL_BITS: u8 = 8;
/// How long [`check`] waits for its read-back. A slower answer counts as a pass: a busy GPU is no
/// reason to fall back.
const CHECK_TIMEOUT: Duration = Duration::from_secs(10);
/// The width of [`check`]'s target: one row of RGBA8 pixels is then exactly the row alignment a
/// copy to a buffer needs.
const CHECK_WIDTH: u32 = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT / 4;
/// The colour [`check`] clears to, as it reads back: a new texture starts as zeros.
const CHECK_COLOR: [u8; 4] = [255, 0, 255, 255];
type DynError = Box<dyn std::error::Error + Send + Sync>;
/// Builds the app once an attempt's window draws.
pub(crate) type Creator<'a> = Box<dyn FnOnce(&eframe::CreationContext<'_>, &Started) -> Result<Box<dyn eframe::App + 'a>, DynError> + 'a>;
/// The backends by name, for the log and the status bar.
const NAMES: [(Backends, &str); 4] =
[(Backends::DX12, "DirectX 12"), (Backends::METAL, "Metal"), (Backends::VULKAN, "Vulkan"), (Backends::GL, "OpenGL")];
/// One way to start the window's graphics.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Attempt {
/// The backends wgpu chooses an adapter from.
pub(crate) backends: Backends,
/// Only a software adapter (WARP, llvmpipe); otherwise wgpu's choice, which prefers a GPU.
pub(crate) software: bool,
/// The window has a stencil buffer, which clips the contents of clipped layout viewports.
pub(crate) stencil: bool,
}
impl Attempt {
/// The same adapter: an attempt that differs only in its stencil buffer.
fn same_adapter(self, other: Attempt) -> bool {
(self.backends, self.software) == (other.backends, other.software)
}
}
impl std::fmt::Display for Attempt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let backends: Vec<&str> = NAMES.iter().filter(|n| self.backends.contains(n.0)).map(|n| n.1).collect();
f.write_str(&if backends.is_empty() { format!("{:?}", self.backends) } else { backends.join(" or ") })?;
if self.software {
f.write_str(" on a software adapter")?;
}
f.write_str(if self.stencil { "" } else { " without a stencil buffer" })
}
}
/// The attempts in order (see the module docs). `first`: the backends the start is configured with;
/// `requested`: they are `WGPU_BACKEND`'s, which every attempt keeps; `stencil`: `CADCRAFT_STENCIL`.
pub(crate) fn attempts(first: Backends, requested: bool, stencil: Switch) -> Vec<Attempt> {
let mut adapters = vec![(first, false)];
if !requested && first.contains(Backends::GL) && first != Backends::GL {
adapters.push((Backends::GL, false));
}
adapters.push((first, true));
let stencils: &[bool] = match stencil {
Switch::On => &[true],
Switch::Off => &[false],
Switch::Default => &[true, false],
};
adapters.into_iter().flat_map(|(backends, software)| stencils.iter().map(move |&stencil| Attempt { backends, software, stencil })).collect()
}
/// What a failed attempt says about the attempts after it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Failure {
/// The adapter, the device or the surface couldn't be made, or nothing was drawn: the same
/// adapter without a stencil buffer fails the same way.
Adapter,
/// Something the stencil buffer is part of failed: the same adapter without one may work.
Stencil,
}
/// The attempt to try after the one at `at` failed with `failure`: the next one after a stencil
/// failure, else the next on another adapter.
pub(crate) fn next(attempts: &[Attempt], at: usize, failure: Failure) -> Option<usize> {
let failed = *attempts.get(at)?;
attempts.iter().enumerate().skip(at + 1).find(|(_, a)| failure == Failure::Stencil || !a.same_adapter(failed)).map(|(i, _)| i)
}
/// What `error` from `eframe::run_native` says about the attempt: `None` when it isn't the graphics
/// (the app's own start, the windowing system).
pub(crate) fn classify(error: &eframe::Error) -> Option<Failure> {
match error {
eframe::Error::Wgpu(WgpuError::ConfigureSurface(_) | WgpuError::CreateRenderer(_)) => Some(Failure::Stencil),
eframe::Error::Wgpu(_) => Some(Failure::Adapter),
eframe::Error::AppCreation(error) => error.downcast_ref::<CheckFailed>().map(|c| c.failure),
_ => None,
}
}
/// The attempt to try after the one at `at` ended with `error`: none once the app was `created`,
/// since a failure after that is no start failure (and the app can't be built twice), and none for
/// an error that isn't the graphics'.
pub(crate) fn retry(attempts: &[Attempt], at: usize, created: bool, error: &eframe::Error) -> Option<usize> {
if created {
return None;
}
next(attempts, at, classify(error)?)
}
/// [`check`] found that the window can't draw. Returned from the app creator, it ends the attempt
/// before the app exists.
#[derive(Debug)]
pub(crate) struct CheckFailed {
failure: Failure,
message: String,
}
impl std::fmt::Display for CheckFailed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for CheckFailed {}
/// Clear a small target and read it back: as it is, then with a stencil buffer of `stencil`, made
/// as egui makes the window's (see the module docs). A target that doesn't come back cleared is a
/// [`Failure::Adapter`] without the stencil buffer and a [`Failure::Stencil`] with it.
pub(crate) fn check(device: &wgpu::Device, queue: &wgpu::Queue, stencil: Option<wgpu::TextureFormat>) -> Result<(), CheckFailed> {
passes(stencil, |format| clear_and_read(device, queue, format))
}
/// [`check`]'s passes, each made by `pass` with or without the stencil buffer: what failed names
/// the [`Failure`], and a device that didn't answer the first pass isn't waited for a second time.
fn passes(
stencil: Option<wgpu::TextureFormat>,
mut pass: impl FnMut(Option<wgpu::TextureFormat>) -> Result<bool, String>,
) -> Result<(), CheckFailed> {
let failed = |failure: Failure| move |message: String| CheckFailed { failure, message };
let answered = pass(None).map_err(failed(Failure::Adapter))?;
match stencil {
Some(format) if answered => pass(Some(format)).map(|_| ()).map_err(failed(Failure::Stencil)),
_ => Ok(()),
}
}
/// One pass of [`check`]: `Err` names what came back instead of [`CHECK_COLOR`]; `Ok(false)`: no
/// answer came, which counts as a pass.
fn clear_and_read(device: &wgpu::Device, queue: &wgpu::Queue, stencil: Option<wgpu::TextureFormat>) -> Result<bool, String> {
let size = wgpu::Extent3d { width: CHECK_WIDTH, height: 1, depth_or_array_layers: 1 };
let row = CHECK_WIDTH * 4;
let submitted = pollster::block_on(egui_wgpu::winit::catch_errors(device, || {
let texture = |format, usage| {
device.create_texture(&wgpu::TextureDescriptor {
label: Some("startup check"),
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
})
};
let color = texture(wgpu::TextureFormat::Rgba8Unorm, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC);
// The usage egui gives the window's depth and stencil texture.
let depth = stencil.map(|format| texture(format, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING));
let color_view = color.create_view(&wgpu::TextureViewDescriptor::default());
let depth_view = depth.as_ref().map(|t| t.create_view(&wgpu::TextureViewDescriptor::default()));
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("startup check"),
size: u64::from(row),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
let [r, g, b, a] = CHECK_COLOR.map(|c| f64::from(c) / 255.0);
drop(encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("startup check"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &color_view,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r, g, b, a }), store: wgpu::StoreOp::Store },
depth_slice: None,
})],
depth_stencil_attachment: depth_view.as_ref().zip(stencil).map(|(view, format)| wgpu::RenderPassDepthStencilAttachment {
view,
depth_ops: format.has_depth_aspect().then_some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }),
stencil_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0), store: wgpu::StoreOp::Discard }),
}),
..Default::default()
}));
encoder.copy_texture_to_buffer(
color.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &buffer,
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: None },
},
size,
);
queue.submit([encoder.finish()]);
buffer
}));
let buffer = submitted.map_err(|e| format!("the device refused the check: {e}"))?;
let (send, mapped) = std::sync::mpsc::channel();
buffer.slice(..).map_async(wgpu::MapMode::Read, move |result| {
let _ = send.send(result);
});
match device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(CHECK_TIMEOUT) }) {
Ok(_) => {}
Err(wgpu::PollError::Timeout) => {
log::warn!("graphics: the start-up check had no answer after {CHECK_TIMEOUT:?}; taken as passed");
return Ok(false);
}
Err(e) => return Err(format!("waiting for the check failed: {e}")),
}
match mapped.try_recv() {
Ok(Ok(())) => {}
Ok(Err(e)) => return Err(format!("the check could not be read back: {e}")),
Err(_) => {
log::warn!("graphics: the start-up check was not read back; taken as passed");
return Ok(false);
}
}
let pixels = buffer.slice(..).get_mapped_range().map_err(|e| format!("the check could not be read back: {e}"))?;
read_back(&pixels).map(|()| true)
}
/// Whether the row [`check`] read back is [`CHECK_COLOR`] throughout, within what a driver's
/// rounding could change.
fn read_back(pixels: &[u8]) -> Result<(), String> {
let row = CHECK_WIDTH as usize * CHECK_COLOR.len();
let cleared = |p: &[u8; CHECK_COLOR.len()]| p.iter().zip(CHECK_COLOR).all(|(&p, c)| p.abs_diff(c) <= 8);
match pixels.as_chunks::<{ CHECK_COLOR.len() }>().0.iter().find(|&p| !cleared(p)) {
Some(p) => Err(format!("a cleared target read back {p:?}, not {CHECK_COLOR:?}")),
None if pixels.len() == row => Ok(()),
None => Err(format!("the check read back {} bytes, not {row}", pixels.len())),
}
}
/// `options` for `attempt`: its backends, its adapter and its stencil buffer.
pub(crate) fn apply(options: &mut eframe::NativeOptions, attempt: Attempt) {
options.stencil_buffer = if attempt.stencil { STENCIL_BITS } else { 0 };
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
create.instance_descriptor.backends = attempt.backends;
create.native_adapter_selector = attempt.software.then(|| Arc::new(software_adapter) as NativeAdapterSelectorMethod);
}
}
/// A software adapter of `adapters` that can show `surface`.
fn software_adapter(adapters: &[wgpu::Adapter], surface: Option<&wgpu::Surface<'_>>) -> Result<wgpu::Adapter, String> {
adapters
.iter()
.find(|a| a.get_info().device_type == DeviceType::Cpu && surface.is_none_or(|s| a.is_surface_supported(s)))
.cloned()
.ok_or_else(|| "no software adapter can show the window".to_owned())
}
/// Run eframe with each attempt in turn until one starts the window, then build the app with
/// `create`. `options` are as configured (their backends are `WGPU_BACKEND`'s or the platform's),
/// `stencil` is `CADCRAFT_STENCIL`. A failed attempt is dropped with its window before any app
/// exists; an error once the app was created ends the start, as before. When every attempt failed,
/// the first one's error is returned: it is the one the start as it always was would have given.
pub(crate) fn run_native(name: &str, options: eframe::NativeOptions, stencil: Switch, create: Creator<'_>) -> eframe::Result {
let requested = Backends::from_env().is_some();
let configured = match &options.wgpu_options.wgpu_setup {
WgpuSetup::CreateNew(create) => create.instance_descriptor.backends,
WgpuSetup::Existing(_) => Backends::all(),
};
// Only what this build has, so no attempt asks for a backend that can't be there.
let first = if requested { configured } else { configured & wgpu::Instance::enabled_backend_features() };
let attempts = attempts(first, requested, stencil);
// Later attempts reuse eframe's event loop, so the hooks a clone drops aren't needed again.
let template = options.clone();
let mut options = Some(options);
let mut create = Some(create);
let mut first_failure = None;
let mut why = None;
let mut at = 0;
while let Some(&attempt) = attempts.get(at) {
let mut attempt_options = options.take().unwrap_or_else(|| template.clone());
apply(&mut attempt_options, attempt);
fault::refuse_adapter(&mut attempt_options, at);
log::info!("graphics: starting with {attempt} (attempt {} of {})", at + 1, attempts.len());
let started = Started { attempt, index: at, why: why.clone() };
let slot = &mut create;
let result = eframe::run_native(
name,
attempt_options,
Box::new(|cc| {
if let Some(rs) = &cc.wgpu_render_state {
fault::check(started.index, started.stencil_format())?;
let checking = std::time::Instant::now();
check(&rs.device, &rs.queue, started.stencil_format())?;
log::info!("graphics: the start-up check passed in {:.1?}", checking.elapsed());
}
let create = slot.take().ok_or("the app was already created")?;
create(cc, &started)
}),
);
let Err(error) = result else { return Ok(()) };
let Some(after) = retry(&attempts, at, create.is_none(), &error) else {
if create.is_none() || classify(&error).is_none() {
return Err(error);
}
log::error!("graphics: {attempt} failed: {error}; no other renderer is left to try");
return Err(first_failure.unwrap_or(error));
};
log::warn!("graphics: {attempt} failed: {error}; trying the next renderer");
// The first failure says why the first choice isn't drawing; the log has the others.
why.get_or_insert_with(|| format!("{attempt} failed: {}", error.to_string().lines().next().unwrap_or_default()));
first_failure.get_or_insert(error);
at = after;
}
Err(first_failure.unwrap_or_else(|| eframe::Error::AppCreation("no renderer to start the window with".into())))
}
/// The attempt that started the window, handed to the app creator.
pub(crate) struct Started {
attempt: Attempt,
/// Its position in [`attempts`].
index: usize,
/// Why the first attempt isn't the one drawing.
why: Option<String>,
}
impl Started {
/// The format of the window's stencil buffer, which the canvas's pipelines must match.
fn stencil_format(&self) -> Option<wgpu::TextureFormat> {
egui_wgpu::depth_format_from_bits(0, if self.attempt.stencil { STENCIL_BITS } else { 0 })
}
/// Draw the canvas on the GPU with the window's render state `rs`, or on the CPU when its
/// pipelines are refused. Logs which renderer draws, and says in the status bar why when it is
/// not the first choice (unless the start already put something there).
pub(crate) fn install(&self, app: &mut CadApp, rs: Option<&egui_wgpu::RenderState>) {
let Some(rs) = rs else { return };
let stencil = self.stencil_format();
let installed = pollster::block_on(egui_wgpu::winit::catch_errors(&rs.device, || app.set_wgpu(rs, stencil)));
let canvas_failed = match installed {
Err(e) => Some(e.to_string()),
Ok(()) => fault::canvas(self.index),
};
if canvas_failed.is_some() {
app.canvas.gpu = None;
app.canvas.gpu_device = None;
}
let info = rs.adapter.get_info();
log::info!(
"graphics: {} draws the window on {} ({:?}, {:?}, driver {}); the canvas draws on the {}",
self.attempt,
info.name.trim(),
info.backend,
info.device_type,
[info.driver.trim(), info.driver_info.trim()].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" "),
if canvas_failed.is_some() { "CPU" } else { "GPU" }
);
if !self.attempt.stencil {
log::warn!("graphics: no stencil buffer: clipped layout viewports draw unclipped");
}
let note = match (&self.why, &canvas_failed) {
(_, Some(error)) => {
Some(cadcraft_ui_egui::tf!("Graphics: the drawing area draws on the CPU, because the GPU refused it: {error}", error = error))
}
(Some(why), None) => Some(cadcraft_ui_egui::tf!("Graphics: drawing with {renderer}, because {why}", renderer = self.attempt, why = why)),
(None, None) => None,
};
if let Some(note) = note {
log::warn!("{note}");
if app.status.is_none() {
app.set_status(note);
}
}
}
}
/// A test switch read only by debug builds: `CADCRAFT_GRAPHICS_FAULT=<attempt>:<step>[,...]` fails
/// the attempt at that position in [`attempts`] (from 0) at `adapter` (its adapter is refused),
/// `draw` or `stencil` ([`check`]'s pass without or with the stencil buffer), or `canvas` (the
/// canvas's pipelines), so each fallback can be run on a machine whose graphics work.
mod fault {
use super::{Arc, CheckFailed, Failure, NativeAdapterSelectorMethod, WgpuSetup, wgpu};
#[cfg(debug_assertions)]
fn asked(index: usize, step: &str) -> bool {
listed(std::env::var("CADCRAFT_GRAPHICS_FAULT").ok().as_deref(), index, step)
}
#[cfg(not(debug_assertions))]
fn asked(_index: usize, _step: &str) -> bool {
false
}
/// Whether `value` lists `<index>:<step>`.
#[cfg(any(debug_assertions, test))]
pub(super) fn listed(value: Option<&str>, index: usize, step: &str) -> bool {
value.is_some_and(|v| v.split(',').any(|f| f.trim().split_once(':') == Some((index.to_string().as_str(), step))))
}
pub(super) fn refuse_adapter(options: &mut eframe::NativeOptions, index: usize) {
if asked(index, "adapter")
&& let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup
{
let refuse = |_: &[wgpu::Adapter], _: Option<&wgpu::Surface<'_>>| Err("refused by CADCRAFT_GRAPHICS_FAULT".to_owned());
create.native_adapter_selector = Some(Arc::new(refuse) as NativeAdapterSelectorMethod);
}
}
pub(super) fn check(index: usize, stencil: Option<wgpu::TextureFormat>) -> Result<(), CheckFailed> {
let fail = |failure, step| CheckFailed { failure, message: format!("the {step} check failed (CADCRAFT_GRAPHICS_FAULT)") };
if asked(index, "draw") {
return Err(fail(Failure::Adapter, "draw"));
}
if stencil.is_some() && asked(index, "stencil") {
return Err(fail(Failure::Stencil, "stencil"));
}
Ok(())
}
pub(super) fn canvas(index: usize) -> Option<String> {
asked(index, "canvas").then(|| "refused by CADCRAFT_GRAPHICS_FAULT".to_owned())
}
}
#[cfg(test)]
mod tests {
use super::*;
const ANY: Backends = Backends::VULKAN.union(Backends::GL);
/// A short name of `attempt`, to read the order in the asserts.
fn key(attempt: &Attempt) -> String {
let short = [(Backends::DX12, "dx12"), (Backends::METAL, "metal"), (Backends::VULKAN, "vulkan"), (Backends::GL, "gl")];
let mut key = short.iter().filter(|(b, _)| attempt.backends.contains(*b)).map(|(_, n)| *n).collect::<Vec<_>>().join("+");
if attempt.software {
key.push_str(" software");
}
if !attempt.stencil {
key.push_str(" no-stencil");
}
key
}
fn keys(list: &[Attempt]) -> Vec<String> {
list.iter().map(key).collect()
}
/// The first attempt is the start as it always was; OpenGL alone comes only where it was one of
/// several, then the same backends on a software adapter, each with and then without a stencil
/// buffer. `WGPU_BACKEND` keeps its backends on every attempt, and `CADCRAFT_STENCIL` its choice.
#[test]
fn the_attempts_begin_with_the_start_as_it_was_and_keep_explicit_choices() {
let linux = attempts(ANY, false, Switch::Default);
assert_eq!(keys(&linux), ["vulkan+gl", "vulkan+gl no-stencil", "gl", "gl no-stencil", "vulkan+gl software", "vulkan+gl software no-stencil"]);
// Windows: DirectX 12 alone (graphics.rs), so the fallback never creates OpenGL there.
let windows = attempts(Backends::DX12, false, Switch::Default);
assert_eq!(keys(&windows), ["dx12", "dx12 no-stencil", "dx12 software", "dx12 software no-stencil"]);
// WGPU_BACKEND=vulkan,gl: no attempt leaves its backends.
assert!(attempts(ANY, true, Switch::Default).iter().all(|a| a.backends == ANY));
assert_eq!(attempts(Backends::GL, false, Switch::Default).len(), 4, "OpenGL alone is already the first");
// CADCRAFT_STENCIL: off is never on, on is never dropped.
assert!(attempts(ANY, false, Switch::Off).iter().all(|a| !a.stencil));
assert!(attempts(ANY, false, Switch::On).iter().all(|a| a.stencil));
assert_eq!(attempts(ANY, false, Switch::On).len() * 2, linux.len());
}
/// A stencil failure tries the same adapter without the stencil buffer; any other failure skips
/// that twin and tries the next adapter; past the last there is nothing.
#[test]
fn a_failure_picks_the_next_attempt_by_what_failed() {
let list = attempts(ANY, false, Switch::Default);
let at = |k: &str| list.iter().position(|a| key(a) == k).unwrap();
let next_key = |from: &str, failure| next(&list, at(from), failure).map(|i| key(&list[i]));
assert_eq!(next_key("vulkan+gl", Failure::Stencil).as_deref(), Some("vulkan+gl no-stencil"));
assert_eq!(next_key("vulkan+gl", Failure::Adapter).as_deref(), Some("gl"));
assert_eq!(next_key("vulkan+gl no-stencil", Failure::Adapter).as_deref(), Some("gl"));
assert_eq!(next_key("gl no-stencil", Failure::Stencil).as_deref(), Some("vulkan+gl software"));
assert_eq!(next_key("vulkan+gl software", Failure::Adapter), None);
assert_eq!(next_key("vulkan+gl software no-stencil", Failure::Stencil), None);
assert_eq!(next(&list, list.len(), Failure::Stencil), None);
// CADCRAFT_STENCIL=1: a stencil failure has no twin to fall back to, so the next adapter.
let on = attempts(Backends::DX12, false, Switch::On);
assert_eq!(next(&on, 0, Failure::Stencil), Some(1));
assert!(on[1].software);
}
/// Errors before the app exists are graphics failures; which kind decides the next attempt. The
/// app's own errors and the windowing system's are not, so they end the start as before.
#[test]
fn start_errors_are_sorted_by_what_failed() {
let no_adapter = eframe::Error::Wgpu(WgpuError::CustomNativeAdapterSelectionError("none".into()));
assert_eq!(classify(&no_adapter), Some(Failure::Adapter));
assert_eq!(classify(&eframe::Error::Wgpu(WgpuError::NoSurfaceFormatsAvailable)), Some(Failure::Adapter));
let refused = || wgpu::Error::Validation { source: Box::new(std::fmt::Error), description: "refused".into() };
assert_eq!(classify(&eframe::Error::Wgpu(WgpuError::ConfigureSurface(refused()))), Some(Failure::Stencil));
assert_eq!(classify(&eframe::Error::Wgpu(WgpuError::CreateRenderer(refused()))), Some(Failure::Stencil));
for failure in [Failure::Adapter, Failure::Stencil] {
let failed = eframe::Error::AppCreation(Box::new(CheckFailed { failure, message: "black".into() }));
assert_eq!(classify(&failed), Some(failure));
}
assert_eq!(classify(&eframe::Error::AppCreation("the app's own start".into())), None);
}
/// Only a graphics failure before the app exists is retried: once the app was created an error
/// ends the start (the app can't be built twice), as does an error that isn't the graphics'.
#[test]
fn only_a_start_failure_before_the_app_exists_is_retried() {
let list = attempts(Backends::DX12, false, Switch::Default);
let gpu = eframe::Error::Wgpu(WgpuError::NoSurfaceFormatsAvailable);
assert_eq!(retry(&list, 0, false, &gpu), Some(2));
assert_eq!(retry(&list, 0, true, &gpu), None);
let black = eframe::Error::AppCreation(Box::new(CheckFailed { failure: Failure::Stencil, message: "black".into() }));
assert_eq!(retry(&list, 0, false, &black), Some(1));
assert_eq!(retry(&list, 0, false, &eframe::Error::AppCreation("the app's own start".into())), None);
}
/// Each attempt takes its backends, its adapter and its stencil buffer.
#[test]
fn an_attempt_sets_its_backends_adapter_and_stencil_buffer() {
let mut options = eframe::NativeOptions::default();
for attempt in attempts(Backends::VULKAN | Backends::GL, false, Switch::Default) {
apply(&mut options, attempt);
let WgpuSetup::CreateNew(create) = &options.wgpu_options.wgpu_setup else { panic!("eframe creates its own wgpu setup") };
assert_eq!(create.instance_descriptor.backends, attempt.backends);
assert_eq!(create.native_adapter_selector.is_some(), attempt.software, "{attempt}");
assert_eq!(options.stencil_buffer > 0, attempt.stencil, "{attempt}");
}
}
/// The read-back is answered and passes on a working device, with and without a stencil
/// buffer. The device is made as the app makes it: on Windows DirectX 12 alone with FXC
/// (graphics.rs; an AMD driver crashes when OpenGL is created there, #31), and egui's limits for
/// the adapter.
#[test]
fn the_check_passes_on_a_device_that_draws() {
let mut options = eframe::NativeOptions::default();
crate::graphics::configure(&mut options, if cfg!(windows) { None } else { Some(Backends::all()) }, None);
let WgpuSetup::CreateNew(mut create) = options.wgpu_options.wgpu_setup else { panic!("eframe creates its own wgpu setup") };
create.instance_descriptor.backends.remove(Backends::BROWSER_WEBGPU);
let setup = WgpuSetup::CreateNew(create);
let instance = pollster::block_on(setup.new_instance());
let config = egui_wgpu::WgpuConfiguration { wgpu_setup: setup, ..Default::default() };
let Ok(rs) = pollster::block_on(egui_wgpu::RenderState::create(&config, &instance, None, Default::default())) else {
eprintln!("no graphics adapter here: the device check is left to machines with one");
return;
};
let info = rs.adapter.get_info();
for stencil in [None, Some(wgpu::TextureFormat::Stencil8)] {
// `check` takes no answer as a pass; a working device must answer, or every start on it
// would wait for the timeout.
let started = std::time::Instant::now();
let read = clear_and_read(&rs.device, &rs.queue, stencil);
let elapsed = started.elapsed();
assert_eq!(read, Ok(true), "{stencil:?} on {} ({:?}, {:?}) after {elapsed:?}", info.name, info.backend, info.device_type);
}
}
/// The read-back passes only when every pixel came back cleared: a target the clear never
/// reached still holds the zeros a texture starts as.
#[test]
fn the_check_fails_a_target_the_clear_did_not_reach() {
let row = |pixel: [u8; 4]| pixel.repeat(CHECK_WIDTH as usize);
assert!(read_back(&row(CHECK_COLOR)).is_ok());
assert!(read_back(&row([250, 6, 251, 255])).is_ok(), "a driver's rounding");
assert!(read_back(&row([0, 0, 0, 0])).is_err(), "never cleared");
assert!(read_back(&row([255, 0, 255, 0])).is_err(), "another alpha");
let mut one_off = row(CHECK_COLOR);
one_off[CHECK_COLOR.len() * 7 + 1] = 200;
assert!(read_back(&one_off).is_err(), "one pixel the clear missed");
assert!(read_back(&row(CHECK_COLOR)[..8]).is_err(), "a short read");
assert!(read_back(&[]).is_err());
}
/// A target that didn't come back cleared blames the adapter without the stencil buffer and the
/// stencil buffer with it; no answer is a pass, and isn't waited for twice.
#[test]
fn a_failed_pass_names_what_failed() {
let stencil = Some(wgpu::TextureFormat::Stencil8);
let failure = |black_with: Option<bool>| {
passes(stencil, |format| if black_with.is_none_or(|with| with == format.is_some()) { Err("black".into()) } else { Ok(true) })
.map_err(|e| e.failure)
};
assert_eq!(failure(Some(false)), Err(Failure::Adapter), "black without the stencil buffer");
assert_eq!(failure(None), Err(Failure::Adapter), "black either way");
assert_eq!(failure(Some(true)), Err(Failure::Stencil), "black only with it");
let mut asked = Vec::new();
let unanswered = passes(stencil, |format| {
asked.push(format);
Ok(false)
});
assert!(unanswered.is_ok());
assert_eq!(asked, [None], "no second wait after no answer");
let mut asked = Vec::new();
let answered = passes(stencil, |format| {
asked.push(format);
Ok(true)
});
assert!(answered.is_ok());
assert_eq!(asked, [None, stencil], "both passes when the first answered");
}
/// The test switch names attempts by position and step, and nothing else trips it.
#[test]
fn the_fault_switch_names_one_step_of_one_attempt() {
assert!(fault::listed(Some("0:stencil"), 0, "stencil"));
assert!(fault::listed(Some(" 2:adapter , 0:draw"), 0, "draw"));
assert!(!fault::listed(Some("0:stencil"), 1, "stencil"));
assert!(!fault::listed(Some("10:draw"), 1, "draw"));
assert!(!fault::listed(Some("0:stencils"), 0, "stencil"));
assert!(!fault::listed(None, 0, "draw"));
}
/// The log and the status bar tell the attempts apart.
#[test]
fn an_attempt_names_what_it_tries() {
let list = attempts(ANY, false, Switch::Default);
let names: std::collections::BTreeSet<String> = list.iter().map(ToString::to_string).collect();
assert_eq!(names.len(), list.len());
}
}
-58
View File
@@ -428,62 +428,4 @@ mod tests {
received.sort();
assert_eq!(received, handed);
}
/// A Nightly profile on Windows keeps its single-instance AF_UNIX socket under
/// `<profile>\single-instance\*.sock`. Both a live socket (while a first Nightly copy is
/// running and a second document launch prepares to hand off) and a leftover/stale socket
/// (after the first copy exits, or from an earlier Nightly build) must pass profile
/// validation, and the next launch must reclaim the stale socket and accept subsequent
/// document handoffs.
#[cfg(windows)]
#[test]
fn nightly_profile_allows_live_and_stale_single_instance_socket_for_handoff_and_reopen() {
use std::ffi::OsString;
use craft_nightly::{BuildFlavor, Profile, StartupOptions, launch_arguments, parse_startup, validate_and_prepare_root};
let profile = std::env::temp_dir().join(format!("cc-ni-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&profile);
std::fs::create_dir_all(&profile).unwrap();
let _cleanup = Cleanup(profile.clone());
let spec = crate::profile_root::spec();
let prepare_profile = |doc: &str| {
let argv = launch_arguments(&profile, &[OsString::from(doc)]);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
let Profile::NightlyV1(root) = launch.profile else {
panic!("expected NightlyV1 profile");
};
validate_and_prepare_root(&root, &spec).unwrap();
launch.passthrough_args
};
let sock_path = socket_path(Some(&profile)).unwrap();
std::fs::create_dir_all(sock_path.parent().unwrap()).unwrap();
if !can_bind(&sock_path) {
return;
}
// 1. Live socket in `<profile>\single-instance\*.sock`: second-document launch must not
// be refused by profile validation before handoff.
let listener = uds_windows::UnixListener::bind(&sock_path).unwrap();
assert_eq!(prepare_profile("second.dwg"), [OsString::from("second.dwg")]);
// 2. First instance exits leaving a leftover/stale socket behind: reopening must pass
// profile validation and reclaim the socket as the new primary instance.
drop(listener);
assert!(sock_path.exists(), "stale socket remains after exit");
assert_eq!(prepare_profile("reopen.dwg"), [OsString::from("reopen.dwg")]);
let Claim::Primary(server) = claim(&[], false, Some(&profile)) else {
panic!("failed to reclaim stale single-instance socket in nightly profile");
};
// 3. While the reclaimed primary instance is running (socket + election lock both live in
// `<profile>\single-instance`), launching a second document passes profile validation
// and hands off to the running instance.
let second_doc = profile.join("second.dwg").to_string_lossy().into_owned();
assert_eq!(prepare_profile(&second_doc), [OsString::from(&second_doc)]);
assert!(matches!(claim(std::slice::from_ref(&second_doc), true, Some(&profile)), Claim::HandedOff));
assert_eq!(server.take_paths(), [PathBuf::from(&second_doc)]);
}
}
+14 -17
View File
@@ -213,14 +213,16 @@ 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 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;
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()
};
first.save_if_changed(&ui, Instant::now()).unwrap();
let bytes = fs::read(&path).unwrap();
let value: Value = serde_json::from_slice(&bytes).unwrap();
@@ -311,9 +313,7 @@ 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")));
let mut ui = UiState::default();
ui.show_palettes = false;
store.save_if_changed(&ui, Instant::now()).unwrap();
store.save_if_changed(&UiState { show_palettes: false, ..Default::default() }, Instant::now()).unwrap();
assert_eq!(fs::read(&path).unwrap(), bytes);
}
fs::remove_dir_all(directory).unwrap();
@@ -351,8 +351,7 @@ mod tests {
let path = directory.join("workspace.json");
let (mut store, _, _) = Workspace::at(Some(path.clone()));
let start = Instant::now();
let mut ui = UiState::default();
ui.history_lines = 1;
let mut ui = UiState { history_lines: 1, ..Default::default() };
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() {
@@ -376,8 +375,7 @@ mod tests {
let directory = temp_dir();
let path = directory.join("workspace.json");
let (mut store, _, _) = Workspace::at(Some(path.clone()));
let mut ui = UiState::default();
ui.show_palettes = false;
let mut ui = UiState { show_palettes: false, ..Default::default() };
store.save_if_changed(&ui, Instant::now()).unwrap();
let good = fs::read(&path).unwrap();
ui.collapsed_groups = vec!["x".repeat(257)];
@@ -393,8 +391,7 @@ mod tests {
let (mut store, _, _) = Workspace::at(Some(path.clone()));
// Simulate a destination becoming unavailable after startup.
fs::create_dir(&path).unwrap();
let mut ui = UiState::default();
ui.show_palettes = false;
let ui = UiState { show_palettes: false, ..Default::default() };
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);
-1
View File
@@ -1 +0,0 @@
9fa32aecf2759cd61bb216a958df68da619798f3
+20 -23
View File
@@ -206,7 +206,8 @@ pub fn next_id(d: &Drawing) -> u32 {
/// Interpret a constraint against the model's current parameters, appending its auxiliary
/// unknowns (contact parameters) to the model, settled with the geometry held still.
pub(crate) fn interpret(c: &Constraint, model: &mut Model, target: f64) -> Result<Built, String> {
let mut b = Built::new(c, model, &model.x0, target)?;
let x = model.x0.clone();
let mut b = Built::new(c, model, &x, target)?;
if b.aux_init.is_empty() {
return Ok(b);
}
@@ -526,26 +527,22 @@ pub fn solve(d: &mut Drawing, opts: &SolveOptions) -> Result<SolveReport, SolveE
/// Largest residual of each constraint at the current geometry (`None` when it cannot be
/// interpreted).
pub fn residuals(d: &Drawing) -> Vec<(u32, Option<f64>)> {
residuals_with_model(d, residual_model(d)).collect()
}
fn residual_model(d: &Drawing) -> Model {
let handles: Vec<Handle> = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
Model::build(d, &handles)
}
fn residuals_with_model(d: &Drawing, mut model: Model) -> impl Iterator<Item = (u32, Option<f64>)> + '_ {
let mut e = env(d);
let mut out = Vec::new();
d.constraints.iter().take(MAX_CONSTRAINTS).map(move |c| {
let target = if c.kind.is_dimensional() { constraint_value(&mut e, c).ok() } else { Some(0.0) };
let r = target.and_then(|t| interpret(c, &mut model, t).ok()).map(|b| {
out.clear();
b.eval(&model, &model.x0, &mut out);
lm::max_abs(&out)
});
(c.id, r)
})
let handles: Vec<Handle> = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
let mut model = Model::build(d, &handles);
d.constraints
.iter()
.take(MAX_CONSTRAINTS)
.map(|c| {
let target = if c.kind.is_dimensional() { constraint_value(&mut e, c).ok() } else { Some(0.0) };
let r = target.and_then(|t| interpret(c, &mut model, t).ok()).map(|b| {
let mut out = Vec::new();
b.eval(&model, &model.x0, &mut out);
lm::max_abs(&out)
});
(c.id, r)
})
.collect()
}
/// Put back what each Fix locks where `before` had it, and report whether anything moved.
@@ -686,9 +683,9 @@ pub fn moved_anchors(d: &Drawing, before: &Drawing) -> Vec<(u32, Vec2)> {
/// True when every interpretable constraint holds at the current geometry.
pub fn all_satisfied(d: &Drawing) -> bool {
let model = residual_model(d);
let tol = scale_tol(&model.x0) * 10.0;
residuals_with_model(d, model).all(|(_, r)| r.is_none_or(|v| v <= tol))
let handles: Vec<Handle> = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
let tol = scale_tol(&Model::build(d, &handles).x0) * 10.0;
residuals(d).iter().all(|(_, r)| r.is_none_or(|v| v <= tol))
}
/// Check that a constraint's references make sense for its type.
+16 -36
View File
@@ -222,27 +222,6 @@ pub(crate) fn null_space(m: &[f64], rows: usize, cols: usize) -> (usize, Vec<Vec
(rank, basis)
}
/// Weighted normal matrix J W⁻¹ Jᵀ. Most constraint rows depend on only a few free coordinates.
fn normal_matrix(jac: &[f64], inverse_weights: &[f64], rows: usize) -> Vec<f64> {
let mut matrix = vec![0.0; rows * rows];
let mut terms = Vec::new();
let width = inverse_weights.len();
for (i, row) in jac.chunks_exact(width).enumerate() {
terms.clear();
terms.extend(row.iter().enumerate().filter(|(_, value)| **value != 0.0).map(|(col, &value)| (col, value, inverse_weights[col])));
for (k, other) in jac.chunks_exact(width).enumerate().skip(i) {
let sum = if terms.len() == width {
row.iter().zip(other).zip(inverse_weights).fold(0.0, |sum, ((&v, &other_v), &weight)| sum + v * other_v * weight)
} else {
terms.iter().fold(0.0, |sum, &(col, v, weight)| sum + v * other[col] * weight)
};
matrix[i * rows + k] = sum;
matrix[k * rows + i] = sum;
}
}
matrix
}
/// Run the solver from `x0`. Only `free` parameters change.
pub(crate) fn solve(f: &dyn Fn(&[f64], &mut Vec<f64>), x0: &[f64], free: &[usize], weights: &[f64], tol: f64, max_iter: usize) -> Outcome {
let mut x = x0.to_vec();
@@ -264,7 +243,22 @@ pub(crate) fn solve(f: &dyn Fn(&[f64], &mut Vec<f64>), x0: &[f64], free: &[usize
while iter < max_iter {
iter += 1;
let jac = jacobian(f, &x, free, rows);
let a = normal_matrix(&jac, &winv, rows);
// A = J W⁻¹ Jᵀ
let mut a = vec![0.0; rows * rows];
for i in 0..rows {
for k in i..rows {
let mut s = 0.0;
for (c, w) in winv.iter().enumerate() {
s += jac.get(i * nf + c).copied().unwrap_or(0.0) * jac.get(k * nf + c).copied().unwrap_or(0.0) * w;
}
if let Some(v) = a.get_mut(i * rows + k) {
*v = s;
}
if let Some(v) = a.get_mut(k * rows + i) {
*v = s;
}
}
}
let diag_max = (0..rows).map(|i| a.get(i * rows + i).copied().unwrap_or(0.0)).fold(0.0f64, f64::max).max(1e-12);
let mut improved = false;
for _ in 0..12 {
@@ -316,20 +310,6 @@ pub(crate) fn solve(f: &dyn Fn(&[f64], &mut Vec<f64>), x0: &[f64], free: &[usize
mod tests {
use super::*;
#[test]
fn sparse_and_dense_constraints_keep_their_weighted_cross_terms() {
// Includes an empty row, an unconstrained column in a sparse row, and a tiny derivative.
let rows = [[-0., 0., -0., -0.], [2., 0., -3., 0.], [0., 0., 0., 1e-12], [1., 3., 2., -5.]];
let weights = [1., 0.25, 0.5, 2.];
let matrix = normal_matrix(&rows.concat(), &weights, rows.len());
for (i, row) in rows.iter().enumerate() {
for (k, other) in rows.iter().enumerate() {
let reference = (0..weights.len()).fold(0.0, |sum, c| sum + row[c] * other[c] * weights[c]);
assert_eq!(matrix[i * rows.len() + k].to_bits(), reference.to_bits());
}
}
}
#[test]
fn dense_and_rank() {
let y = solve_dense(vec![2.0, 1.0, 1.0, 3.0], vec![3.0, 5.0], 2).unwrap();
-2
View File
@@ -328,8 +328,6 @@ fn invalid_references_and_purge() {
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
backwards: false,
upside_down: false,
}),
);
let bad = |d: &mut Drawing, c: Constraint| assert!(add(d, c, &SolveOptions::default()).is_err());
+5 -14
View File
@@ -46,21 +46,15 @@ mod layout;
mod proxy;
mod text;
mod wipeout;
mod xdata;
pub use xdata::{
MAX_XDATA_APP_NAME, MAX_XDATA_CHUNK, MAX_XDATA_GROUPS, MAX_XDATA_STRING, RESERVED_XDATA_APPS, XdataError, check_xdata_app_name,
check_xdata_groups, is_model_xdata, is_model_xdata_app, is_reserved_xdata_app, is_xdata_group, set_xdata_app, xdata_apps, xdata_of,
};
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal};
pub use common::{Common, Handle, Lineweight, RawTag, Transparency};
pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, PolyfaceMesh, Polyline3d, RayLine, Solid};
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
pub use fill::{Gradient, Hatch, HatchLoop};
pub use layout::{Image, Table, TableCell, Viewport, ViewportUcs};
pub use proxy::{ProxyTables, TableOrder, proxy_entities};
pub use text::{HAlign, MText, MTextBackground, MTextColumnType, MTextColumns, Text, VAlign};
pub use layout::{Image, Table, TableCell, Viewport};
pub use proxy::{ProxyTables, proxy_entities};
pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign};
pub use wipeout::Wipeout;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Unknown {
@@ -405,9 +399,7 @@ impl EntityKind {
t3(p);
}
if let DimKind::Linear { rotation } = &mut d.kind {
// A mirror reflects the dimension line's direction about the mirror line:
// `rot` is twice the mirror line's angle, so `a` lands at `rot - a`.
*rotation = cadcraft_geom::norm_angle(if mirror { rot - *rotation } else { *rotation + rot });
*rotation = cadcraft_geom::norm_angle(*rotation + rot);
}
d.marks.transform(&t3, rot, s, mirror);
d.block = None;
@@ -625,8 +617,7 @@ impl EntityKind {
EntityKind::Polyline3d(p) => p.points.iter().map(|q| q.xy()).collect(),
EntityKind::Spline(s) => {
if s.fit.is_empty() {
// One grip per control vertex: a closed spline's repeats have none (#3566).
s.control.iter().take(s.distinct_controls()).copied().collect()
s.control.clone()
} else {
s.fit.clone()
}
-40
View File
@@ -154,43 +154,7 @@ impl AttribProps {
#[derive(Clone, Copy, Debug)]
pub struct TagKey<'a>(pub &'a str);
#[cfg(test)]
std::thread_local! {
static TAG_CROSS_PROBE: std::cell::Cell<Option<(usize, [usize; 2])>> = const { std::cell::Cell::new(None) };
}
#[cfg(test)]
fn record_tag_cross_probe(left: &str, right: &str) {
TAG_CROSS_PROBE.with(|probe| {
let Some((position, mut counts)) = probe.get() else { return };
match (left.as_bytes().get(position), right.as_bytes().get(position)) {
(Some(b'A'), Some(b'D')) => counts[0] += 1,
(Some(b'D'), Some(b'A')) => counts[1] += 1,
_ => return,
}
probe.set(Some((position, counts)));
});
}
impl TagKey<'_> {
/// Count comparisons in both directions between the A and D fixture tag sets.
#[cfg(test)]
pub(crate) fn with_cross_probes<T>(position: usize, f: impl FnOnce() -> T) -> (T, [usize; 2]) {
struct Restore(Option<(usize, [usize; 2])>);
impl Drop for Restore {
fn drop(&mut self) {
TAG_CROSS_PROBE.with(|probe| probe.set(self.0));
}
}
TAG_CROSS_PROBE.with(|probe| {
let _restore = Restore(probe.replace(Some((position, [0; 2]))));
let value = f();
(value, probe.get().map_or([0; 2], |(_, counts)| counts))
})
}
/// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case`
/// finds equal.
fn folded(&self) -> impl Iterator<Item = u8> + '_ {
@@ -200,8 +164,6 @@ impl TagKey<'_> {
impl PartialEq for TagKey<'_> {
fn eq(&self, other: &Self) -> bool {
#[cfg(test)]
record_tag_cross_probe(self.0, other.0);
self.0.eq_ignore_ascii_case(other.0)
}
}
@@ -210,8 +172,6 @@ impl Eq for TagKey<'_> {}
impl Ord for TagKey<'_> {
fn cmp(&self, other: &Self) -> Ordering {
#[cfg(test)]
record_tag_cross_probe(self.0, other.0);
self.folded().cmp(other.folded())
}
}
+1 -8
View File
@@ -100,9 +100,7 @@ impl DimMarks {
/// Transform the points and angles (part of [`super::EntityKind::transform`]).
pub(super) fn transform(&mut self, t3: &dyn Fn(&mut Vec3), rot: f64, s: f64, mirror: bool) {
if let Some(a) = &mut self.oblique {
// A mirror reflects a direction about the mirror line: `rot` is the transformed X
// axis (twice the mirror line's angle), so a direction `a` lands at `rot - a`.
*a = cadcraft_geom::norm_angle(if mirror { rot - *a } else { *a + rot });
*a = cadcraft_geom::norm_angle(if mirror { rot - (*a - rot) } else { *a + rot });
}
if let Some(j) = &mut self.jog_line {
t3(j);
@@ -197,11 +195,6 @@ pub struct Leader {
pub spline: bool,
#[serde(default = "standard")]
pub style: String,
/// Per-leader style overrides (the `ACAD` DSTYLE xdata of a LEADER): DimStyle field names
/// (camelCase) → values, merged over the named style as a dimension's are. A leader draws
/// with its arrow size, overall scale, leader arrowhead and dimension line colour.
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
pub overrides: serde_json::Map<String, serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+2 -3
View File
@@ -7,9 +7,8 @@ pub struct HatchLoop {
pub vertices: Vec<PolyVertex>,
#[serde(default)]
pub outer: bool,
/// Original DXF group 92 bits. Writing keeps only Textbox (8) and Outermost (16), derives
/// External (1) from `outer`, and sets Polyline (2). Derived (4) stays here but is not
/// written: the pixel size (group 47) it needs is not kept (#3664).
/// Original DXF group 92 bits. Writing keeps only Derived (4), Textbox (8) and
/// Outermost (16), derives External (1) from `outer`, and sets Polyline (2).
/// None uses the flags of a locally created loop.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub boundary_flags: Option<i64>,
+1 -38
View File
@@ -1,6 +1,6 @@
use cadcraft_geom::Mat3;
use super::common::{Handle, RawTag};
use super::common::Handle;
use super::{Color, Deserialize, Serialize, Vec2, Vec3, standard, yes};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -27,19 +27,6 @@ pub struct Viewport {
/// Display on (MVIEW ON/OFF). An off viewport shows its border but no model space.
#[serde(default = "yes")]
pub on: bool,
/// The viewport's own UCS (DXF groups 110–112, 79, 146, 345, 346), the one it keeps while
/// `ucs_per_viewport` is set.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ucs: Option<ViewportUcs>,
/// UCS per viewport (UCSVP, DXF group 71): the viewport keeps its own UCS instead of
/// following the current one.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub ucs_per_viewport: bool,
/// The viewport's groups CADCraft doesn't model (snap, grid, lens and clipping, render mode,
/// plot style sheet, shade plot, visual style, background, lighting…), as read: written back
/// on save and carried by copies, their references pointed at what they named.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub extra: Vec<RawTag>,
/// The view twist (DVIEW TWist inside the viewport; DXF group 51): radians counterclockwise,
/// the model view seen through the viewport is turned on the sheet by it. 0 is untwisted.
#[serde(default, skip_serializing_if = "is_zero_twist")]
@@ -75,27 +62,6 @@ impl Viewport {
}
}
/// A layout viewport's own UCS.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ViewportUcs {
pub origin: Vec3,
pub x_axis: Vec3,
pub y_axis: Vec3,
/// Elevation (DXF group 146).
#[serde(default)]
pub elevation: f64,
/// Orthographic type (DXF group 79): 0 none, 1 top, 2 bottom, 3 front, 4 back, 5 left, 6 right.
#[serde(default)]
pub ortho: u8,
/// The named UCS it is, by UCS table name (DXF group 345).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub named: Option<String>,
/// The UCS an orthographic one is based on, by UCS table name (DXF group 346); none: the WCS.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub base: Option<String>,
}
impl Default for Viewport {
fn default() -> Self {
Viewport {
@@ -110,9 +76,6 @@ impl Default for Viewport {
layer_colors: Vec::new(),
clip: None,
on: true,
ucs: None,
ucs_per_viewport: false,
extra: Vec::new(),
twist: 0.0,
}
}
+82 -390
View File
@@ -35,36 +35,6 @@ pub struct ProxyTables {
pub styles: Vec<(String, String)>,
}
/// The LAYER and LTYPE names the indices of proxy graphics count in, in table order (the
/// linetypes without ByBlock and ByLayer, as in [`ProxyTables`]).
#[derive(Clone, Copy, Debug, Default)]
pub struct TableOrder<'a> {
pub layers: &'a [String],
pub linetypes: &'a [String],
}
/// The chunk that sets the layer by its index (ATTRIBUTE_LAYER).
const LAYER_CHUNK: u32 = 16;
/// The chunk that sets the linetype by its index (ATTRIBUTE_LINETYPE).
const LINETYPE_CHUNK: u32 = 18;
/// The linetype indices that stand for ByBlock and ByLayer.
const LINETYPE_BYBLOCK: u32 = 32766;
const LINETYPE_BYLAYER: u32 = 32767;
/// The names a record's own graphics show for its table indices (`Unknown::names_by_index`).
#[derive(Default)]
struct Learned {
layers: std::collections::HashMap<u32, Option<String>>,
linetypes: std::collections::HashMap<u32, String>,
}
/// The names that stand for the table indices a record uses while it is decoded again to learn
/// them; an index without one leaves the layer, or gives ByLayer, as one past a table does.
struct Marks {
layers: std::collections::HashMap<u32, String>,
linetypes: std::collections::HashMap<u32, String>,
}
impl Unknown {
/// The proxy graphics bytes of an entity: the 310 groups after its size group (92, or 160 in
/// newer files), cut to that size. An ACAD_PROXY_ENTITY holds them in its proxy data: the size
@@ -122,22 +92,21 @@ impl Unknown {
Some((at, size))
}
/// The record's groups with the table indices of its proxy graphics (ATTRIBUTE_LAYER and
/// ATTRIBUTE_LINETYPE) turned into the written tables `written`, by name; everything else as
/// read. The name of an index is the one the record's own decoded graphics use after it (so a
/// proxy copied from another drawing, or one whose layer was renamed, keeps what it shows);
/// an index no drawn entity follows takes the name from the file's tables `read` (see
/// [`crate::Drawing::proxy_layers`] and [`crate::Drawing::proxy_linetypes`]).
///
/// A layer that is gone becomes layer 0 (the proxy's own layer, as in a block); a layer index
/// past the table, or one of a record without a name, stays past the written one, which keeps
/// the layer before it as AutoCAD does. A linetype that is gone, or an index that names none,
/// becomes ByLayer (32767, what an index past the table means too); ByBlock (32766) and
/// ByLayer stay. The picture of a kept dimension (#3438) is rewritten too: by the tables alone
/// when the dimension draws its block instead. Only the 310 groups that hold the declared size
/// are read and rewritten. `None` when no index changes, or the graphics aren't readable.
pub fn with_proxy_tables(&self, read: TableOrder<'_>, written: TableOrder<'_>) -> Option<Vec<RawTag>> {
use std::collections::HashMap;
/// The record's groups with the layer indices of its proxy graphics (ATTRIBUTE_LAYER) turned
/// into the written LAYER table `written`, by name; everything else as read. The name of an
/// index is the one the record's own decoded graphics draw on after it (so a proxy copied from
/// another drawing, or one whose layer was renamed, keeps the layer it shows); an index no
/// drawn entity follows takes the name from the file's table `read` (see
/// [`crate::Drawing::proxy_layers`]). A layer that is gone becomes layer 0 (the proxy's own
/// layer, as in a block); an index past the table, or one of a record without a name, stays
/// past the written one, which keeps the layer before it as AutoCAD does. Only the 310 groups
/// that hold the declared size are read and rewritten. `None` when no index changes, or the
/// graphics aren't readable.
pub fn with_proxy_layers(&self, read: &[String], written: &[String]) -> Option<Vec<RawTag>> {
// Only a proxy entity's own graphics: a kept dimension draws from its block instead.
if !self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") {
return None;
}
let (at, size) = self.graphics_size_group()?;
let (mut bytes, mut groups) = (Vec::new(), Vec::new());
for i in (at + 1..self.tags.len()).take_while(|&i| self.tags[i].code == 310) {
@@ -151,72 +120,49 @@ impl Unknown {
groups.push((i, bytes.len() - before));
}
let end = size.min(bytes.len());
// The ATTRIBUTE_LAYER (16) and ATTRIBUTE_LINETYPE (18) chunks: where each index sits.
let mut refs: Vec<(usize, u32, u32)> = Vec::new();
// The ATTRIBUTE_LAYER chunks: where each index sits.
let mut refs: Vec<(usize, u32)> = Vec::new();
let mut chunk = 8usize;
while let (Some(len), Some(kind)) = (u32_at(&bytes[..end], chunk), u32_at(&bytes[..end], chunk + 4)) {
let len = len as usize;
if len < 8 || chunk.saturating_add(len) > end {
break;
}
if (kind == LAYER_CHUNK || kind == LINETYPE_CHUNK)
if kind == 16
&& let Some(i) = u32_at(&bytes[..chunk + len], chunk + 8)
{
refs.push((chunk + 8, kind, i));
refs.push((chunk + 8, i));
}
chunk += len;
}
if refs.is_empty() {
return None;
}
let of = |k: u32| -> Vec<u32> { refs.iter().filter(|r| r.1 == k).map(|r| r.2).collect() };
let learned = self.names_by_index(&bytes[..end], &of(LAYER_CHUNK), &of(LINETYPE_CHUNK), read.layers);
let indices: Vec<u32> = refs.iter().map(|r| r.1).collect();
let learned = self.layers_by_index(&bytes[..end], &indices);
if read.is_empty() && learned.is_empty() {
return None;
}
// Each written name's first place, found once.
let places = |names: &[String]| {
let mut place: HashMap<String, u32> = HashMap::new();
for (p, n) in names.iter().enumerate() {
place.entry(n.to_ascii_lowercase()).or_insert(u32::try_from(p).unwrap_or(u32::MAX));
}
place
};
let (layer_at, linetype_at) = (places(written.layers), places(written.linetypes));
let zero = layer_at.get("0").copied();
let len = |names: &[String]| u32::try_from(names.len()).unwrap_or(u32::MAX);
let layers_past = len(written.layers).max(len(read.layers));
let linetypes_past = len(written.linetypes).max(len(read.linetypes));
// Without the file's table or names from the graphics, an index can't be placed.
let known_layers = !read.layers.is_empty() || !learned.layers.is_empty();
let known_linetypes = !read.linetypes.is_empty() || !learned.linetypes.is_empty();
let layer = |i: u32| {
let name = match learned.layers.get(&i) {
Some(name) => name.as_deref(),
None => read.layers.get(i as usize).map(String::as_str),
};
match name.filter(|n| !n.is_empty()) {
Some(name) => layer_at.get(&name.to_ascii_lowercase()).copied().or(zero).unwrap_or(i),
None if i >= layers_past => i,
None => layers_past,
}
};
let linetype = |i: u32| {
if i == LINETYPE_BYBLOCK || i == LINETYPE_BYLAYER {
return i;
}
let name = learned.linetypes.get(&i).or_else(|| read.linetypes.get(i as usize)).map(String::as_str);
let by = |n: &str| n.eq_ignore_ascii_case("ByLayer") || n.eq_ignore_ascii_case("ByBlock");
match name.filter(|n| !n.is_empty() && !by(n)) {
Some(name) => linetype_at.get(&name.to_ascii_lowercase()).copied().unwrap_or(LINETYPE_BYLAYER),
None if i >= linetypes_past => i,
None => LINETYPE_BYLAYER,
}
};
let mut resolved: HashMap<(u32, u32), u32> = HashMap::new();
let mut place: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
for (p, n) in written.iter().enumerate() {
place.entry(n.to_ascii_lowercase()).or_insert(u32::try_from(p).unwrap_or(u32::MAX));
}
let zero = place.get("0").copied();
let past = u32::try_from(written.len()).unwrap_or(u32::MAX).max(u32::try_from(read.len()).unwrap_or(u32::MAX));
let mut resolved: std::collections::HashMap<u32, u32> = std::collections::HashMap::new();
let mut changed = false;
for (offset, kind, i) in refs {
let j = *resolved.entry((kind, i)).or_insert_with(|| match kind {
LAYER_CHUNK if known_layers => layer(i),
LINETYPE_CHUNK if known_linetypes => linetype(i),
_ => i,
for (offset, i) in refs {
let j = *resolved.entry(i).or_insert_with(|| {
let name = match learned.get(&i) {
Some(name) => name.as_deref(),
None => read.get(i as usize).map(String::as_str),
};
match name.filter(|n| !n.is_empty()) {
Some(name) => place.get(&name.to_ascii_lowercase()).copied().or(zero).unwrap_or(i),
None if i >= past => i,
None => past,
}
});
if j != i {
bytes[offset..offset + 4].copy_from_slice(&j.to_le_bytes());
@@ -235,20 +181,15 @@ impl Unknown {
Some(tags)
}
/// The layer and linetype each index of `bytes` (the record's ATTRIBUTE_LAYER indices
/// `layers` and ATTRIBUTE_LINETYPE indices `linetypes`) stands for in this record's decoded
/// graphics: the bytes decoded again with each index `i` named `#i` give the same entities in
/// the same order, so each one's marker meets its real name. Only the indices the record uses
/// get a marker, so the work follows the chunks, not the largest index.
///
/// A layer is `None` for an index after which the graphics stay on the layer before (one past
/// the table it was read with). When the entities after an index stay on the layer before but
/// the file's LAYER table `read` names that layer at the index, it names it. An index whose
/// entities disagree is left out. Empty when the graphics don't match (not decoded from these
/// bytes, such as a kept dimension's reference to its block).
fn names_by_index(&self, bytes: &[u8], layers: &[u32], linetypes: &[u32], read: &[String]) -> Learned {
use std::collections::{HashMap, HashSet};
/// What the entities after a layer index say about it.
/// The layer each ATTRIBUTE_LAYER index of `bytes` (the record's `indices`) stands for in
/// this record's decoded graphics: the bytes decoded again with index `i` named `#i` give the
/// same entities in the same order, so each one's marker meets its real layer. `None` for an
/// index after which the graphics stay on the layer before (one past the table it was read
/// with). An index above 65,535 isn't named here (it resolves through the file's table, like
/// one no entity follows). Empty when the graphics don't match
/// (not decoded from these bytes); an index whose entities disagree is left out.
fn layers_by_index(&self, bytes: &[u8], indices: &[u32]) -> std::collections::HashMap<u32, Option<String>> {
/// What the entities after an index say about it.
enum Seen {
/// They are on this layer, and the ones before them weren't.
Named(String),
@@ -258,42 +199,27 @@ impl Unknown {
/// It keeps the layer before (two kept observations on different layers).
Keeps,
}
let mut out = Learned::default();
if self.graphics.is_empty() || self.graphics.iter().any(|g| matches!(g.kind, EntityKind::Insert(_))) {
const MAX: u32 = 65_535;
let mut out: std::collections::HashMap<u32, Option<String>> = std::collections::HashMap::new();
if self.graphics.is_empty() {
return out;
}
let mark = |i: &u32| (*i, format!("\u{1}{i}"));
let marks = Marks {
layers: layers.iter().map(mark).collect(),
linetypes: linetypes.iter().filter(|&&i| i != LINETYPE_BYBLOCK && i != LINETYPE_BYLAYER).map(mark).collect(),
};
let marked = decode(bytes, &ProxyTables::default(), Handle(0), Some(&marks));
let max = indices.iter().copied().filter(|&i| i <= MAX).max().unwrap_or(0);
let markers = ProxyTables { layers: (0..=max).map(|i| format!("\u{1}{i}")).collect(), ..ProxyTables::default() };
let marked = proxy_entities(bytes, &markers, Handle(0));
if marked.len() != self.graphics.len() {
return out;
}
let same = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
let index = |name: &str| name.strip_prefix('\u{1}').and_then(|i| i.parse::<u32>().ok());
let mut seen: HashMap<u32, Seen> = HashMap::new();
let mut conflict = HashSet::new();
let mut linetype_conflict = HashSet::new();
let mut seen: std::collections::HashMap<u32, Seen> = std::collections::HashMap::new();
let mut conflict = std::collections::HashSet::new();
let mut before: Option<(&str, &str)> = None;
for (m, g) in marked.iter().zip(&self.graphics) {
if let Some(i) = index(&m.common.linetype) {
match out.linetypes.get(&i) {
Some(a) if !same(a, &g.common.linetype) => {
linetype_conflict.insert(i);
}
Some(_) => {}
None => {
out.linetypes.insert(i, g.common.linetype.clone());
}
}
}
let (mark, real) = (m.common.layer.as_str(), g.common.layer.as_str());
let changed_here = before.is_none_or(|(prev_mark, _)| prev_mark != mark);
let kept = before.is_some_and(|(_, prev_real)| same(prev_real, real));
before = Some((mark, real));
let Some(i) = index(mark) else { continue };
let Some(i) = mark.strip_prefix('\u{1}').and_then(|i| i.parse::<u32>().ok()) else { continue };
if !changed_here {
// The same marker on another real layer: an index in between (one past the table
// the marker decoding doesn't see as such) changed it, so this one can't be named.
@@ -321,19 +247,10 @@ impl Unknown {
}
}
for (i, s) in seen {
if conflict.contains(&i) {
continue;
if !conflict.contains(&i) {
out.insert(i, if let Seen::Named(n) = s { Some(n) } else { None });
}
let name = match s {
Seen::Named(n) => Some(n),
// Staying on the layer before says nothing when the table names that layer here:
// the index sets it again.
Seen::Kept(n) => read.get(i as usize).filter(|r| !r.is_empty() && same(r, &n)).map(|_| n),
Seen::Keeps => None,
};
out.layers.insert(i, name);
}
out.linetypes.retain(|i, _| !linetype_conflict.contains(i));
out
}
}
@@ -344,27 +261,16 @@ impl crate::Drawing {
/// it at once. RENAME calls it, LAYMRG for each merged layer (its graphics move to the
/// target, as its objects do) and LAYDEL with layer 0.
pub fn rename_proxy_layer(&mut self, old: &str, new: &str) {
rename_in(&mut self.proxy_layers, old, new);
self.rename_in_graphics(old, new, TableName::Layer);
}
/// Rename linetype `old` to `new` where proxy graphics use it, as
/// [`crate::Drawing::rename_proxy_layer`] does for a layer: RENAME calls it.
pub fn rename_proxy_linetype(&mut self, old: &str, new: &str) {
rename_in(&mut self.proxy_linetypes, old, new);
self.rename_in_graphics(old, new, TableName::Linetype);
}
/// Rename the graphics' `field` from `old` to `new`.
fn rename_in_graphics(&mut self, old: &str, new: &str, field: TableName) {
let uses = |e: &Entity| matches!(&e.kind, EntityKind::Unknown(u) if u.graphics.iter().any(|g| field.of(&g.common).eq_ignore_ascii_case(old)));
for n in &mut self.proxy_layers {
if n.eq_ignore_ascii_case(old) {
*n = new.to_string();
}
}
let uses = |e: &Entity| matches!(&e.kind, EntityKind::Unknown(u) if u.graphics.iter().any(|g| g.common.layer.eq_ignore_ascii_case(old)));
let fix = |e: &mut Entity| {
if let EntityKind::Unknown(u) = &mut e.kind {
for g in &mut u.graphics {
let n = field.of_mut(&mut g.common);
if n.eq_ignore_ascii_case(old) {
*n = new.to_string();
}
for g in u.graphics.iter_mut().filter(|g| g.common.layer.eq_ignore_ascii_case(old)) {
g.common.layer = new.to_string();
}
}
};
@@ -384,36 +290,6 @@ impl crate::Drawing {
}
}
/// The table name of an entity's properties that proxy graphics set by index.
#[derive(Clone, Copy)]
enum TableName {
Layer,
Linetype,
}
impl TableName {
fn of(self, c: &Common) -> &str {
match self {
TableName::Layer => &c.layer,
TableName::Linetype => &c.linetype,
}
}
fn of_mut(self, c: &mut Common) -> &mut String {
match self {
TableName::Layer => &mut c.layer,
TableName::Linetype => &mut c.linetype,
}
}
}
/// Rename `old` to `new` in the table order `names`.
fn rename_in(names: &mut [String], old: &str, new: &str) {
for n in names.iter_mut().filter(|n| n.eq_ignore_ascii_case(old)) {
*n = new.to_string();
}
}
/// Append the bytes of hex string `s`. False on a character that isn't a hex digit.
fn push_hex(out: &mut Vec<u8>, s: &str) -> bool {
let digits: Vec<u8> = s.trim().bytes().collect();
@@ -428,14 +304,8 @@ fn push_hex(out: &mut Vec<u8>, s: &str) -> bool {
/// The entities the proxy graphics `bytes` draw, all with `handle` (the proxy's): selecting one
/// selects the proxy.
pub fn proxy_entities(bytes: &[u8], tables: &ProxyTables, handle: Handle) -> Vec<Entity> {
decode(bytes, tables, handle, None)
}
/// [`proxy_entities`], with the indices in `marks` named by them instead of `tables`.
fn decode(bytes: &[u8], tables: &ProxyTables, handle: Handle, marks: Option<&Marks>) -> Vec<Entity> {
let mut r = Decoder {
tables,
marks,
handle,
pen: Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..Common::default() },
fill: false,
@@ -457,8 +327,6 @@ fn decode(bytes: &[u8], tables: &ProxyTables, handle: Handle, marks: Option<&Mar
struct Decoder<'a> {
tables: &'a ProxyTables,
/// Names standing for the indices while a record is decoded again (`Unknown::names_by_index`).
marks: Option<&'a Marks>,
handle: Handle,
/// Layer, colour, linetype and lineweight for the entities that follow.
pen: Common,
@@ -559,26 +427,18 @@ impl Decoder<'_> {
}
// ATTRIBUTE_LAYER: index into the layer table; an index past it, or one of a record
// without a name, leaves the layer.
LAYER_CHUNK => {
let name = b.u32().and_then(|i| match self.marks {
Some(m) => m.layers.get(&i),
None => self.tables.layers.get(i as usize),
});
if let Some(name) = name.filter(|n| !n.is_empty()) {
16 => {
if let Some(name) = b.u32().and_then(|i| self.tables.layers.get(i as usize)).filter(|n| !n.is_empty()) {
self.pen.layer = name.clone();
}
}
// ATTRIBUTE_LINETYPE: index into the linetypes other than ByBlock and ByLayer;
// 32766 is ByBlock, 32767 and anything past the table ByLayer.
LINETYPE_CHUNK => {
18 => {
if let Some(i) = b.u32() {
let name = match self.marks {
Some(m) => m.linetypes.get(&i),
None => self.tables.linetypes.get(i as usize),
};
self.pen.linetype = match i {
LINETYPE_BYBLOCK => "ByBlock".into(),
_ => name.filter(|n| !n.is_empty()).cloned().unwrap_or_else(|| "ByLayer".into()),
32766 => "ByBlock".into(),
_ => self.tables.linetypes.get(i as usize).filter(|n| !n.is_empty()).cloned().unwrap_or_else(|| "ByLayer".into()),
};
}
}
@@ -736,15 +596,6 @@ impl Decoder<'_> {
fn arc_between(&mut self, c: Vec3, r: f64, e1: Vec3, e2: Vec3, a0: f64, a1: f64) {
let (at, u, v) = self.axes(c, e1, e2);
let on = |a: f64| at + u * (r * a.cos()) + v * (r * a.sin());
// A sweep too short for an arc or an elliptical arc to hold (it would read as a full
// turn): the chord between its ends.
if (a1 - a0).abs() <= cadcraft_geom::EPS {
let (p, q) = (on(a0), on(a1));
if p != q && p.is_finite() && q.is_finite() {
self.push(EntityKind::Line(Line { a: p.to3(0.0), b: q.to3(0.0) }));
}
return;
}
if round(u * r, v * r).is_some() {
return self.arc_3p(on(a0), on((a0 + a1) / 2.0), on(a1));
}
@@ -879,8 +730,6 @@ impl Decoder<'_> {
style,
halign: Default::default(),
valign: Default::default(),
backwards: false,
upside_down: false,
}));
}
}
@@ -918,13 +767,6 @@ fn round(u: Vec2, v: Vec2) -> Option<f64> {
/// ellipse's own parameter (counter-clockwise from its major axis).
fn ellipse(c: Vec2, u: Vec2, v: Vec2, a0: f64, a1: f64) -> Option<Ellipse> {
use std::f64::consts::{FRAC_PI_2, TAU};
// Conjugate radii on one line (a plane seen edge-on, also through an exact quarter turn,
// whose cosine leaves a tiny minor axis), relative to the longer: no ellipse, the caller
// draws the line it covers.
let longer = u.len().max(v.len());
if u.cross(v).abs() <= 1e-9 * longer * longer {
return None;
}
// c + u·cos a + v·sin a = c + p·cos(a − t) + q·sin(a − t): p and q at right angles.
let t = 0.5 * (2.0 * u.dot(v)).atan2(u.len2() - v.len2());
let p = u * t.cos() + v * t.sin();
@@ -1457,155 +1299,6 @@ mod tests {
assert!(own.proxy_graphics_bytes().is_empty());
}
/// The layer order `names` with no linetypes.
fn layers(names: &[String]) -> TableOrder<'_> {
TableOrder { layers: names, linetypes: &[] }
}
/// A record with the graphics `g`: in its proxy data for an ACAD_PROXY_ENTITY, else in its
/// `AcDbEntity` part (a kept dimension naming block `*D1`).
fn record(dxf_type: &str, g: &[u8], graphics: Vec<Entity>) -> Unknown {
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let hex: String = g.iter().map(|b| format!("{b:02X}")).collect();
let tags = if dxf_type == "ACAD_PROXY_ENTITY" {
vec![tag(100, "AcDbProxyEntity"), tag(92, &g.len().to_string()), tag(310, &hex)]
} else {
vec![tag(100, "AcDbEntity"), tag(8, "0"), tag(92, &g.len().to_string()), tag(310, &hex), tag(100, "AcDbDimension"), tag(2, "*D1")]
};
Unknown { dxf_type: dxf_type.into(), tags, graphics }
}
fn unit_circle() -> Vec<u8> {
let mut circle = pt(0.0, 0.0);
circle.extend(1.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0));
circle
}
/// Graphics that stay on the layer before after an index don't hide that the table names the
/// index: with layers 1, then 2 and 99, then 2, then 1 and 99 before four circles (A, B, B,
/// A), the second 2 sets B again, and saving keeps all four where they are.
#[test]
fn an_index_staying_on_the_layer_its_table_names_keeps_it() {
let circle = unit_circle();
let layer = |i: u32| chunk(16, &i.to_le_bytes());
let g = graphics(&[
layer(1),
chunk(2, &circle),
layer(2),
layer(99),
chunk(2, &circle),
layer(2),
chunk(2, &circle),
layer(1),
layer(99),
chunk(2, &circle),
]);
let read: Vec<String> = ["0", "A", "B"].map(String::from).to_vec();
let tables = ProxyTables { layers: read.clone(), ..ProxyTables::default() };
let u = record("ACAD_PROXY_ENTITY", &g, proxy_entities(&g, &tables, Handle(1)));
let on = |es: &[Entity]| es.iter().map(|e| e.common.layer.clone()).collect::<Vec<_>>();
assert_eq!(on(&u.graphics), ["A", "B", "B", "A"]);
assert!(u.with_proxy_tables(layers(&read), layers(&read)).is_none(), "nothing changes for the same table");
let written: Vec<String> = ["0", "X", "A", "B"].map(String::from).to_vec();
let again = Unknown { tags: u.with_proxy_tables(layers(&read), layers(&written)).expect("remapped"), ..u.clone() };
let w = ProxyTables { layers: written, ..ProxyTables::default() };
assert_eq!(on(&proxy_entities(&again.proxy_graphics_bytes(), &w, Handle(1))), ["A", "B", "B", "A"]);
}
/// Linetype indices follow the written LTYPE table by name, as layer indices do: a linetype
/// that is gone becomes ByLayer, and ByBlock, ByLayer and an index past the table stay.
#[test]
fn linetype_indices_follow_the_written_table() {
let circle = unit_circle();
let linetype = |i: u32| chunk(18, &i.to_le_bytes());
let g = graphics(&[
linetype(2),
chunk(2, &circle),
linetype(32766),
chunk(2, &circle),
linetype(1),
chunk(2, &circle),
linetype(9),
chunk(2, &circle),
]);
let read: Vec<String> = ["Continuous", "DASHED", "HIDDEN"].map(String::from).to_vec();
let tables = ProxyTables { linetypes: read.clone(), ..ProxyTables::default() };
let u = record("ACAD_PROXY_ENTITY", &g, proxy_entities(&g, &tables, Handle(1)));
let drawn = |es: &[Entity]| es.iter().map(|e| e.common.linetype.clone()).collect::<Vec<_>>();
assert_eq!(drawn(&u.graphics), ["HIDDEN", "ByBlock", "DASHED", "ByLayer"]);
let saved = |written: &[String]| {
let tags = u.with_proxy_tables(TableOrder { layers: &[], linetypes: &read }, TableOrder { layers: &[], linetypes: written });
let again = Unknown { tags: tags.unwrap_or_else(|| u.tags.clone()), ..u.clone() };
drawn(&proxy_entities(&again.proxy_graphics_bytes(), &ProxyTables { linetypes: written.to_vec(), ..ProxyTables::default() }, Handle(1)))
};
let names = |n: &[&str]| n.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(saved(&read), ["HIDDEN", "ByBlock", "DASHED", "ByLayer"]);
assert_eq!(saved(&names(&["Continuous", "CENTER", "DASHED", "HIDDEN"])), ["HIDDEN", "ByBlock", "DASHED", "ByLayer"]);
assert_eq!(saved(&names(&["Continuous", "HIDDEN"])), ["HIDDEN", "ByBlock", "ByLayer", "ByLayer"]);
}
/// A kept dimension's picture (#3438) follows the written LAYER table too: by its decoded
/// graphics when it draws them, by the file's table when it draws its block instead.
#[test]
fn a_kept_dimensions_picture_follows_the_written_table() {
let circle = unit_circle();
let g = graphics(&[chunk(16, &2u32.to_le_bytes()), chunk(2, &circle)]);
let read: Vec<String> = ["0", "UNUSED", "A"].map(String::from).to_vec();
let written: Vec<String> = ["0", "A", "Defpoints"].map(String::from).to_vec();
let tables = ProxyTables { layers: read.clone(), ..ProxyTables::default() };
let w = ProxyTables { layers: written.clone(), ..ProxyTables::default() };
for graphics in [proxy_entities(&g, &tables, Handle(1)), vec![block_ref()]] {
let u = record("LARGE_RADIAL_DIMENSION", &g, graphics);
let again = Unknown { tags: u.with_proxy_tables(layers(&read), layers(&written)).expect("remapped"), ..u.clone() };
assert_eq!(proxy_entities(&again.proxy_graphics_bytes(), &w, Handle(1))[0].common.layer, "A");
}
// A reference to the block on another layer isn't taken for the picture (one entity as
// well): the file's table names index 2.
let elsewhere = Entity { common: Common { layer: "Defpoints".into(), ..Common::default() }, ..block_ref() };
let u = record("LARGE_RADIAL_DIMENSION", &g, vec![elsewhere]);
assert!(u.names_by_index(&g, &[2], &[], &read).layers.is_empty());
}
fn block_ref() -> Entity {
Entity {
handle: Handle(1),
common: Common::default(),
kind: EntityKind::Insert(super::super::Insert { block: "*D1".into(), ..super::super::Insert::default() }),
}
}
/// An exact quarter turn about Y shows a circle edge-on: it draws as the line it covers, not
/// as an ellipse with the minor axis the turn's cosine leaves. An arc too short for its sweep
/// to be held draws as its chord, not as a full turn, round or under an uneven matrix.
#[test]
fn quarter_turns_and_tiny_sweeps_draw_lines() {
let matrix = |m: [f64; 16]| chunk(29, &m.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>());
let (s, c) = std::f64::consts::FRAC_PI_2.sin_cos();
let turn = matrix([c, 0.0, s, 0.0, 0.0, 1.0, 0.0, 0.0, -s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0]);
let line = |es: &[Entity]| match es {
[e] => match &e.kind {
EntityKind::Line(l) => (l.a.xy(), l.b.xy()),
other => panic!("{other:?}"),
},
_ => panic!("{es:?}"),
};
let near = |p: Vec2, x: f64, y: f64| (p - Vec2::new(x, y)).len() < 1e-12;
let (a, b) = line(&proxy_entities(&graphics(&[turn, chunk(2, &unit_circle())]), &tables(), Handle(1)));
assert!(near(a, 0.0, -1.0) && near(b, 0.0, 1.0), "{a:?} {b:?}");
let sweep = 5e-10f64;
let mut tiny = pt(0.0, 0.0);
tiny.extend(1.0f64.to_le_bytes());
tiny.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
tiny.extend(pt(1.0, 0.0));
tiny.extend(sweep.to_le_bytes());
let stretch = matrix([2.0, 0.0, 0.0, 10.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]);
for (chunks, x) in [(vec![chunk(4, &tiny)], 1.0), (vec![stretch, chunk(4, &tiny)], 12.0)] {
let (a, b) = line(&proxy_entities(&graphics(&chunks), &tables(), Handle(1)));
assert!(near(a, x, 0.0) && (b - Vec2::new(x, sweep)).len() < 1e-15, "{a:?} {b:?}");
}
}
/// Saving renames the layer indices by name into the written table, reading only the 310
/// groups the declared size needs: a damaged group after them doesn't stop it.
#[test]
@@ -1625,7 +1318,7 @@ mod tests {
};
assert_eq!(u.graphics[0].common.layer, "B");
let written: Vec<String> = ["0", "B", "C"].map(String::from).to_vec();
let tags = u.with_proxy_tables(layers(&read), layers(&written)).expect("remapped");
let tags = u.with_proxy_layers(&read, &written).expect("remapped");
let again = Unknown { tags, ..u.clone() };
assert_eq!(
proxy_entities(&again.proxy_graphics_bytes(), &ProxyTables { layers: written, ..ProxyTables::default() }, Handle(1))[0].common.layer,
@@ -1635,8 +1328,8 @@ mod tests {
}
/// An index whose graphics stay on the layer before (99 here, past the table) doesn't make
/// the index before it (3) look contradictory when that one comes again, and a large index
/// is found like any other.
/// the index before it (3) look contradictory when that one comes again; an index above
/// 65,535 isn't named (it resolves through the file's table), and the others still are.
#[test]
fn indices_are_named_around_kept_layers_and_huge_indices() {
let mut circle = pt(0.0, 0.0);
@@ -1652,13 +1345,12 @@ mod tests {
}
let g = graphics(&chunks);
let u = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: proxy_entities(&g, &tables, Handle(1)) };
let mut learned: Vec<(u32, Option<String>)> = u.names_by_index(&g, indices, &[], &tables.layers).layers.into_iter().collect();
let mut learned: Vec<(u32, Option<String>)> = u.layers_by_index(&g, indices).into_iter().collect();
learned.sort();
learned
};
assert_eq!(named(&[0, 3, 99, 3]), [(0, Some("0".into())), (3, Some("B".into())), (99, None)]);
// Only the indices used get a marker: 70,000 keeps the layer before, as past the table.
assert_eq!(named(&[2, 70_000]), [(2, Some("C".into())), (70_000, None)]);
assert_eq!(named(&[2, 70_000]), [(2, Some("C".into()))]);
// Layer 4 (past the table, so it keeps layer 0), a circle, then layers 1 and 4 at once (4
// keeps A): both circles follow index 4 in the marker decoding, on different layers.
let g = graphics(&[
@@ -1676,9 +1368,9 @@ mod tests {
graphics: proxy_entities(&g, &tables, Handle(1)),
};
assert_eq!(u.graphics.iter().map(|e| e.common.layer.as_str()).collect::<Vec<_>>(), ["0", "A"]);
assert!(!u.names_by_index(&g, &[4, 1, 4], &[], &tables.layers).layers.contains_key(&4), "index 4 isn't named");
assert!(!u.layers_by_index(&g, &[4, 1, 4]).contains_key(&4), "index 4 isn't named");
// Saved with the same table, nothing changes, so both circles stay where they are.
assert!(u.with_proxy_tables(layers(&tables.layers), layers(&tables.layers)).is_none());
assert!(u.with_proxy_layers(&tables.layers, &tables.layers).is_none());
}
/// Truncated chunks, sizes past the end, huge counts and garbage draw what they can and
-28
View File
@@ -42,13 +42,6 @@ pub struct Text {
pub halign: HAlign,
#[serde(default)]
pub valign: VAlign,
/// Mirrored left to right (AutoCAD's Backwards; DXF 71 bit 2). New text takes it from its
/// style; later style changes don't change it.
#[serde(default)]
pub backwards: bool,
/// Mirrored top to bottom (AutoCAD's Upside down; DXF 71 bit 4).
#[serde(default)]
pub upside_down: bool,
}
impl Text {
@@ -90,27 +83,6 @@ pub struct MText {
/// one column.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub columns: Option<MTextColumns>,
/// Background mask (DXF 90/63/421/45); `None` when off.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub background: Option<MTextBackground>,
}
/// MTEXT background mask (DXF 90, 63/421, 45).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MTextBackground {
/// DXF group 90 bitmask: bit 1 = fill colour set, bit 2 = use drawing background colour.
pub mask: u8,
/// DXF group 63 (ACI) or 421 (true colour); `None` when using drawing background.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub color: Option<super::Color>,
/// DXF group 45 border offset factor (default 1.5, valid 1.0..=5.0).
#[serde(default = "default_bg_scale")]
pub scale: f64,
}
fn default_bg_scale() -> f64 {
1.5
}
fn attach_tl() -> u8 {
-341
View File
@@ -1,341 +0,0 @@
//! Extended entity data (xdata): the groups 1000–1071 other applications attach to an entity,
//! kept raw in [`Common::xdata`](super::Common::xdata) as whole applications, each from its
//! `1001` group on. This module reads them per application, replaces or removes one
//! application's data, and checks data that comes from outside (a command's parameters, a LISP
//! list) before it goes onto an entity: input is hostile, so codes, values, brace nesting and
//! sizes are all checked and nothing here panics.
use super::RawTag;
/// Most xdata groups one object may carry (AutoCAD allows 16 KB of xdata per object).
pub const MAX_XDATA_GROUPS: usize = 16_384;
/// Longest application name, in bytes.
pub const MAX_XDATA_APP_NAME: usize = 255;
/// Longest string value (groups 1000 and 1003), in bytes: what one DXF group holds.
pub const MAX_XDATA_STRING: usize = 255;
/// Longest binary chunk (group 1004), in bytes.
pub const MAX_XDATA_CHUNK: usize = 127;
/// Applications whose xdata CADCraft writes itself, from its own model, when a drawing is saved.
/// It is never kept as an entity's raw xdata (the reader models it) and can't be set as such:
/// a copy written beside the generated data would contradict it.
pub const RESERVED_XDATA_APPS: &[&str] = &["CADCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD"];
/// Whether `name` (any case) is one of [`RESERVED_XDATA_APPS`].
pub fn is_reserved_xdata_app(name: &str) -> bool {
let up = name.trim().to_ascii_uppercase();
RESERVED_XDATA_APPS.contains(&up.as_str())
}
/// Whether application `name`'s xdata on an entity of `kind` is written from the model rather
/// 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);
impl std::fmt::Display for XdataError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for XdataError {}
fn err<T>(msg: impl Into<String>) -> Result<T, XdataError> {
Err(XdataError(msg.into()))
}
/// Check an application name: not empty, at most [`MAX_XDATA_APP_NAME`] bytes, no control
/// characters and none of the characters a symbol table name can't hold.
pub fn check_xdata_app_name(name: &str) -> Result<(), XdataError> {
let name = name.trim();
if name.is_empty() {
return err("an xdata application name must not be empty");
}
if name.len() > MAX_XDATA_APP_NAME {
return err(format!("an xdata application name may have at most {MAX_XDATA_APP_NAME} bytes"));
}
if name.chars().any(|c| c.is_control() || "<>/\\\":;?*|,=`".contains(c)) {
return err(format!("`{name}` is not a valid xdata application name (no control characters or <>/\\\":;?*|,=`)"));
}
Ok(())
}
/// Whether `code` is an xdata group code an application's data may hold (`1001`, the
/// application name, is not one of them: it starts an application).
pub fn is_xdata_group(code: i32) -> bool {
matches!(code, 1000 | 1002..=1005 | 1010..=1013 | 1020..=1023 | 1030..=1033 | 1040..=1042 | 1070 | 1071)
}
/// Check the groups of one application (after its `1001`): every code an xdata code with a
/// value of its kind, control strings `{` and `}` balanced, points complete (a `101x` group
/// followed by its `102x` and `103x`), at most [`MAX_XDATA_GROUPS`] groups.
pub fn check_xdata_groups(groups: &[RawTag]) -> Result<(), XdataError> {
if groups.len() > MAX_XDATA_GROUPS {
return err(format!("at most {MAX_XDATA_GROUPS} xdata groups per application"));
}
let mut depth: u32 = 0;
let mut i = 0;
while let Some(t) = groups.get(i) {
let v = t.value.trim();
match t.code {
1000 | 1003 => {
if t.value.len() > MAX_XDATA_STRING {
return err(format!("group {}: a string may have at most {MAX_XDATA_STRING} bytes", t.code));
}
if t.value.chars().any(|c| c == '\n' || c == '\r') {
return err(format!("group {}: a string may not hold a line break", t.code));
}
}
1002 => match v {
"{" => depth = depth.saturating_add(1),
"}" => match depth.checked_sub(1) {
Some(d) => depth = d,
None => return err("group 1002: a `}` without its `{`"),
},
_ => return err("group 1002 must be `{` or `}`"),
},
1004 => {
if v.len() > MAX_XDATA_CHUNK * 2 || v.len() % 2 != 0 || !v.bytes().all(|b| b.is_ascii_hexdigit()) {
return err(format!("group 1004 must be hex text of an even length, at most {MAX_XDATA_CHUNK} bytes"));
}
}
1005 => {
if v.is_empty() || v.len() > 16 || !v.bytes().all(|b| b.is_ascii_hexdigit()) {
return err("group 1005 must be a hex handle");
}
}
1010..=1013 => {
let (y, z) = (groups.get(i + 1), groups.get(i + 2));
let complete = y.is_some_and(|y| y.code == t.code + 10) && z.is_some_and(|z| z.code == t.code + 20);
if !complete {
return err(format!("group {}: a point needs its {} and {} groups", t.code, t.code + 10, t.code + 20));
}
for p in [Some(t), y, z].into_iter().flatten() {
real(p)?;
}
i += 3;
continue;
}
1020..=1023 | 1030..=1033 => return err(format!("group {} may only follow its {} group", t.code, t.code - (t.code - 1010) / 10 * 10)),
1040..=1042 => {
real(t)?;
}
1070 => {
let ok = v.parse::<i64>().is_ok_and(|n| i16::try_from(n).is_ok());
if !ok {
return err("group 1070 must be a 16-bit integer");
}
}
1071 => {
let ok = v.parse::<i64>().is_ok_and(|n| i32::try_from(n).is_ok());
if !ok {
return err("group 1071 must be a 32-bit integer");
}
}
1001 => return err("group 1001 (an application name) can't be inside an application's data"),
c => return err(format!("group {c} is not an xdata group code (1000–1071)")),
}
i += 1;
}
if depth != 0 {
return err("group 1002: a `{` without its `}`");
}
Ok(())
}
fn real(t: &RawTag) -> Result<f64, XdataError> {
match t.value.trim().parse::<f64>() {
Ok(v) if v.is_finite() => Ok(v),
_ => err(format!("group {} must be a finite number", t.code)),
}
}
/// The applications of an xdata run, in order: each name as written and its groups after the
/// `1001`. Groups before the first `1001` belong to nobody and are left out.
pub fn xdata_apps(xdata: &[RawTag]) -> Vec<(&str, &[RawTag])> {
let mut out = Vec::new();
let mut start: Option<(usize, &str)> = None;
for (i, t) in xdata.iter().enumerate() {
if t.code != 1001 {
continue;
}
if let Some((s, name)) = start.take() {
out.push((name, xdata.get(s + 1..i).unwrap_or(&[])));
}
start = Some((i, t.value.trim()));
}
if let Some((s, name)) = start {
out.push((name, xdata.get(s + 1..).unwrap_or(&[])));
}
out
}
/// The groups of application `app` (any case): those of its first run.
pub fn xdata_of<'a>(xdata: &'a [RawTag], app: &str) -> Option<&'a [RawTag]> {
xdata_apps(xdata).into_iter().find(|(name, _)| name.eq_ignore_ascii_case(app.trim())).map(|(_, g)| g)
}
/// Replace the xdata of application `app` (any case) with `groups`, or remove it (`None`, or no
/// groups). Every run of that application goes; new data is appended after the other
/// applications' data, with its `1001` group. The groups are taken as given: check them with
/// [`check_xdata_groups`] first when they come from outside.
pub fn set_xdata_app(xdata: &mut Vec<RawTag>, app: &str, groups: Option<&[RawTag]>) {
let app = app.trim();
let mut kept: Vec<RawTag> = Vec::with_capacity(xdata.len());
let mut skipping = false;
for t in xdata.drain(..) {
if t.code == 1001 {
skipping = t.value.trim().eq_ignore_ascii_case(app);
}
if !skipping {
kept.push(t);
}
}
if let Some(groups) = groups.filter(|g| !g.is_empty()) {
kept.push(RawTag { code: 1001, value: app.to_string() });
kept.extend(groups.iter().cloned());
}
*xdata = kept;
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
fn t(code: i32, value: &str) -> RawTag {
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")];
let apps = xdata_apps(&x);
assert_eq!(apps.len(), 2);
assert_eq!(apps[0].0, "A");
assert_eq!(apps[0].1.len(), 2);
assert_eq!(apps[1], ("b", &x[4..]));
assert_eq!(xdata_of(&x, "B"), Some(&x[4..]));
assert_eq!(xdata_of(&x, "c"), None);
assert!(xdata_apps(&[t(1000, "stray")]).is_empty());
}
#[test]
fn set_replaces_removes_and_appends() {
let mut x = vec![t(1001, "A"), t(1000, "one"), t(1001, "B"), t(1000, "two"), t(1001, "a"), t(1000, "dup")];
set_xdata_app(&mut x, "a", Some(&[t(1070, "7")]));
assert_eq!(x, vec![t(1001, "B"), t(1000, "two"), t(1001, "a"), t(1070, "7")]);
set_xdata_app(&mut x, "B", None);
assert_eq!(x, vec![t(1001, "a"), t(1070, "7")]);
set_xdata_app(&mut x, "C", Some(&[]));
assert_eq!(x.len(), 2);
set_xdata_app(&mut x, "A", None);
assert!(x.is_empty());
}
#[test]
fn checks_accept_every_kind_and_refuse_bad_data() {
let good = vec![
t(1000, "text"),
t(1002, "{"),
t(1003, "Layer"),
t(1004, "DEADBEEF"),
t(1005, "1A2"),
t(1010, "1.5"),
t(1020, "2"),
t(1030, "0"),
t(1040, "2.5"),
t(1041, "1e3"),
t(1042, "-1"),
t(1070, "32767"),
t(1071, "2147483647"),
t(1002, "}"),
];
assert_eq!(check_xdata_groups(&good), Ok(()));
for bad in [
vec![t(1002, "}")],
vec![t(1002, "{")],
vec![t(1002, "x")],
vec![t(1001, "APP")],
vec![t(999, "comment")],
vec![t(8, "layer")],
vec![t(1010, "1"), t(1020, "2")],
vec![t(1020, "2")],
vec![t(1010, "nan"), t(1020, "2"), t(1030, "3")],
vec![t(1040, "inf")],
vec![t(1040, "x")],
vec![t(1070, "40000")],
vec![t(1071, "3000000000")],
vec![t(1004, "ABC")],
vec![t(1004, "XY")],
vec![t(1005, "")],
vec![t(1005, "zz")],
vec![t(1000, &"x".repeat(256))],
vec![t(1000, "a\nb")],
vec![t(1000, "x"); MAX_XDATA_GROUPS + 1],
] {
assert!(check_xdata_groups(&bad).is_err(), "{:?}", bad.first());
}
assert_eq!(check_xdata_app_name("PE_URL"), Ok(()));
assert_eq!(check_xdata_app_name("My App-1.0$"), Ok(()));
for bad in ["", " ", "a*b", "a\tb", "x/y", &"n".repeat(256)] {
assert!(check_xdata_app_name(bad).is_err(), "{bad:?}");
}
assert!(is_reserved_xdata_app("cadcraft") && !is_reserved_xdata_app("ACAD"));
}
}
+43 -533
View File
@@ -242,152 +242,27 @@ pub fn ole_frame_accepts(m: &cadcraft_geom::Mat3) -> bool {
m.b.abs() < t && m.c.abs() < t && m.a > 0.0 && (m.a - m.d).abs() <= t
}
/// What a single-line text value draws, as the fonts read it.
#[derive(Clone, Copy, Default)]
struct Drawn {
/// How many characters take room.
chars: usize,
/// Whether any of them is underlined, and whether any is overlined.
underlined: bool,
overlined: bool,
}
/// What a single-line text value draws, as the fonts read it: a `%%` code is the one character
/// it stands for (`%%d`, `%%p`, `%%c`, `%%%`, `%%nnn`) or none (`%%u` and `%%o`, which turn the
/// underline and the overline on and off for the characters after them), `\U+XXXX` is one
/// character, and invisible formatting characters (joiners, directional marks) take no room.
fn drawn_text(value: &str) -> Drawn {
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()
.filter(|hex| hex.iter().all(char::is_ascii_hexdigit))
.and_then(|hex| u32::from_str_radix(&hex.iter().collect::<String>(), 16).ok())
.and_then(char::from_u32);
if let Some(u) = escaped {
drawn += usize::from(!invisible(u));
i += 7;
} else if c == '%' && chars.get(i + 1) == Some(&'%') {
match chars.get(i + 2).map_or(' ', char::to_ascii_lowercase) {
'u' => (under, i) = (!under, i + 3),
'o' => (over, i) = (!over, i + 3),
'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();
(drawn, i) = (drawn + 1, i + 2 + digits);
}
// Not a code: the percent sign is drawn, and the next one is read again.
_ => (drawn, i) = (drawn + 1, i + 1),
}
} else {
drawn += usize::from(!invisible(c));
i += 1;
}
if drawn > before {
(out.underlined, out.overlined) = (out.underlined || under, out.overlined || over);
}
}
Drawn { chars: drawn, ..out }
}
/// 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), its underline and overline included. Empty when nothing is drawn.
fn text_box(t: &crate::Text, drawn: Drawn) -> Bounds2 {
/// Bounds of a single-line TEXT / ATTDEF / ATTRIB of `len` characters, following its justification
/// the same way the renderer places it (the stroke font is about 0.88 of the height per character).
fn text_box(t: &crate::Text, len: usize) -> Bounds2 {
use crate::{HAlign, VAlign};
let len = drawn.chars;
if len == 0 {
return Bounds2::EMPTY;
}
let natural = t.height * 0.9 * t.width_factor.abs().max(0.01) * len as f64;
let w = t.height * 0.9 * t.width_factor.abs().max(0.01) * len.max(1) as f64;
// Justified text (TL, ML and BL too) hangs from its alignment point (DXF group 11).
let origin = t.justify_point();
// Aligned and Fit text span their two points (groups 10 and 11) whatever rotation is stored:
// the line runs from the first to the second, Fit at its own height with its width stretched,
// Aligned at the height that keeps its proportions. With no second point, or one on the
// first, they are placed like left-justified text, as the renderer places them.
let second = t.align_pt.map(|p| p.xy()).filter(|_| matches!(t.halign, HAlign::Aligned | HAlign::Fit));
let span = second.map(|p| origin.dist(p)).filter(|d| d.is_finite() && *d > 1e-12);
// The fonts shape with the width factor as it is, not floored like the fallback width above,
// with 1 when it is unusable, and with a height of 1 when the height is.
let usable = t.width_factor.is_finite() && t.width_factor.abs() > 1e-6;
let wf = if usable { t.width_factor.abs() } else { 1.0 };
let height = if t.height.is_finite() && t.height > 0.0 { t.height } else { 1.0 };
let shaped = height * 0.9 * wf * len as f64;
// Fit text is stretched by scaling its width factor by span / shaped width and shaping again.
// When the scaled factor is one the fonts cannot use (the stored one is, or the span is a tiny
// part of the text's width), the text is not stretched: it is drawn at a factor of 1.
// The shaped width here is an estimate, and the fonts decide by their own: it is taken to be
// within this factor of the estimate. Where the fonts decide by a cutoff, the box is the larger
// of the two outcomes unless the estimate is clear of the cutoff by this factor.
const MARGIN: f64 = 4.0;
let fits = |d: f64| {
let fitted = wf * d / shaped;
usable && fitted.is_finite() && fitted > 1e-6 * MARGIN
};
let unstretched = height * 0.9 * len as f64;
// The fonts leave a line of next to no width as it is, neither stretched nor scaled: the same
// cutoff as theirs, with no margin, since a box scaled for text that is left alone is
// enormous.
let no_width = shaped <= 1e-12;
// Aligned text is scaled by span / shaped width, so the narrower the line, the taller it is
// drawn. The least width the stroke font gives a line: its narrowest characters are 1 unit
// wide on a cap height of 6, with 1.6 units between characters. The height from that width
// holds whatever the line is made of, also shrunk into a span shorter than its width.
let narrowest = height * wf * (2.6 * len as f64 - 1.6) / 6.0;
// The most width it gives one (its widest characters are 4 units wide), for the least height
// the line can be drawn at.
let widest = height * wf * (5.6 * len as f64 - 1.6) / 6.0;
// Width, the most and the least height the line is drawn at, and its direction.
let (w, h, low, rotation) = match (span, second) {
(Some(_), Some(p)) if no_width => (shaped, height, height, origin.angle_to(p)),
// Unstretched is the larger outcome: a span this near the cutoff is far shorter than the text.
(Some(d), Some(p)) if t.halign == HAlign::Fit && !fits(d) => (unstretched, height, height, origin.angle_to(p)),
(Some(d), Some(p)) if t.halign == HAlign::Fit => (d, height, height, origin.angle_to(p)),
(Some(d), Some(p)) => (d, height * d / narrowest, height * d / widest, origin.angle_to(p)),
_ => (natural, t.height, t.height, t.rotation),
};
let dx = match t.halign {
HAlign::Left | HAlign::Aligned | HAlign::Fit => 0.0,
HAlign::Center | HAlign::Middle => -w / 2.0,
HAlign::Right => -w,
};
// 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,
let dy = match (t.halign, t.valign) {
(HAlign::Middle, _) => -t.height / 2.0,
(_, VAlign::Baseline) => 0.0,
(_, VAlign::Bottom) => drawn_h / 3.0,
(_, VAlign::Top) => -drawn_h,
(_, VAlign::Bottom) => t.height / 3.0,
(_, VAlign::Middle) => -t.height / 2.0,
(_, VAlign::Top) => -t.height,
};
// 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 });
Bounds2::from_points(local.map(|p| origin + Vec2::new(p.x * mx, p.y * my).rotate(rotation)))
}
/// Whether `e` is a point on the layer Defpoints (the name in any case), as the block of a
/// dimension holds the dimension's definition points. The reference app selects a dimension and a
/// block reference by such a point of its block whatever a viewport freezes, the layer Defpoints
/// too, where a line on that layer follows the viewport. So a selection through a viewport counts
/// such a part of a block ([`ViewportBounds`]); the viewport itself does not draw it.
pub fn point_on_defpoints(e: &Entity) -> bool {
matches!(e.kind, EntityKind::Point(_)) && e.common.layer.eq_ignore_ascii_case("Defpoints")
let local = [Vec2::new(dx, dy), Vec2::new(dx + w, dy), Vec2::new(dx + w, dy + t.height), Vec2::new(dx, dy + t.height)];
Bounds2::from_points(local.map(|p| origin + p.rotate(t.rotation)))
}
/// Whether an entity inside a block definition shows: its own invisible flag and its layer count,
@@ -395,27 +270,16 @@ pub fn point_on_defpoints(e: &Entity) -> bool {
/// entities a visibility state hides are invisible this way, and they sit far from the block's
/// geometry in real drawings. Layer "0" takes the insert's layer, which the caller has checked.
/// `off_counts`: a layer turned off counts too, as in the drawing's extents ([`extent_bounds`]).
/// `frozen`: the layers frozen in the layout viewport measured through ([`ViewportBounds`]); a
/// point on the layer Defpoints counts whatever that viewport freezes ([`point_on_defpoints`]).
fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool, frozen: &[String]) -> bool {
let frozen: &[String] = if point_on_defpoints(e) { &[] } else { frozen };
fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool) -> bool {
// Attribute definitions are not drawn in an insert (its attribs are, see below), except
// constant ones, which the insert's bounds add on their own.
!matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts, frozen)
!matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts)
}
/// Whether what lies on `layer` inside an insert counts: layer "0" takes the insert's layer, which
/// the caller has checked; a frozen layer never counts, one turned off only with `off_counts`.
/// Nor does one of the layers in `frozen`, those frozen in the layout viewport measured through,
/// which does not draw them (the names compared as the renderer compares them).
fn layer_counts(d: &Drawing, layer: &str, off_counts: bool, frozen: &[String]) -> bool {
layer == "0" || (d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts)) && !frozen_in(frozen, layer))
}
/// Whether `layer` is one of the layers in `frozen`, those frozen in a layout viewport (the names
/// compared as the renderer compares them).
fn frozen_in(frozen: &[String], layer: &str) -> bool {
frozen.iter().any(|f| f.eq_ignore_ascii_case(layer))
fn layer_counts(d: &Drawing, layer: &str, off_counts: bool) -> bool {
layer == "0" || d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts))
}
/// The layer an insert's attribute draws on, as the renderer takes it: its own, else its
@@ -449,18 +313,13 @@ impl Contents<'_> {
}
}
/// [`Contents`] of `blk` referenced at `depth`, measured once and kept in `blocks`: the parts that
/// count there ([`in_block_visible`], and a constant value by its layer as [`layer_counts`] says),
/// so those on a layer in `frozen` are left out ([`bounds_in`] says what the maps hold and why the
/// depth is part of the key).
/// [`Contents`] of `blk` referenced at `depth`, measured once and kept in `blocks`.
fn contents<'a, 'm>(
d: &'a Drawing,
blk: &'a crate::Block,
depth: usize,
blocks: &'m mut HashMap<(&'a str, usize), Contents<'a>>,
in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>,
off_counts: bool,
frozen: &[String],
) -> Option<&'m Contents<'a>> {
let key = (blk.name.as_str(), depth);
if !blocks.contains_key(&key) {
@@ -475,13 +334,11 @@ fn contents<'a, 'm>(
&& attmode != 0
&& (!a.invisible || attmode == 2)
&& be.common.visible
&& layer_counts(d, &be.common.layer, off_counts, frozen) =>
&& layer_counts(d, &be.common.layer, off_counts) =>
{
c.constants.push((a.tag.as_str(), constant_box(a, be.common.matches_layout_orientation())));
}
_ if in_block_visible(d, be, off_counts, frozen) => {
c.geometry = c.geometry.union(&bounds_in(d, be, depth + 1, blocks, in_drawing, off_counts, frozen));
}
_ if in_block_visible(d, be, off_counts) => c.geometry = c.geometry.union(&bounds_in(d, be, depth + 1, blocks, off_counts)),
_ => {}
}
}
@@ -490,27 +347,13 @@ fn contents<'a, 'm>(
blocks.get(&key)
}
/// [`Contents`] of the block `blk`, referenced at `depth`, as the drawing shows them: no viewport's
/// frozen layers are left out. For a clipped reference measured through a viewport ([`bounds_in`]).
/// `in_drawing` keeps them, apart from that viewport's own block bounds.
fn drawing_contents<'a, 'm>(
d: &'a Drawing,
blk: &'a crate::Block,
depth: usize,
off_counts: bool,
in_drawing: &'m mut HashMap<(&'a str, usize), Contents<'a>>,
) -> Option<&'m Contents<'a>> {
// With no layer left out, the measure never asks for the drawing's boxes itself.
contents(d, blk, depth, in_drawing, &mut HashMap::new(), off_counts, &[])
}
/// The box of a constant attribute definition's value, as a block reference draws it: upright
/// when the definition matches the layout's orientation, like other text (#2498).
fn constant_box(a: &crate::Attrib, upright: bool) -> Bounds2 {
let turn = |r: f64| if upright { 0.0 } else { r };
match a.multiline_text() {
Some(m) if !blank(&m.contents) => mtext_box(&crate::MText { rotation: turn(m.rotation), ..m }),
None if !blank(&a.text.value) => text_box(&crate::Text { rotation: turn(a.text.rotation), ..a.text.clone() }, drawn_text(&a.text.value)),
None if !blank(&a.text.value) => text_box(&crate::Text { rotation: turn(a.text.rotation), ..a.text.clone() }, a.text.value.chars().count()),
_ => Bounds2::EMPTY,
}
}
@@ -551,13 +394,13 @@ fn mtext_box(t: &crate::MText) -> Bounds2 {
/// The box of what `e` draws (block contents on layers turned off left out).
pub fn entity_bounds(d: &Drawing, e: &Entity, depth: usize) -> Bounds2 {
bounds_of(d, e, depth, false, &[], &mut HashMap::new(), &mut HashMap::new())
bounds_of(d, e, depth, false, &mut HashMap::new())
}
/// The box `e` takes in the drawing's extents: as [`entity_bounds`], but block contents on a layer
/// turned off count, as AutoCAD 2024's ZOOM Extents counts them (a frozen layer's do not).
pub fn extent_bounds(d: &Drawing, e: &Entity) -> Bounds2 {
bounds_of(d, e, 0, true, &[], &mut HashMap::new(), &mut HashMap::new())
bounds_of(d, e, 0, true, &mut HashMap::new())
}
/// The bounds of block contents measured so far, kept across the entities of one unchanged
@@ -575,95 +418,35 @@ pub struct BlockBoundsCache<'a> {
/// [`entity_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`.
pub fn entity_bounds_cached<'a>(d: &'a Drawing, e: &Entity, depth: usize, cache: &mut BlockBoundsCache<'a>) -> Bounds2 {
bounds_of(d, e, depth, false, &[], &mut cache.drawn, &mut HashMap::new())
bounds_of(d, e, depth, false, &mut cache.drawn)
}
/// [`extent_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`.
pub fn extent_bounds_cached<'a>(d: &'a Drawing, e: &Entity, cache: &mut BlockBoundsCache<'a>) -> Bounds2 {
bounds_of(d, e, 0, true, &[], &mut cache.extents, &mut HashMap::new())
bounds_of(d, e, 0, true, &mut cache.extents)
}
/// The boxes of what one layout viewport draws: [`entity_bounds`] with the block contents on the
/// layers frozen in that viewport left out, as the viewport leaves them out when it draws. It
/// keeps the block bounds it has measured, as a [`BlockBoundsCache`] does, so use one only while
/// the drawing it measured is unchanged. The layers belong to it, so the bounds measured through
/// one viewport never answer for another. Two things a selection counts whatever the viewport
/// draws stay in: a clipped reference (XCLIP) is selected by its boundary, so it keeps the box the
/// drawing gives it, and a dimension by its definition points, which its block holds as points on
/// the layer Defpoints, so such a point counts in any block ([`point_on_defpoints`]).
pub struct ViewportBounds<'a> {
/// The layers frozen in the viewport.
frozen: &'a [String],
/// By block name and depth, the box of the block contents the viewport draws.
blocks: HashMap<(&'a str, usize), Contents<'a>>,
/// The same with no layer of the viewport left out: the box the drawing gives the contents,
/// which a clipped reference keeps.
in_drawing: HashMap<(&'a str, usize), Contents<'a>>,
}
impl<'a> ViewportBounds<'a> {
/// For a viewport that freezes the layers in `frozen` (none: the drawing as it shows anywhere).
pub fn new(frozen: &'a [String]) -> Self {
ViewportBounds { frozen, blocks: HashMap::new(), in_drawing: HashMap::new() }
}
/// The layers frozen in the viewport.
pub fn frozen(&self) -> &'a [String] {
self.frozen
}
/// Whether the viewport leaves `part` out for its layer. `part` is an entity of the block
/// that an object the viewport draws is drawn from (a block reference, a dimension, a
/// multileader), and it is left out when its layer is frozen in the viewport, as in the
/// boxes above. A part on layer 0 never is: it takes the layer of the object, which the
/// caller has checked. What the drawing itself hides (a layer frozen for the whole drawing
/// or turned off) is not looked at here.
pub fn leaves_out(&self, part: &Entity) -> bool {
part.common.layer != "0" && frozen_in(self.frozen, &part.common.layer)
}
/// The box of what the viewport draws of `e`. Like [`entity_bounds`] it does not look at the
/// layer `e` itself is on: whether the viewport draws `e` at all is the caller's to check.
pub fn entity_bounds(&mut self, d: &'a Drawing, e: &Entity) -> Bounds2 {
bounds_of(d, e, 0, false, self.frozen, &mut self.blocks, &mut self.in_drawing)
}
}
/// The box of `e` at `depth` with the block bounds in `blocks` and `in_drawing`: [`bounds_in`], a
/// top-level annotative object measured as it draws.
fn bounds_of<'a>(
d: &'a Drawing,
e: &Entity,
depth: usize,
off_counts: bool,
frozen: &[String],
blocks: &mut HashMap<(&'a str, usize), Contents<'a>>,
in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>,
) -> Bounds2 {
fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blocks: &mut HashMap<(&'a str, usize), Contents<'a>>) -> Bounds2 {
// A top-level annotative object measures as it draws at the current annotation scale.
if depth == 0 {
match d.anno_draw(e) {
crate::AnnoDraw::Plain => {}
crate::AnnoDraw::Hidden => return Bounds2::EMPTY,
crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, in_drawing, off_counts, frozen),
crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, off_counts),
}
}
bounds_in(d, e, depth, blocks, in_drawing, off_counts, frozen)
bounds_in(d, e, depth, blocks, off_counts)
}
/// The bounds of a record kept as read that draws something: a proxy as its proxy graphics draw
/// (layer 0 in them is the proxy's layer), each at the next depth as a block's contents are, and an
/// OLE2FRAME as its frame. Measured through a viewport, the proxy graphics on a layer `frozen`
/// there are left out as a block's parts are ([`in_block_visible`]), and a reference among them
/// takes its boxes from `blocks` and `in_drawing` as any other does ([`bounds_in`]).
/// OLE2FRAME as its frame.
fn unknown_bounds<'a>(
d: &'a Drawing,
u: &crate::Unknown,
depth: usize,
blocks: &mut HashMap<(&'a str, usize), Contents<'a>>,
in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>,
off_counts: bool,
frozen: &[String],
) -> Bounds2 {
if u.graphics.is_empty() {
return ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points);
@@ -673,8 +456,8 @@ fn unknown_bounds<'a>(
}
u.graphics
.iter()
.filter(|g| in_block_visible(d, g, off_counts, frozen))
.fold(Bounds2::EMPTY, |b, g| b.union(&bounds_in(d, g, depth + 1, blocks, in_drawing, off_counts, frozen)))
.filter(|g| in_block_visible(d, g, off_counts))
.fold(Bounds2::EMPTY, |b, g| b.union(&bounds_in(d, g, depth + 1, blocks, off_counts)))
}
/// [`entity_bounds`] with the bounds of block contents (in block coordinates) already computed,
@@ -682,29 +465,19 @@ fn unknown_bounds<'a>(
/// expanding the block again, so nested or self-referencing blocks cost at most one pass over each
/// definition per depth instead of one per reference (which grows exponentially with the nesting
/// depth). The depth is part of the key because [`MAX_BLOCK_DEPTH`] cuts a deep visit short: its
/// bounds must not stand in for a shallower reference to the same block (#706). The bounds in
/// `blocks` depend on `off_counts` and on `frozen` (see [`layer_counts`]), so one map goes with
/// one value of each. `in_drawing` is the map that goes with the same `off_counts` and no frozen
/// layer: a measure through a viewport takes from it the box the drawing gives the block of a
/// clipped reference ([`drawing_contents`]). A measure with no frozen layer does not use it.
fn bounds_in<'a>(
d: &'a Drawing,
e: &Entity,
depth: usize,
blocks: &mut HashMap<(&'a str, usize), Contents<'a>>,
in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>,
off_counts: bool,
frozen: &[String],
) -> Bounds2 {
/// bounds must not stand in for a shallower reference to the same block (#706).
fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<(&'a str, usize), Contents<'a>>, off_counts: bool) -> Bounds2 {
match &e.kind {
EntityKind::Table(t) if t.is_broken() => t.bounds(),
EntityKind::Text(t) if blank(&t.value) => Bounds2::EMPTY,
EntityKind::MText(t) if blank(&t.contents) => Bounds2::EMPTY,
// Text that matches the layout's orientation is drawn upright (#2498).
EntityKind::Text(t) if e.common.matches_layout_orientation() => text_box(&crate::Text { rotation: 0.0, ..t.clone() }, drawn_text(&t.value)),
EntityKind::Text(t) if e.common.matches_layout_orientation() => {
text_box(&crate::Text { rotation: 0.0, ..t.clone() }, t.value.chars().count())
}
EntityKind::MText(t) if e.common.matches_layout_orientation() => mtext_box(&crate::MText { rotation: 0.0, ..t.clone() }),
EntityKind::Text(t) => text_box(t, drawn_text(&t.value)),
EntityKind::AttDef(a) => text_box(&a.text, drawn_text(&a.tag)),
EntityKind::Text(t) => text_box(t, t.value.chars().count()),
EntityKind::AttDef(a) => text_box(&a.text, a.tag.chars().count()),
EntityKind::MText(t) => mtext_box(t),
EntityKind::Insert(ins) => {
if depth >= MAX_BLOCK_DEPTH {
@@ -717,18 +490,9 @@ fn bounds_in<'a>(
let mut defs = None;
if let Some(blk) = d.block(&ins.block) {
let m = ins.transform(blk.base.xy());
let c = contents(d, blk, depth, blocks, in_drawing, off_counts, frozen);
let c = contents(d, blk, depth, blocks, off_counts);
defs = c.map(|c| &c.defs);
let mut inner = c.map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
// XCLIP: the reference app selects a clipped reference by its boundary whatever a
// viewport draws inside it, so a clipped reference keeps the box the drawing gives it.
// One that is not inverted and has a part drawn gets the boundary's box below as it is.
if !frozen.is_empty()
&& let Some(c) = ins.clip.as_ref().filter(|c| c.active())
&& (c.inverted || inner.is_empty())
{
inner = drawing_contents(d, blk, depth, off_counts, in_drawing).map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
}
let inner = c.map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) };
// XCLIP: the reference app takes the boundary's box, also where it reaches past the
// block or misses it (an inverted clip can show anything, so it keeps the block's).
@@ -750,10 +514,10 @@ fn bounds_in<'a>(
}
}
for a in &ins.attribs {
if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts, frozen) {
if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts) {
b = b.union(&match a.multiline_text() {
Some(m) => mtext_box(&m),
None => text_box(&a.text, drawn_text(&a.text.value)),
None => text_box(&a.text, a.text.value.chars().count()),
});
}
}
@@ -787,7 +551,7 @@ fn bounds_in<'a>(
// Reuse the shared block-bounds cache (as the Insert branch does) so a dimension
// block with branching or self-referencing children costs one pass per definition
// per depth, not one per reference (which grows exponentially) (CWE-400).
let inner = contents(d, blk, depth, blocks, in_drawing, off_counts, frozen).map_or(Bounds2::EMPTY, |c| c.geometry);
let inner = contents(d, blk, depth, blocks, off_counts).map_or(Bounds2::EMPTY, |c| c.geometry);
// The block draws translated by the insertion point (group 12), so its bounds
// move with it (#2634); the cache above keeps the block's own bounds.
let off = dm.insertion_point.xy();
@@ -806,7 +570,7 @@ fn bounds_in<'a>(
}
if let Some(ins) = &m.block {
let be = Entity { handle: e.handle, common: e.common.clone(), kind: EntityKind::Insert(ins.clone()) };
b = b.union(&bounds_in(d, &be, depth, blocks, in_drawing, off_counts, frozen));
b = b.union(&bounds_in(d, &be, depth, blocks, off_counts));
}
b
}
@@ -826,7 +590,7 @@ fn bounds_in<'a>(
EntityKind::LwPolyline(p) => lwpolyline_bounds(p),
// A proxy measures as its proxy graphics draw. An OLE object's content is not drawn, but its
// frame is, so the frame counts (#2422).
EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => unknown_bounds(d, u, depth, blocks, in_drawing, off_counts, frozen),
EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => unknown_bounds(d, u, depth, blocks, off_counts),
kind => {
let mut b = Bounds2::EMPTY;
for p in kind.prims() {
@@ -918,8 +682,6 @@ mod tests {
style: "Standard".into(),
halign,
valign,
backwards: false,
upside_down: false,
}
}
@@ -939,7 +701,6 @@ mod tests {
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}
}
@@ -959,15 +720,6 @@ mod tests {
let b = bounds(EntityKind::MText(mtext("A LONG LINE OF WRAPPING TEXT", 5.0)));
assert!((b.max.x - b.min.x - 5.0).abs() < 1e-9, "width {}", b.max.x - b.min.x);
}
#[test]
fn mirrored_text_extends_the_other_way() {
let plain = bounds(EntityKind::Text(text(HAlign::Left, VAlign::Baseline)));
assert!(plain.min.x >= -1e-9 && plain.min.y >= -1e-9);
let back = bounds(EntityKind::Text(Text { backwards: true, upside_down: true, ..text(HAlign::Left, VAlign::Baseline) }));
assert!(back.max.x <= 1e-9 && back.max.y <= 1e-9, "{back:?}");
assert!((back.width() - plain.width()).abs() < 1e-9);
}
#[test]
fn right_justified_text_is_left_of_alignment_point() {
let b = bounds(EntityKind::Text(text(HAlign::Right, VAlign::Baseline)));
@@ -1015,7 +767,6 @@ mod tests {
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
};
let ml = crate::MLeader {
leaders: vec![vec![Vec3::new(0.0, 0.0, 0.0)]],
@@ -1123,247 +874,6 @@ mod tests {
}
}
/// A viewport leaves a part of a block out for its layer when that layer is frozen in the
/// viewport, its name matched whatever its case. A part on layer 0 is never left out, also
/// where the viewport freezes layer 0: it takes the layer of the object drawn from the block.
/// A layer the drawing itself hides (frozen for the whole drawing, or turned off) is not the
/// viewport's to leave out, and a viewport that freezes no layer leaves nothing out.
#[test]
fn a_viewport_leaves_out_the_parts_on_its_frozen_layers() {
let part = |layer: &str| {
let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 0.0) });
let mut e = Entity::new(crate::Handle(1), kind);
e.common.layer = layer.into();
e
};
let frozen = ["hidden".to_string(), "0".to_string()];
let (through, plain) = (ViewportBounds::new(&frozen), ViewportBounds::new(&[]));
assert!(through.leaves_out(&part("Hidden")), "a layer frozen in the viewport, its name in another case");
assert!(!plain.leaves_out(&part("Hidden")), "the same part where no layer is frozen");
assert!(!through.leaves_out(&part("0")), "layer 0 takes the object's layer");
assert!(!through.leaves_out(&part("Other")), "a layer the viewport does not freeze");
}
/// Through a layout viewport the block contents on a layer frozen in it take no room: a part
/// of a reference, a part two blocks deep, a nested reference that is itself on that layer
/// (with everything in it), an attribute, the parts of the block a dimension or a multileader
/// draws (a reference nested in a dimension's block too), and the parts of an annotative
/// reference. A clipped reference (XCLIP) keeps the box the drawing gives it, whatever is drawn
/// of it. The layer's name is matched whatever its case. With no layer frozen
/// the box is the one [`entity_bounds`] gives, and one [`ViewportBounds`] gives every entity
/// the box a fresh one gives it.
#[test]
fn a_viewport_leaves_out_block_contents_on_the_layers_frozen_in_it() {
let line = |handle: u64, y: f64, layer: &str| {
let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) });
let mut e = Entity::new(crate::Handle(handle), kind);
e.common.layer = layer.into();
e
};
let reference = |block: &str| crate::Insert { block: block.into(), ..crate::Insert::default() };
let ins = |block: &str, layer: &str| {
let mut e = Entity::new(crate::Handle(2), EntityKind::Insert(reference(block)));
e.common.layer = layer.into();
e
};
let mut d = Drawing::new_metric();
d.ensure_layer("Hidden");
let mut add = |name: &str, parts: Vec<Entity>| {
let mut b = crate::Block::new(name);
for part in parts {
b.entities.push(part);
}
d.blocks.insert(name.into(), std::sync::Arc::new(b));
};
// B: a line on layer 0 along y = 0 and one on "Hidden" along y = 50. N nests B. Z holds a
// reference to B that is itself on "Hidden", and a line along y = 90. H is all on "Hidden".
add("B", vec![line(1, 0.0, "0"), line(3, 50.0, "Hidden")]);
add("N", vec![ins("B", "0")]);
add("Z", vec![ins("B", "Hidden"), line(1, 90.0, "0")]);
add("H", vec![line(1, 50.0, "Hidden")]);
// A reference to B with an attribute on "Hidden" at y = 70.
let mut tagged = ins("B", "0");
if let EntityKind::Insert(i) = &mut tagged.kind {
i.attribs.push(crate::Attrib {
tag: "T".into(),
text: Text { insert: Vec3::new(0.0, 70.0, 0.0), align_pt: None, ..text(HAlign::Left, VAlign::Baseline) },
invisible: false,
constant: false,
prompt: String::new(),
props: crate::AttribProps { layer: Some("Hidden".into()), ..Default::default() },
multiline: None,
modes: Default::default(),
});
}
// References to H clipped to a boundary around its line, and with that clip inverted: no
// part of either is drawn where "Hidden" is frozen in the viewport. And a reference to B
// with the inverted clip: its line along y = 0 is drawn there.
let clip = |block: &str, inverted: bool| {
let mut e = ins(block, "0");
if let EntityKind::Insert(i) = &mut e.kind {
let boundary = crate::ClipBoundary::new(vec![Vec2::new(-2.0, 40.0), Vec2::new(12.0, 60.0)]);
i.clip = Some(crate::ClipBoundary { inverted, ..boundary });
}
e
};
let (clipped, clipped_inverted, clipped_partly) = (clip("H", false), clip("H", true), clip("B", true));
// An annotative reference to B: measured as it draws at the annotation scale, here 1:1.
let mut scaled = ins("B", "0");
scaled.common.anno_scales = vec![crate::AnnoScale::unit()];
// Dimensions that draw B and N, and a multileader that draws B.
let dimension = |block: &str| {
let kind = EntityKind::Dimension(crate::Dimension {
kind: crate::DimKind::Aligned,
defpt: Vec3::new(5.0, 1.0, 0.0),
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::new(10.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 0.0,
text_rotation: 0.0,
user_text_pos: false,
block: Some(block.into()),
insertion_point: Vec3::ZERO,
overrides: Default::default(),
assoc: Vec::new(),
marks: Default::default(),
});
Entity::new(crate::Handle(3), kind)
};
let (dim, dim_nested) = (dimension("B"), dimension("N"));
let leader = Entity::new(
crate::Handle(4),
EntityKind::MLeader(crate::MLeader {
leaders: vec![vec![Vec3::ZERO]],
landing: Vec3::new(1.0, 0.0, 0.0),
dogleg: 0.45,
text: None,
style: "Standard".into(),
arrow_size: 1.0,
spline: false,
block: Some(reference("B")),
}),
);
let frozen = ["HIDDEN".to_string()];
let mut view = ViewportBounds::new(&frozen);
let ys = |b: Bounds2| (b.min.y, b.max.y);
assert_eq!(ys(entity_bounds(&d, &ins("B", "0"), 0)), (0.0, 50.0));
assert_eq!(ys(view.entity_bounds(&d, &ins("B", "0"))), (0.0, 0.0), "a part on the frozen layer");
assert_eq!(ys(view.entity_bounds(&d, &ins("N", "0"))), (0.0, 0.0), "a part two blocks deep");
assert_eq!(ys(entity_bounds(&d, &ins("Z", "0"), 0)), (0.0, 90.0));
assert_eq!(ys(view.entity_bounds(&d, &ins("Z", "0"))), (90.0, 90.0), "a nested reference on the frozen layer");
assert!(!entity_bounds(&d, &ins("H", "0"), 0).is_empty());
assert!(view.entity_bounds(&d, &ins("H", "0")).is_empty(), "nothing of it is drawn");
let boundary = (Vec2::new(-2.0, 40.0), Vec2::new(12.0, 60.0));
let (drawn, seen) = (entity_bounds(&d, &clipped, 0), view.entity_bounds(&d, &clipped));
assert_eq!((drawn.min, drawn.max), boundary);
assert_eq!((seen.min, seen.max), boundary, "a clipped reference no part of which is drawn keeps its boundary");
assert_eq!(ys(entity_bounds(&d, &clipped_inverted, 0)), (50.0, 50.0));
assert_eq!(ys(view.entity_bounds(&d, &clipped_inverted)), (50.0, 50.0), "and one clipped the other way its block's box");
assert_eq!(ys(entity_bounds(&d, &clipped_partly, 0)), (0.0, 50.0));
assert_eq!(ys(view.entity_bounds(&d, &clipped_partly)), (0.0, 50.0), "with a part drawn too");
assert!(entity_bounds(&d, &tagged, 0).max.y >= 70.0);
assert_eq!(ys(view.entity_bounds(&d, &tagged)), (0.0, 0.0), "an attribute on the frozen layer");
assert_eq!(ys(entity_bounds(&d, &scaled, 0)), (0.0, 50.0));
assert_eq!(ys(view.entity_bounds(&d, &scaled)), (0.0, 0.0), "an annotative reference");
assert_eq!(entity_bounds(&d, &dim, 0).max.y, 50.0);
assert!(view.entity_bounds(&d, &dim).max.y < 50.0, "the block a dimension draws");
assert_eq!(entity_bounds(&d, &dim_nested, 0).max.y, 50.0);
assert!(view.entity_bounds(&d, &dim_nested).max.y < 50.0, "a reference nested in the block a dimension draws");
assert_eq!(entity_bounds(&d, &leader, 0).max.y, 50.0);
assert!(view.entity_bounds(&d, &leader).max.y < 50.0, "the block a multileader draws");
let clips = [clipped, clipped_inverted, clipped_partly];
let all = [ins("B", "0"), ins("N", "0"), ins("Z", "0"), ins("H", "0"), tagged, scaled, dim, dim_nested, leader].into_iter().chain(clips);
let all: Vec<Entity> = all.collect();
let mut plain = ViewportBounds::new(&[]);
for e in &all {
let (shared, fresh) = (view.entity_bounds(&d, e), ViewportBounds::new(&frozen).entity_bounds(&d, e));
assert_eq!((shared.min, shared.max), (fresh.min, fresh.max));
let (unfrozen, drawn) = (plain.entity_bounds(&d, e), entity_bounds(&d, e, 0));
assert_eq!((unfrozen.min, unfrozen.max), (drawn.min, drawn.max));
}
}
/// With the layer Defpoints frozen in the viewport, a point on that layer that is a part of a
/// block still counts: in the block of a reference, one block deeper, in the block of a
/// dimension, as its definition points are held, and in that of a dimension that is itself a
/// part of a block. Here the point lies far above all the rest. A line on Defpoints, a point
/// on another frozen layer and a line on one are left out. One [`ViewportBounds`] gives each of
/// them the box a fresh one gives it.
#[test]
fn a_viewport_keeps_the_points_on_defpoints_in_a_block() {
let line = |handle: u64, y: f64, layer: &str| {
let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) });
let mut e = Entity::new(crate::Handle(handle), kind);
e.common.layer = layer.into();
e
};
let point = |handle: u64, y: f64, layer: &str| {
let mut e = Entity::new(crate::Handle(handle), EntityKind::Point(crate::Point { p: Vec3::new(5.0, y, 0.0), angle: 0.0 }));
e.common.layer = layer.into();
e
};
let ins = |block: &str| Entity::new(crate::Handle(9), EntityKind::Insert(crate::Insert { block: block.into(), ..crate::Insert::default() }));
let dimension = |block: &str| {
let kind = EntityKind::Dimension(crate::Dimension {
kind: crate::DimKind::Aligned,
defpt: Vec3::new(5.0, 1.0, 0.0),
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::new(10.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 0.0,
text_rotation: 0.0,
user_text_pos: false,
block: Some(block.into()),
insertion_point: Vec3::ZERO,
overrides: Default::default(),
assoc: Vec::new(),
marks: Default::default(),
});
Entity::new(crate::Handle(8), kind)
};
let mut d = Drawing::new_metric();
d.ensure_layer("Hidden");
d.ensure_layer("Defpoints");
let mut add = |name: &str, parts: Vec<Entity>| {
let mut block = crate::Block::new(name);
for part in parts {
block.entities.push(part);
}
d.blocks.insert(name.into(), std::sync::Arc::new(block));
};
// P: a line along y = 0 on layer 0, a point on Defpoints at y = 200, a line on Defpoints
// along y = 250 and a line on "Hidden" along y = 300. NP holds a reference to P, DP a
// dimension that draws P. H is P with the point on "Hidden".
add("P", vec![line(1, 0.0, "0"), point(2, 200.0, "Defpoints"), line(3, 250.0, "Defpoints"), line(4, 300.0, "Hidden")]);
add("NP", vec![ins("P")]);
add("DP", vec![dimension("P")]);
add("H", vec![line(1, 0.0, "0"), point(2, 200.0, "Hidden")]);
let ys = |b: Bounds2| (b.min.y, b.max.y);
assert_eq!(ys(entity_bounds(&d, &ins("P"), 0)), (0.0, 300.0));
let frozen = ["HIDDEN".to_string(), "defpoints".to_string()];
let mut view = ViewportBounds::new(&frozen);
assert_eq!(ys(view.entity_bounds(&d, &ins("P"))), (0.0, 200.0), "the point on Defpoints in a reference's block, not the lines");
assert_eq!(ys(view.entity_bounds(&d, &ins("NP"))), (0.0, 200.0), "the same one block deeper");
assert_eq!(view.entity_bounds(&d, &dimension("P")).max.y, 200.0, "a dimension's definition point");
assert_eq!(view.entity_bounds(&d, &ins("DP")).max.y, 200.0, "the same for a dimension in a block");
assert_eq!(ys(view.entity_bounds(&d, &ins("H"))), (0.0, 0.0), "a point on another frozen layer");
// Where the viewport freezes only the other layer, the line on Defpoints counts too.
let hidden = ["Hidden".to_string()];
assert_eq!(ys(ViewportBounds::new(&hidden).entity_bounds(&d, &ins("P"))), (0.0, 250.0));
for e in [ins("P"), ins("NP"), dimension("P"), ins("DP"), ins("H")] {
let (shared, fresh) = (view.entity_bounds(&d, &e), ViewportBounds::new(&frozen).entity_bounds(&d, &e));
assert_eq!((shared.min, shared.max), (fresh.min, fresh.max));
}
}
/// A turned array of references reaches its side copies, not only the first and the last;
/// a hostile count measures only the copies that are drawn.
#[test]
+1 -111
View File
@@ -42,19 +42,11 @@ pub struct ForeignExtra {
pub color_book: Option<(String, String)>,
/// Other unmodelled property groups (material 347, shadow mode 284).
pub props: Vec<RawTag>,
/// Unmodelled groups of the record's own last subclass, written just before its xdata. Filled
/// on save from the entity itself ([`crate::Viewport::extra`]), so that copies keep them.
pub tail: Vec<RawTag>,
}
impl ForeignExtra {
pub fn is_empty(&self) -> bool {
self.xdict.is_none()
&& self.reactors.is_empty()
&& self.xdata.is_empty()
&& self.color_book.is_none()
&& self.props.is_empty()
&& self.tail.is_empty()
self.xdict.is_none() && self.reactors.is_empty() && self.xdata.is_empty() && self.color_book.is_none() && self.props.is_empty()
}
}
@@ -97,36 +89,11 @@ pub struct Foreign {
/// The drawing's own `$ACADVER` is the version it is saved as, which SAVEAS changes, so a
/// later save must not take it for this one (#2471).
pub version: Option<String>,
/// Block references with kept annotation scale contexts, as they were read: what a context
/// is brought up to date from (see [`KeptPlacement`]), by handle.
pub placements: BTreeMap<Handle, KeptPlacement>,
/// The file's registered applications (APPID names as read, in file order). Saving writes
/// them all back, whether or not any xdata still names them.
pub appids: Vec<String>,
}
/// A block reference as read: its insertion point, rotation (radians) and scale, and each of its
/// attributes as read, in order. Its kept contexts were written for it then; what it did since
/// moves them.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct KeptPlacement {
pub insert: crate::geom::Vec3,
pub rotation: f64,
pub scale: crate::geom::Vec3,
pub attribs: Vec<KeptAttrib>,
}
/// An attribute of a block reference as read: its tag, insertion and alignment points and
/// rotation (radians). Found again by tag and place among the reference's attributes with that
/// tag, since the attributes can be reordered or replaced (ATTSYNC) after the file is read.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct KeptAttrib {
pub tag: String,
pub insert: crate::geom::Vec3,
pub align: crate::geom::Vec3,
pub rotation: f64,
}
impl Foreign {
/// The class of the file's CLASSES a proxy's group 91 names (see [`class_number`]), if any.
/// Saving as DWG keeps a proxy with that class and leaves out one whose class it can't name.
@@ -143,47 +110,9 @@ impl Foreign {
&& self.targets.is_empty()
&& self.class_order.is_empty()
&& self.data_store.is_empty()
&& self.placements.is_empty()
&& self.appids.is_empty()
}
/// Re-key what is kept for the record named `from` under each of `kinds` (e.g. `["LAYER"]`, or
/// `["BLOCK_RECORD", "BLOCK", "ENDBLK"]` for a block) to the name `to`, after a rename: its
/// extras ([`Foreign::records`]) and the roles of its file handles ([`Foreign::targets`]), so
/// saving writes its xdata, extension dictionary and reactors on the renamed record. Names
/// compare trimmed and upper-case, as the reader keys them, so a rename that only changes case
/// changes nothing.
pub fn rename(&mut self, kinds: &[&str], from: &str, to: &str) {
let (from, to) = (from.trim().to_ascii_uppercase(), to.trim().to_ascii_uppercase());
if from == to {
return;
}
for kind in kinds {
let old: ForeignKey = ((*kind).to_string(), from.clone());
let new: ForeignKey = ((*kind).to_string(), to.clone());
if let Some(extra) = self.records.remove(&old) {
self.records.insert(new.clone(), extra);
}
self.targets.values_mut().filter(|k| **k == old).for_each(|k| *k = new.clone());
}
}
/// Whether anything is kept for the record named `from` under one of `kinds`: what
/// [`Foreign::rename`] would re-key.
pub fn names(&self, kinds: &[&str], from: &str) -> bool {
let from = from.trim().to_ascii_uppercase();
let hit = |k: &ForeignKey| k.1 == from && kinds.contains(&k.0.as_str());
self.records.keys().any(hit) || self.targets.values().any(hit)
}
/// [`Foreign::rename`] on a drawing's shared copy, which is cloned only when it keeps
/// something for the renamed record and the name really changes (not only its case).
pub fn rename_shared(this: &mut std::sync::Arc<Foreign>, kinds: &[&str], from: &str, to: &str) {
if !from.trim().eq_ignore_ascii_case(to.trim()) && this.names(kinds, from) {
std::sync::Arc::make_mut(this).rename(kinds, from, to);
}
}
/// The entities with a geometry record in the data store: an `ACDSRECORD` naming the entity
/// (320) that holds its `ASM_Data`. A 320 without one doesn't keep an entity's geometry.
pub fn data_store_entities(&self) -> std::collections::BTreeSet<Handle> {
@@ -461,42 +390,3 @@ pub fn class_number<S: AsRef<str>>(groups: impl IntoIterator<Item = (i32, S)> +
pub fn class_index(number: Option<i64>) -> Option<usize> {
usize::try_from(number?.checked_sub(500)?).ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn key(k: &str, n: &str) -> ForeignKey {
(k.to_string(), n.to_string())
}
#[test]
fn rename_rekeys_records_and_targets_of_the_given_kinds_only() {
let mut f = Foreign::default();
let xdict = ForeignExtra { xdict: Some(Handle(0x40)), ..ForeignExtra::default() };
f.records.insert(key("BLOCK_RECORD", "DOOR"), xdict.clone());
f.records.insert(key("LAYER", "DOOR"), ForeignExtra { reactors: vec![Handle(0x41)], ..ForeignExtra::default() });
f.targets.insert(Handle(0x10), key("BLOCK_RECORD", "DOOR"));
f.targets.insert(Handle(0x11), key("BLOCK", "DOOR"));
f.targets.insert(Handle(0x12), key("LAYER", "DOOR"));
f.rename(&["BLOCK_RECORD", "BLOCK", "ENDBLK"], "Door", "Gate");
assert_eq!(f.records.get(&key("BLOCK_RECORD", "GATE")), Some(&xdict));
assert!(!f.records.contains_key(&key("BLOCK_RECORD", "DOOR")));
assert!(f.records.contains_key(&key("LAYER", "DOOR")), "another kind with the same name stays");
assert_eq!(f.targets.get(&Handle(0x10)), Some(&key("BLOCK_RECORD", "GATE")));
assert_eq!(f.targets.get(&Handle(0x11)), Some(&key("BLOCK", "GATE")));
assert_eq!(f.targets.get(&Handle(0x12)), Some(&key("LAYER", "DOOR")));
}
#[test]
fn rename_shared_leaves_an_unrelated_drawing_shared() {
let mut f = Foreign::default();
f.records.insert(key("LAYER", "A"), ForeignExtra { xdict: Some(Handle(0x40)), ..ForeignExtra::default() });
let mut a = std::sync::Arc::new(f);
let snapshot = a.clone();
Foreign::rename_shared(&mut a, &["LAYER"], "B", "C");
assert!(std::sync::Arc::ptr_eq(&a, &snapshot));
Foreign::rename_shared(&mut a, &["LAYER"], "a", "c");
assert!(a.records.contains_key(&key("LAYER", "C")) && snapshot.records.contains_key(&key("LAYER", "A")));
}
}
+6 -15
View File
@@ -31,8 +31,8 @@ pub use cadcraft_geom as geom;
pub use constraint::*;
pub use entity::*;
pub use extents::{
BlockBoundsCache, MAX_BLOCK_DEPTH, ViewportBounds, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, ole_frame,
ole_frame_accepts, ole_frame_transform, point_on_defpoints,
BlockBoundsCache, MAX_BLOCK_DEPTH, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, ole_frame, ole_frame_accepts,
ole_frame_transform,
};
pub use format::Format;
pub use gdt::*;
@@ -41,7 +41,7 @@ pub use names::{Named, NamedList, NamedMap};
pub use plotstyle::*;
pub use plotter::*;
pub use raster::{Raster, Rasters};
pub use refedit::{RefEdit, WorkItem, XrefSource};
pub use refedit::{RefEdit, WorkItem};
pub use store::EntityStore;
pub use tables::*;
pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES};
@@ -112,8 +112,7 @@ pub struct Drawing {
/// Dimension styles in table order; [`Drawing::dim_style`] looks them up by name.
pub dim_styles: NamedList<DimStyle>,
pub mleader_styles: Vec<MLeaderStyle>,
/// Table styles in table order; looked up by name with [`NamedList::by_name`].
pub table_styles: NamedList<TableStyle>,
pub table_styles: Vec<TableStyle>,
/// Multiline styles (MLSTYLE); STANDARD is always there.
pub mline_styles: Vec<MLineStyle>,
/// Block definitions by name; [`Drawing::block`] looks them up.
@@ -121,9 +120,6 @@ pub struct Drawing {
pub model: EntityStore,
/// Model layout's page setup, or the default extents-to-fit setup for a new drawing.
pub model_page: Option<PageSetup>,
/// The Model layout's own flags as the file had them (see [`Layout::flags`]); `None` for a
/// new drawing.
pub model_layout_flags: Option<i64>,
/// Layouts in list order (`tab_order` orders the tabs); [`Drawing::layout`] looks them up by name.
pub layouts: NamedList<Layout>,
/// The layout a file marks active (its block is `*Paper_Space`, the others `*Paper_SpaceN`),
@@ -177,9 +173,6 @@ pub struct Drawing {
/// turns those indices into the written table's (#3094). An empty name stands for a record
/// without one. Empty for a drawing not read from a file.
pub proxy_layers: Vec<String>,
/// The LTYPE table of that file in the same way, without ByBlock and ByLayer (proxy graphics
/// count the others).
pub proxy_linetypes: Vec<String>,
}
impl Default for Drawing {
@@ -202,7 +195,7 @@ impl Drawing {
d.scales = metric_scales();
d.dim_styles.push(DimStyle::iso25());
d.mleader_styles = vec![MLeaderStyle::metric()];
d.table_styles = vec![TableStyle::metric()].into();
d.table_styles = vec![TableStyle::metric()];
d.header.set_str("DIMSTYLE", "ISO-25");
d
}
@@ -220,12 +213,11 @@ impl Drawing {
text_styles: vec![TextStyle::default()].into(),
dim_styles: vec![DimStyle::default()].into(),
mleader_styles: vec![MLeaderStyle::default()],
table_styles: vec![TableStyle::default()].into(),
table_styles: vec![TableStyle::default()],
mline_styles: vec![MLineStyle::default()],
blocks: NamedMap::default(),
model: EntityStore::new(),
model_page: None,
model_layout_flags: None,
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)].into(),
active_layout: None,
views: Vec::new(),
@@ -247,7 +239,6 @@ impl Drawing {
portable_fonts: false,
rasters: Rasters::default(),
proxy_layers: Vec::new(),
proxy_linetypes: Vec::new(),
}
}
-38
View File
@@ -250,44 +250,6 @@ pub fn pattern_for(d: &Drawing, name: &str) -> Option<HatchPattern> {
Some(if d.header.i64("MEASUREMENT", 0) == 1 { scaled_pattern(p, 25.4) } else { p })
}
/// The pattern name of a user-defined hatch, as the DXF Reference writes it (group 2). Its families
/// are not a named pattern's: a hatch stores them at unit scale, turned by its angle and spaced by
/// its scale (groups 52, 41 and 77 of a DXF file), so [`user_defined_lines`] makes them for a file
/// that lists none (AutoCAD's own are written with 78 = 0).
pub const USER_PATTERN: &str = "_USER";
/// Whether `name` is a user-defined hatch's pattern name ([`USER_PATTERN`], in any case).
pub fn is_user_pattern(name: &str) -> bool {
name.eq_ignore_ascii_case(USER_PATTERN)
}
/// 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;
/// Whether the scale can be used for hatch pattern lines.
pub fn is_supported_hatch_pattern_scale(scale: f64) -> bool {
scale.is_finite() && scale > MIN_HATCH_PATTERN_SCALE
}
/// The effective scale of a stored hatch. Use unit scale when its scale is unusable.
pub fn effective_hatch_pattern_scale(scale: f64) -> f64 {
if is_supported_hatch_pattern_scale(scale) { scale } else { 1.0 }
}
/// The line families of a user-defined hatch at unit scale, as a pattern definition has them: lines
/// along the hatch's angle, its scale apart, and with `double` a second family at right angles to
/// them. The hatch's angle turns the families and its scale spaces them, so a hatch of spacing
/// `s` and lines at `a` stores angle `a`, scale `s` and these families.
pub fn user_defined_lines(double: bool) -> Vec<PatternLine> {
let family = || PatternLine { angle: 0.0, origin: (0.0, 0.0), delta: (0.0, 1.0), dashes: Vec::new() };
if double { vec![family(), PatternLine { angle: 90.0, ..family() }] } else { vec![family()] }
}
/// `p` with every length (origins, offsets, dashes) multiplied by `k`.
fn scaled_pattern(mut p: HatchPattern, k: f64) -> HatchPattern {
for l in &mut p.lines {
+6 -6
View File
@@ -1,6 +1,6 @@
//! The drawing's tables of named entries (layers, blocks, linetypes, text styles, dimension styles,
//! table styles and layouts), whose names are looked up without case through an index instead of a
//! scan once a table is large and looked up often.
//! The drawing's tables of named entries (layers, blocks, linetypes, text styles, dimension styles
//! and layouts), whose names are looked up without case through an index instead of a scan once a
//! table is large and looked up often.
//!
//! [`Drawing::layer`](crate::Drawing::layer), [`Drawing::block`](crate::Drawing::block) and the
//! other lookups by name run for every entity while a drawing is read, measured and drawn, and
@@ -117,11 +117,11 @@ macro_rules! named_by_field {
}
)*};
}
named_by_field!(crate::Layer, crate::Linetype, crate::TextStyle, crate::DimStyle, crate::TableStyle, crate::Layout);
named_by_field!(crate::Layer, crate::Linetype, crate::TextStyle, crate::DimStyle, crate::Layout);
/// A list of named entries in their own order (the drawing's layers, linetypes, text styles,
/// dimension styles, table styles and layouts). It reads and changes as a `Vec`;
/// [`NamedList::by_name`] finds the first entry of a name without case.
/// dimension styles and layouts). It reads and changes as a `Vec`; [`NamedList::by_name`] finds the
/// first entry of a name without case.
pub struct NamedList<T> {
list: Vec<T>,
index: Lazy<usize>,
+11 -50
View File
@@ -186,11 +186,7 @@ impl PlotStyle {
/// The printed colour of an object drawn in `rgb`: the style's colour (else `rgb`), turned
/// grey when asked, then screened toward white.
pub fn apply_color(&self, rgb: Rgb) -> Rgb {
self.shade(self.color.unwrap_or(rgb))
}
/// `c` turned grey when the style asks for it, then screened toward white: what the style
/// does to a colour it does not replace.
pub fn shade(&self, c: Rgb) -> Rgb {
let c = self.color.unwrap_or(rgb);
let c = if self.grayscale {
let g = (c.luma().clamp(0.0, 1.0) * 255.0).round() as u8;
Rgb(g, g, g)
@@ -376,65 +372,30 @@ impl PlotStyleTable {
}
}
/// The tables of the user's plot style folder, as the host last read them (see
/// [`set_plot_style_folder`]). Empty until a host reads a folder.
static FOLDER: std::sync::RwLock<Option<std::sync::Arc<Vec<PlotStyleTable>>>> = std::sync::RwLock::new(None);
/// Replace the tables of the user's plot style folder that every drawing can use. The host reads
/// the folder (this crate does no file I/O) and calls this again after each change.
pub fn set_plot_style_folder(tables: Vec<PlotStyleTable>) {
if let Ok(mut f) = FOLDER.write() {
*f = Some(std::sync::Arc::new(tables));
}
}
/// The tables of the user's plot style folder (empty when the host has read none).
pub fn plot_style_folder() -> std::sync::Arc<Vec<PlotStyleTable>> {
FOLDER.read().ok().and_then(|f| f.clone()).unwrap_or_default()
}
/// The folder's table called `name` (case-insensitive).
pub fn plot_style_folder_table(name: &str) -> Option<PlotStyleTable> {
let n = name.trim();
plot_style_folder().iter().find(|t| t.name.eq_ignore_ascii_case(n)).cloned()
}
/// Whether a page setup's table name means "no plot style table".
pub fn no_plot_style_table(name: &str) -> bool {
let n = name.trim();
n.is_empty() || n.eq_ignore_ascii_case("none")
}
/// The plot style table a page setup names, if it is one we know: the drawing's own tables first
/// (a folder table a layout chose is copied into the drawing, and the drawing then plots with its
/// copy whatever happens to the file), then the user's plot style folder, then the built-in ones. `None` for no table (empty or "None") and for tables we don't have.
/// The plot style table a page setup names, if it is one we know: the drawing's own tables
/// first, then the built-in ones. `None` for no table (empty or "None") and for tables we don't
/// have.
pub fn plot_style_table(d: &crate::Drawing, name: &str) -> Option<PlotStyleTable> {
if no_plot_style_table(name) {
return None;
}
let n = name.trim();
d.plot_style_tables
.iter()
.find(|t| t.name.eq_ignore_ascii_case(n))
.cloned()
.or_else(|| plot_style_folder_table(n))
.or_else(|| PlotStyleTable::builtin(n))
d.plot_style_tables.iter().find(|t| t.name.eq_ignore_ascii_case(n)).cloned().or_else(|| PlotStyleTable::builtin(n))
}
/// The names of every table a drawing can use: the drawing's own, the folder's, then the built-in
/// ones, each name once.
/// The names of every table a drawing can use: its own, then the built-in ones it doesn't
/// shadow.
pub fn plot_style_table_names(d: &crate::Drawing) -> Vec<String> {
let mut v: Vec<String> = Vec::new();
let folder = plot_style_folder();
let all = d
.plot_style_tables
.iter()
.map(|t| t.name.as_str())
.chain(folder.iter().map(|t| t.name.as_str()))
.chain(BUILTIN_PLOT_STYLE_TABLES.iter().copied());
for n in all {
if !v.iter().any(|x| x.eq_ignore_ascii_case(n)) {
v.push(n.to_string());
let mut v: Vec<String> = d.plot_style_tables.iter().map(|t| t.name.clone()).collect();
for b in BUILTIN_PLOT_STYLE_TABLES {
if !v.iter().any(|n| n.eq_ignore_ascii_case(b)) {
v.push((*b).to_string());
}
}
v
+3 -12
View File
@@ -79,21 +79,15 @@ impl Default for DevicePaper {
impl DevicePaper {
/// The paper with hostile values fixed: finite sizes within 1..=[`MAX_PAPER_MM`] mm
/// (portrait), margins 0..=1000 mm that leave a printable area (else none), a name of at
/// most [`MAX_PLOTTER_NAME`] characters. A sheet wider than tall is stored turned 90° and
/// its margins turn with it, so the printable area the caller measured against the sheet it
/// named is the one the stored portrait paper holds.
/// most [`MAX_PLOTTER_NAME`] characters.
pub fn sanitized(mut self) -> DevicePaper {
let side = |v: f64| if v.is_finite() { v.clamp(1.0, MAX_PAPER_MM) } else { 1.0 };
let (w, h) = (side(self.width), side(self.height));
self.width = w.min(h);
self.height = w.max(h);
for m in &mut self.margins {
*m = if m.is_finite() { m.clamp(0.0, 1000.0) } else { 0.0 };
}
if w > h {
let [l, b, r, t] = self.margins;
self.margins = [b, r, t, l];
}
self.width = w.min(h);
self.height = w.max(h);
let [l, b, r, t] = self.margins;
if l + r >= self.width || b + t >= self.height {
self.margins = [0.0; 4];
@@ -249,9 +243,6 @@ mod tests {
assert_eq!(back.papers[1].margins, [0.0, 1000.0, 0.0, 5.0], "hostile margins clamped");
let wide = DevicePaper { margins: [150.0, 0.0, 100.0, 0.0], ..DevicePaper::default() }.sanitized();
assert_eq!(wide.margins, [0.0; 4], "margins wider than the paper are dropped");
let turned = DevicePaper { name: "Banner".into(), width: 400.0, height: 200.0, margins: [150.0, 0.0, 150.0, 0.0] }.sanitized();
assert_eq!((turned.width, turned.height), (200.0, 400.0), "portrait");
assert_eq!(turned.margins, [0.0, 150.0, 0.0, 150.0], "margins turn with the sheet");
assert!(back.paper("a3 BORDERLESS").is_some());
assert!(PlotterConfig::from_file_text("{}").is_err());
assert!(PlotterConfig::from_file_text(r#"{"cadcraftPlotter": 1}"#).is_err(), "needs a name");
-30
View File
@@ -42,36 +42,6 @@ pub struct RefEdit {
/// Block objects taken out of the working set with their edits (block coordinates, the block
/// object's handle).
pub released: Vec<Entity>,
/// The nested references picked through to reach the edited block: block references inside
/// block definitions, outermost first. Empty when the picked reference's own block is edited.
pub path: Vec<Handle>,
/// Set when the edited block comes from an external reference: REFCLOSE Save writes it back
/// into its source drawing.
pub xref: Option<XrefSource>,
}
/// Where an xref edited in place is written back to.
#[derive(Clone, Debug, PartialEq)]
pub struct XrefSource {
/// The xref (its block name in this drawing).
pub xref: String,
/// The source drawing file.
pub file: String,
/// `file` with every symbolic link resolved when the edit began: the file that is written.
/// The save is refused when `file` leads somewhere else by then.
pub real: String,
/// The version the file was in when the edit began, as its `$ACADVER` code ("AC1015"): it
/// is written back in that version (`None`: in the drawing's own).
pub version: Option<String>,
/// Whether the file is a binary DXF (written back as one).
pub binary: bool,
/// The block of the source drawing being edited; `None` for its model space.
pub block: Option<String>,
/// The file's size and modification time when the edit began.
pub stamp: Option<(u64, std::time::SystemTime)>,
/// Edited block objects (their handles in this drawing) and the objects of the source
/// drawing they were loaded from.
pub sources: Vec<(Handle, Handle)>,
}
impl RefEdit {
+1 -74
View File
@@ -6,19 +6,12 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use crate::{Entity, Handle};
const CHUNK_MAX: usize = 1024;
const SHARDS: usize = 64;
/// A content token no store has had: one count for the process (a `u64` does not run out).
fn next_token() -> u64 {
static NEXT: AtomicU64 = AtomicU64::new(1);
NEXT.fetch_add(1, Ordering::Relaxed)
}
#[derive(Clone, Debug, Default)]
struct Chunk {
id: u32,
@@ -31,19 +24,11 @@ pub struct EntityStore {
shards: Vec<Arc<HashMap<Handle, u32>>>,
len: usize,
next_chunk: u32,
/// This state of the entities ([`EntityStore::content_token`]). Not part of [`PartialEq`].
token: u64,
}
impl Default for EntityStore {
fn default() -> Self {
EntityStore {
chunks: Vec::new(),
shards: (0..SHARDS).map(|_| Arc::new(HashMap::new())).collect(),
len: 0,
next_chunk: 0,
token: next_token(),
}
EntityStore { chunks: Vec::new(), shards: (0..SHARDS).map(|_| Arc::new(HashMap::new())).collect(), len: 0, next_chunk: 0 }
}
}
@@ -62,17 +47,6 @@ impl EntityStore {
pub fn new() -> Self {
Self::default()
}
/// A number for this state of the entities: a clone has it too, and every edit gives the
/// store a number no store has had, so two stores with one token hold the same entities in
/// the same order. What is derived from the entities (a block's ATTDEFs by tag) can be kept
/// under it. Not part of [`PartialEq`]: equal stores can have different tokens.
pub fn content_token(&self) -> u64 {
self.token
}
/// The entities are about to change: a new token.
fn edited(&mut self) {
self.token = next_token();
}
pub fn len(&self) -> usize {
self.len
}
@@ -127,7 +101,6 @@ impl EntityStore {
self.replace(e);
return;
}
self.edited();
let needs_new = self.chunks.last().is_none_or(|c| c.items.len() >= CHUNK_MAX);
if needs_new {
let c = self.new_chunk();
@@ -147,7 +120,6 @@ impl EntityStore {
self.replace(e);
return;
}
self.edited();
let needs_new = self.chunks.first().is_none_or(|c| c.items.len() >= CHUNK_MAX);
if needs_new {
let c = self.new_chunk();
@@ -165,7 +137,6 @@ impl EntityStore {
pub fn replace(&mut self, e: Entity) -> bool {
let Some(id) = self.chunk_id(e.handle) else { return false };
let Some(pos) = self.chunk_pos(id) else { return false };
self.edited();
let Some(c) = self.chunks.get_mut(pos) else { return false };
let chunk = Arc::make_mut(c);
if let Some(slot) = chunk.items.iter_mut().find(|x| x.handle == e.handle) {
@@ -178,7 +149,6 @@ impl EntityStore {
pub fn remove(&mut self, h: Handle) -> Option<Arc<Entity>> {
let id = self.chunk_id(h)?;
let pos = self.chunk_pos(id)?;
self.edited();
let c = self.chunks.get_mut(pos)?;
let chunk = Arc::make_mut(c);
let i = chunk.items.iter().position(|x| x.handle == h)?;
@@ -195,7 +165,6 @@ impl EntityStore {
pub fn modify<F: FnOnce(&mut Entity)>(&mut self, h: Handle, f: F) -> bool {
let Some(id) = self.chunk_id(h) else { return false };
let Some(pos) = self.chunk_pos(id) else { return false };
self.edited();
let Some(c) = self.chunks.get_mut(pos) else { return false };
let chunk = Arc::make_mut(c);
match chunk.items.iter_mut().find(|x| x.handle == h) {
@@ -250,7 +219,6 @@ impl EntityStore {
self.push(Arc::unwrap_or_clone(e));
return false;
};
self.edited();
let Some(c) = self.chunks.get_mut(pos) else {
// Unreachable in practice too; never lose the object.
self.push(Arc::unwrap_or_clone(e));
@@ -329,47 +297,6 @@ mod tests {
Entity::new(Handle(h), EntityKind::Point(Point { p: Vec2::new(h as f64, 0.0).to3(0.0), angle: 0.0 }))
}
/// One token per state of the entities: shared by clones, new after every kind of edit, and
/// different for copies edited apart (#1660's ATTDEF index is kept by it).
#[test]
fn a_content_token_names_one_state_of_the_entities() {
let mut a = EntityStore::new();
for h in 1..=3 {
a.push(ent(h));
}
assert_eq!(a.clone().content_token(), a.content_token(), "a clone holds the same entities");
let (mut b, mut c) = (a.clone(), a.clone());
assert!(b.modify(Handle(1), |e| e.common.layer = "B".into()));
assert!(c.modify(Handle(1), |e| e.common.layer = "C".into()));
assert_ne!(b.content_token(), c.content_token(), "copies edited apart");
assert_ne!(b.content_token(), a.content_token());
let edits: [fn(&mut EntityStore); 8] = [
|s| s.push(ent(9)),
|s| s.push_front(ent(8)),
|s| {
s.replace(ent(2));
},
|s| {
s.remove(Handle(3));
},
|s| {
s.bring_to_front(Handle(1));
},
|s| {
s.send_to_back(Handle(2));
},
|s| {
s.move_next_to(Handle(1), Handle(2), true);
},
|s| s.sort_by_key(|e| std::cmp::Reverse(e.handle.0)),
];
for (i, edit) in edits.iter().enumerate() {
let mut s = a.clone();
edit(&mut s);
assert_ne!(s.content_token(), a.content_token(), "edit {i}");
}
}
#[test]
fn push_get_remove() {
let mut s = EntityStore::new();
-16
View File
@@ -725,17 +725,9 @@ pub struct Block {
pub explodable: bool,
#[serde(default)]
pub units: u8,
/// References to this block scale uniformly (the BLOCK_RECORD's group 281).
#[serde(default)]
pub scale_uniformly: bool,
/// The parameters of an associative array when this is an array block.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub array: Option<crate::ArrayParams>,
/// An xref's file as its loaded objects were read from it: size and modification time (as the
/// system gives it, so a time before 1970 is kept too). Kept per drawing, so an edit in place (REFEDIT) can tell whether
/// the file changed since this drawing loaded it (session state; not saved).
#[serde(skip)]
pub xref_stamp: Option<(u64, std::time::SystemTime)>,
}
/// The load state of an external reference.
@@ -781,9 +773,7 @@ impl Block {
xref_path: None,
explodable: true,
units: 0,
scale_uniformly: false,
array: None,
xref_stamp: None,
}
}
}
@@ -909,11 +899,6 @@ pub struct Layout {
/// them; `None` for a layout CADCraft made, written as 0,0 to 12,9 (#2109).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limits: Option<(Vec2, Vec2)>,
/// The layout's own flags (LAYOUT group 70 after the AcDbLayout marker; DXF Reference: 1 is
/// its PSLTSCALE and 2 its LIMCHECK, each the value while the layout is current) as the file
/// had them; `None` for a layout CADCraft made, saved with the drawing's PSLTSCALE.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub flags: Option<i64>,
}
impl Layout {
@@ -927,7 +912,6 @@ impl Layout {
ucs: None,
ucs_previous: Vec::new(),
limits: None,
flags: None,
}
}
}
+4 -119
View File
@@ -29,7 +29,7 @@ fn new_metric_drawing_has_metric_multileader_and_table_styles() {
let i = Drawing::new_imperial();
assert_eq!(i.mleader_styles, vec![MLeaderStyle::default()]);
assert_eq!(*i.table_styles, vec![TableStyle::default()]);
assert_eq!(i.table_styles, vec![TableStyle::default()]);
assert_eq!((i.mleader_styles[0].text_height, i.table_styles[0].text_height), (0.18, 0.18));
}
@@ -222,8 +222,6 @@ fn visible_attributes_of_a_missing_block_still_count() {
style: "Standard".into(),
halign: HAlign::Left,
valign: VAlign::Baseline,
backwards: false,
upside_down: false,
},
invisible,
constant: false,
@@ -273,46 +271,6 @@ fn transform_arc_mirror_keeps_shape() {
}
}
#[test]
fn mirroring_a_rotated_dimension_reflects_its_direction() {
let dim = |kind: DimKind, marks: DimMarks| {
EntityKind::Dimension(Dimension {
kind,
defpt: Vec3::ZERO,
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::new(7.071_067_811_865_475, 7.071_067_811_865_475, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 10.0,
text_rotation: 0.0,
user_text_pos: false,
block: None,
insertion_point: Vec3::ZERO,
overrides: Default::default(),
assoc: vec![],
marks,
})
};
// A dimension line at 45° mirrored across the X axis runs at -45° (315°) and still measures 10.
let mut k = dim(DimKind::Linear { rotation: std::f64::consts::FRAC_PI_4 }, DimMarks::default());
k.transform(&Mat3::mirror(Vec2::ZERO, Vec2::X));
let EntityKind::Dimension(d) = k else { panic!("a dimension") };
let DimKind::Linear { rotation } = d.kind else { panic!("a linear dimension") };
assert!((rotation - 7.0 * std::f64::consts::FRAC_PI_4).abs() < 1e-9, "{rotation}");
let p2 = Vec2::new(7.071_067_811_865_475, -7.071_067_811_865_475);
assert!((p2.dot(Vec2::from_angle(rotation)).abs() - 10.0).abs() < 1e-9, "the mirrored measurement");
// Oblique extension lines reflect about the mirror line too (a 45° line here) instead of
// being double-reflected (120° rather than 30°).
let mut k = dim(DimKind::Aligned, DimMarks { oblique: Some(std::f64::consts::FRAC_PI_3), ..DimMarks::default() });
k.transform(&Mat3::mirror(Vec2::ZERO, Vec2::new(1.0, 1.0)));
let EntityKind::Dimension(d) = k else { panic!("a dimension") };
assert!((d.marks.oblique.unwrap_or(0.0) - (std::f64::consts::FRAC_PI_2 - std::f64::consts::FRAC_PI_3)).abs() < 1e-9, "{:?}", d.marks.oblique);
}
#[test]
fn insert_bounds_with_cyclic_block_terminate() {
let mut d = Drawing::new_imperial();
@@ -485,8 +443,6 @@ fn plain_attrib(tag: &str) -> Attrib {
style: "Standard".into(),
halign: HAlign::Left,
valign: VAlign::Baseline,
backwards: false,
upside_down: false,
},
invisible: false,
constant: false,
@@ -642,8 +598,6 @@ fn attdef_in_block_is_ignored_in_insert_extents() {
style: "Standard".into(),
halign: HAlign::Left,
valign: VAlign::Baseline,
backwards: false,
upside_down: false,
},
invisible: false,
constant: false,
@@ -669,8 +623,6 @@ fn text_kind(value: &str) -> EntityKind {
style: "Standard".into(),
halign: HAlign::Left,
valign: VAlign::Baseline,
backwards: false,
upside_down: false,
})
}
@@ -686,7 +638,6 @@ fn mtext_kind(contents: &str) -> EntityKind {
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
})
}
@@ -940,68 +891,6 @@ fn constant_values_count_in_extents_as_attmode_shows_them() {
assert!(top(2, true) > 40.0, "ATTMODE 2 shows an invisible one");
}
#[test]
fn aligned_and_fit_text_extents_span_their_two_points() {
// Drawn from the first point to the second whatever rotation is stored: Fit at its own height,
// Aligned at the height that keeps its proportions.
let ext = |halign: HAlign, second: Option<Vec3>| {
let mut t = plain_attrib("T").text;
t.value = "AB".into();
(t.halign, t.align_pt) = (halign, second);
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap();
extents_pair(&d)
};
let left = ext(HAlign::Left, None);
// Along x to a far second point: both reach it; only Aligned grows taller.
let far = Some(Vec3::new(20.0, 0.0, 0.0));
let (fit, aligned) = (ext(HAlign::Fit, far), ext(HAlign::Aligned, far));
assert!((fit.1.x - 20.0).abs() < 1e-9 && (aligned.1.x - 20.0).abs() < 1e-9, "{fit:?} {aligned:?}");
assert!(fit.1.x > left.1.x + 10.0, "wider than the same text left-justified");
assert_eq!(fit.1.y, left.1.y, "Fit keeps its height");
assert!(aligned.1.y > left.1.y * 5.0, "Aligned scales its height with its width");
// Straight up: the line turns to run to the second point.
let up = ext(HAlign::Fit, Some(Vec3::new(0.0, 20.0, 0.0)));
assert!((up.1.y - 20.0).abs() < 1e-9 && up.1.x < 1.0 && up.0.x < -0.5, "{up:?}");
// No second point, or one on the first: placed like left-justified text.
assert_eq!(ext(HAlign::Fit, None), left);
assert_eq!(ext(HAlign::Aligned, Some(Vec3::ZERO)), left);
}
#[test]
fn aligned_text_extents_keep_the_proportions_of_a_narrow_width_factor() {
// The fonts shape with the width factor as stored, so a text ten times narrower fitted over
// the same span is drawn ten times taller: its extents grow with it.
let top = |width_factor: f64| {
let mut t = plain_attrib("T").text;
t.value = "AB".into();
(t.halign, t.align_pt, t.width_factor) = (HAlign::Aligned, Some(Vec3::new(20.0, 0.0, 0.0)), width_factor);
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap();
extents_pair(&d).1.y
};
assert!(top(0.001) > top(0.01) * 5.0, "{} {}", top(0.001), top(0.01));
}
#[test]
fn aligned_and_fit_text_extents_follow_how_unusable_sizes_are_drawn() {
let ext = |halign: HAlign, height: f64, width_factor: f64| {
let mut t = plain_attrib("T").text;
t.value = "AB".into();
(t.halign, t.align_pt, t.height, t.width_factor) = (halign, Some(Vec3::new(1000.0, 0.0, 0.0)), height, width_factor);
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap();
extents_pair(&d)
};
// A height of 0 is drawn as a height of 1: Aligned text still spans its points and has room.
let flat = ext(HAlign::Aligned, 0.0, 1.0);
assert!((flat.1.x - 1000.0).abs() < 1e-9 && flat.1.y > flat.0.y, "{flat:?}");
assert_eq!(flat, ext(HAlign::Aligned, 1.0, 1.0));
// Fit text with a width factor of 0 is not stretched to the second point.
assert!(ext(HAlign::Fit, 1.0, 0.0).1.x < 100.0);
assert!((ext(HAlign::Fit, 1.0, 1.0).1.x - 1000.0).abs() < 1e-9);
}
#[test]
fn an_attribute_lies_on_the_layer_of_the_first_definition_of_its_tag() {
// Two definitions of one tag, in different case, on a frozen layer and on layer 0: an
@@ -1076,13 +965,9 @@ fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() {
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
ins.attribs = (0..N).map(|i| plain_attrib(&tag('A', i))).collect();
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let (bounds, cross_probes) = crate::TagKey::with_cross_probes(1000, || d.extents(&Space::Model));
assert!(!bounds.is_empty());
// Layer inheritance and the constant-value filter each query the opposite set.
// With no matches, an unindexed scan bypasses the probe (zero) or compares every pair.
for probes in cross_probes {
assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {cross_probes:?}");
}
let t = std::time::Instant::now();
assert!(!d.extents(&Space::Model).is_empty());
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
/// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N
+3 -6
View File
@@ -7,7 +7,7 @@
//! that contain themselves lose the reference that closes the loop, and objects sharing a handle
//! get new ones.
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use cadcraft_doc::{Block, DimStyle, Drawing, Entity, EntityKind, EntityStore, Handle, Layer, Linetype, MLeaderStyle, TableStyle, TextStyle};
@@ -425,9 +425,6 @@ fn references(d: &mut Drawing, out: &mut Vec<Issue>) {
let all = all_handles(d);
let ok_text = |d: &Drawing, n: &str| d.text_style(n).is_some();
let ok_dim = |d: &Drawing, n: &str| d.dim_style(n).is_some();
// Multileader style names, lower-cased, built once: a scan per multileader made a file of N of
// them naming styles among N quadratic to audit (#1924).
let mleader_styles: BTreeSet<String> = d.mleader_styles.iter().map(|s| s.name.to_ascii_lowercase()).collect();
// Missing names, counted: (what, name) → (objects, first location).
let mut counts: BTreeMap<(&'static str, String), (usize, String)> = BTreeMap::new();
missing_layers(d, out);
@@ -465,12 +462,12 @@ fn references(d: &mut Drawing, out: &mut Vec<Issue>) {
if let Some(t) = &mut m.text {
text_style(&mut t.style);
}
if !mleader_styles.contains(&m.style.to_ascii_lowercase()) {
if !has_name(&d.mleader_styles, &m.style, |s| &s.name) {
note("multileader style", &m.style);
m.style = "Standard".into();
}
}
EntityKind::Table(t) if d.table_styles.by_name(&t.style).is_none() => {
EntityKind::Table(t) if !has_name(&d.table_styles, &t.style, |s| &s.name) => {
note("table style", &t.style);
t.style = "Standard".into();
}
+2 -25
View File
@@ -166,9 +166,6 @@ pub struct Autosaver {
start: std::time::Instant,
#[cfg(not(target_arch = "wasm32"))]
last_beat: Option<f64>,
/// Who-has-it-open locks of the drawings open from files ([`crate::drawlock`]).
#[cfg(not(target_arch = "wasm32"))]
drawing_locks: crate::drawlock::Locks,
/// This app's lock files: one per folder, because SAVEFILEPATH can change while files remain
/// in the old folder. Each with the file it holds open for the system lock, or `None` where
/// locks don't work and only the file's age counts.
@@ -190,8 +187,6 @@ impl Autosaver {
#[cfg(not(target_arch = "wasm32"))]
last_beat: None,
#[cfg(not(target_arch = "wasm32"))]
drawing_locks: crate::drawlock::Locks::default(),
#[cfg(not(target_arch = "wasm32"))]
locks: Vec::new(),
}
}
@@ -461,8 +456,7 @@ mod native {
impl Autosaver {
/// Autosave what is due (writing in the background) and delete files no longer needed.
/// Returns how long until the next autosave or drawing-lock heartbeat is due, so the host
/// can wake up for it.
/// Returns how long until the next autosave is due, so the host can wake up for it.
pub fn tick(&mut self, s: &Session) -> Option<Duration> {
let now = self.start.elapsed().as_secs_f64();
self.reap();
@@ -471,23 +465,7 @@ mod native {
let jobs = self.plan(s, now, minutes, &dir);
self.perform(jobs);
self.heartbeat(&dir, now);
self.drawing_locks.sync(s, &self.instance);
// The drawing locks need their heartbeat even with nothing to autosave (SAVETIME 0,
// every drawing saved): left untouched they go stale and another app takes them over.
let due = self.next_due(now, minutes).map(Duration::from_secs_f64);
due.into_iter().chain(self.drawing_locks.next_beat()).min()
}
/// Keep the drawing locks with `locks` instead of the default ones (e.g. a shorter
/// heartbeat, see [`crate::drawlock::Locks::with_heartbeat`]).
pub fn with_locks(mut self, locks: crate::drawlock::Locks) -> Self {
self.drawing_locks = locks;
self
}
/// What the drawing locks have to tell the user (someone else has a drawing open).
pub fn take_lock_notes(&mut self) -> Vec<String> {
self.drawing_locks.take_notes()
self.next_due(now, minutes).map(Duration::from_secs_f64)
}
/// Autosave every drawing with changes not yet autosaved right away, without waiting for
@@ -663,7 +641,6 @@ mod native {
let _ = h.join();
}
self.busy.clear();
self.drawing_locks.release_all(&self.instance);
for path in self.files() {
discard(&path);
}
-6
View File
@@ -280,9 +280,6 @@ impl DocState {
self.view_history.clear();
self.block_edit = Some(be);
self.revision += 1;
// The editor's drawing is another drawing with the host's handles: a name given in the
// host must not resolve in it (BCLOSE ends the editor's names the same way, #1660).
self.expire_names();
}
/// Save the Block Editor's objects into the block (BSAVE), or into a new block `as_name`
@@ -349,9 +346,6 @@ impl DocState {
self.views = host.views;
self.view_history = host.view_history;
self.revision += 1;
// The editor's drawing shares the host's handles: a name given in it must never resolve
// to a host record (or the other way round) after the drawing comes back.
self.expire_names();
Ok(())
}
}
-1
View File
@@ -35,7 +35,6 @@ 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};
+2 -26
View File
@@ -151,7 +151,6 @@ impl Interactive for LeaderM {
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}),
EntityKind::MText(m) => Some(m.clone()),
_ => None,
@@ -248,25 +247,14 @@ struct Sizes {
text: f64,
above: bool,
text_style: String,
/// An annotative style: the annotation scale takes DIMSCALE's place, as for an annotative
/// dimension, so the sizes are unscaled and the text is annotative.
annotative: bool,
}
fn sizes(s: &Session) -> Sizes {
// The current style with the drawing's DIM* overrides (what SETVAR DIMTXT… sets).
let st = s.doc().ok().and_then(|d| d.dim_style(&style(s)).map(|st| st.with_overrides(&d.dim_overrides()))).unwrap_or_default();
let dimscale = s.doc().map_or(1.0, |d| d.header.f64("DIMSCALE", 1.0));
let k = if st.annotative { 1.0 } else { st.effective_scale(dimscale) };
let k = if st.scale > 0.0 { st.scale } else { 1.0 };
let text_style = if st.text_style.is_empty() { "Standard".to_string() } else { st.text_style.clone() };
Sizes {
arrow: st.arrow_size * k,
gap: st.text_gap.abs() * k,
text: st.text_height * k,
above: st.text_above != 0,
text_style,
annotative: st.annotative,
}
Sizes { arrow: st.arrow_size * k, gap: st.text_gap.abs() * k, text: st.text_height * k, above: st.text_above != 0, text_style }
}
/// LEADER's JSON form: a straight leader with an arrow through `pts`, and `text` (lines split at
@@ -305,9 +293,6 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
arrow,
spline,
style: style(s),
// The drawing's DIM* overrides, as a new dimension takes them: the arrowhead is then drawn
// with the DIMASZ the hook line above was sized from, and they are saved with the leader.
overrides: s.doc().map(|d| d.dim_overrides()).unwrap_or_default(),
}))?;
let annotation = match ann {
Annotation::Text(lines) => {
@@ -328,7 +313,6 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}))?)
}
Annotation::Quick { lines, width } => {
@@ -346,7 +330,6 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}))?)
}
Annotation::Copy(m) => {
@@ -365,12 +348,5 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
}
Annotation::None => None,
};
if let (true, Some(t)) = (z.annotative, annotation)
&& matches!(s.doc()?.entity(t).map(|e| &e.kind), Some(EntityKind::MText(_)))
{
let d = s.doc_mut()?;
let cur = d.current_anno_scale();
d.modify_entity(t, |e| cadcraft_doc::set_annotative(e, true, &cur))?;
}
Ok(std::iter::once(leader).chain(annotation).collect())
}
@@ -31,7 +31,6 @@ fn mleader_kind(s: &Session, pts: &[Vec2], text: &str, landing: bool) -> Option<
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}),
style: st.name.clone(),
arrow_size: st.arrow_size,
-25
View File
@@ -480,31 +480,6 @@ fn table_create_edit_merge() {
assert!(dl.prims.len() > 10);
}
#[test]
fn covered_text_survives_save_and_unmerge() {
let text = "CoveredText".repeat(30);
let table = cadcraft_doc::Table {
col_widths: vec![2.0, 2.0],
row_heights: vec![0.5],
cells: vec![vec![
cadcraft_doc::TableCell { text: "Title".into(), merged: Some((1, 2)), ..Default::default() },
cadcraft_doc::TableCell { text: text.clone(), ..Default::default() },
]],
..Default::default()
};
let mut drawing = cadcraft_doc::Drawing::new_imperial();
drawing.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Table(table)).unwrap();
let bytes = cadcraft_io::write(&drawing, "table.dxf").unwrap();
let drawing = cadcraft_io::read(&bytes, "table.dxf").unwrap();
let handle = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Table(_))).unwrap().handle;
let mut session = Session::new();
session.open_drawing(drawing, "table.dxf", None);
session.execute("table.unmerge", &json!({ "handle": handle.hex(), "row": 0, "col": 1 })).unwrap();
let EntityKind::Table(table) = &session.doc().unwrap().entity(handle).unwrap().kind else { panic!("expected table") };
assert_eq!(table.cells[0][0].merged, None);
assert_eq!(table.cells[0][1].text, text);
}
#[test]
fn table_interactive() {
let mut s = Session::new();
+2 -4
View File
@@ -117,10 +117,8 @@ fn run_recover(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.state_mut()?;
let report = crate::audit::fix(Arc::make_mut(&mut st.doc));
if report.issues.is_empty() {
// Nothing to fix: the drawing opens unchanged, like OPEN. `fix` may already
// have copied it, so put the saved one back; no record name exists yet.
let saved = st.saved.clone();
st.restore_drawing(saved);
// Nothing to fix: the drawing opens unchanged, like OPEN.
st.doc = st.saved.clone();
}
if copy && !st.is_dirty() {
// An unsaved copy (Drawing Recovery): closing it asks to save it under a name.
+11 -16
View File
@@ -18,7 +18,7 @@ use super::has_doc;
use crate::{Accept, AttribAsk, AttribEntry, EngineError, Input, Interactive, Origin, Prompt, Result, Session, Step};
mod attdef;
pub(crate) mod attedit;
mod attedit;
mod burst;
mod description;
mod dyngrip;
@@ -457,20 +457,17 @@ fn current_text_style(s: &Session) -> String {
s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into())
}
/// A text style's name as the table spells it, with the width factor, the oblique angle and the
/// Backwards and Upside down effects an attribute definition takes from it (the renderer uses the
/// entity's own values).
type StyleValues = (String, f64, f64, (bool, bool));
/// The [`StyleValues`] of the style named `name`. `None` when the drawing has no such style.
fn style_values(s: &Session, name: &str) -> Result<Option<StyleValues>> {
Ok(s.doc()?.text_style(name).map(|t| (t.name.clone(), t.width_factor, t.oblique, (t.backwards, t.upside_down))))
/// A text style's name as the table spells it, with the width factor and oblique angle an
/// attribute definition takes from it (the renderer uses the entity's own values). `None` when
/// the drawing has no such style.
fn style_values(s: &Session, name: &str) -> Result<Option<(String, f64, f64)>> {
Ok(s.doc()?.text_style(name).map(|t| (t.name.clone(), t.width_factor, t.oblique)))
}
/// The current text style (TEXTSTYLE) with its width factor and oblique angle.
fn current_style_values(s: &Session) -> StyleValues {
fn current_style_values(s: &Session) -> (String, f64, f64) {
let name = current_text_style(s);
style_values(s, &name).ok().flatten().unwrap_or((name, 1.0, 0.0, (false, false)))
style_values(s, &name).ok().flatten().unwrap_or((name, 1.0, 0.0))
}
/// A justification code as `-ATTDEF` takes it, typed or in `justify`. Align and Fit run between
@@ -485,7 +482,7 @@ fn attdef_justify(code: &str) -> Result<(HAlign, VAlign)> {
/// The named text style with its width factor and oblique angle, or the error both the JSON form
/// and the typed `Style` option give for a style the drawing doesn't have.
fn resolve_style(s: &Session, name: &str) -> Result<StyleValues> {
fn resolve_style(s: &Session, name: &str) -> Result<(String, f64, f64)> {
style_values(s, name)?.ok_or_else(|| bad("attdef", format!("no text style \"{name}\"")))
}
@@ -510,10 +507,10 @@ fn attdef_kind(
height: f64,
invisible: bool,
j: (HAlign, VAlign),
style: StyleValues,
style: (String, f64, f64),
) -> EntityKind {
let (halign, valign) = j;
let (style, width_factor, oblique, (backwards, upside_down)) = style;
let (style, width_factor, oblique) = style;
let left = halign == HAlign::Left && valign == VAlign::Baseline;
EntityKind::AttDef(Attrib {
tag: tag.to_ascii_uppercase(),
@@ -528,8 +525,6 @@ fn attdef_kind(
style,
halign,
valign,
backwards,
upside_down,
},
invisible,
constant: false,
+1 -3
View File
@@ -103,7 +103,7 @@ impl AttdefM {
fn finish(&mut self, s: &mut Session, rotation: f64) -> Result<Step> {
let (h, v) = self.justify;
let left = h == HAlign::Left && v == VAlign::Baseline;
let (style, width_factor, oblique, (backwards, upside_down)) = super::resolve_style(s, &self.style)?;
let (style, width_factor, oblique) = super::resolve_style(s, &self.style)?;
s.add_entity(EntityKind::AttDef(Attrib {
tag: self.tag.to_uppercase(),
text: Text {
@@ -117,8 +117,6 @@ impl AttdefM {
style,
halign: h,
valign: v,
backwards,
upside_down,
},
invisible: self.flags & INVISIBLE != 0,
constant: self.flags & CONSTANT != 0,
+8 -105
View File
@@ -3,7 +3,7 @@
//! time or by replacing a string in all of them. Attribute tags match in any case, as in AutoCAD.
use cadcraft_doc::color::Color;
use cadcraft_doc::{Attrib, AttribProps, Common, EntityKind, HAlign, Handle, Text, VAlign};
use cadcraft_doc::{AttribProps, Common, EntityKind, HAlign, Handle, Text, VAlign};
use cadcraft_geom::Vec3;
use serde_json::{Map, Value, json};
@@ -20,7 +20,7 @@ pub(super) fn attedit_spec() -> CommandSpec {
CommandSpec::new("attedit", "Single...", run)
.menu(&["Modify", "Object", "Attribute", "Single..."])
.alias(&["ate", "eattedit"])
.params("{handle, values?: {TAG: value} (tags in any case; every attribute with the tag), at?: {index: value} (one attribute, by its place in the reference, for repeated tags); constant attributes are left alone} → {changed, unknownTags?, constantTags?}")
.params("{handle, values: {TAG: value} (tags in any case)} → {changed, unknownTags?}")
.interactive(|_| Ok(Box::new(AtteditM::default())))
}
@@ -35,11 +35,7 @@ pub(super) fn dash_attedit_spec() -> CommandSpec {
/// The value `values` gives for `tag`, matching the tag in any case. Numbers and booleans count
/// as their text.
pub(super) fn value_for(values: &Map<String, Value>, tag: &str) -> Option<String> {
text_of(values.get(tag).or_else(|| values.iter().find(|(k, _)| k.eq_ignore_ascii_case(tag)).map(|(_, v)| v))?)
}
/// A value given for an attribute as its text (numbers and booleans count as their text).
fn text_of(v: &Value) -> Option<String> {
let v = values.get(tag).or_else(|| values.iter().find(|(k, _)| k.eq_ignore_ascii_case(tag)).map(|(_, v)| v))?;
match v {
Value::String(t) => Some(t.clone()),
Value::Number(n) => Some(n.to_string()),
@@ -67,103 +63,18 @@ pub(super) fn with_unknown_tags(s: &Session, h: Handle, values: &Map<String, Val
fn run(s: &mut Session, p: &Value) -> Result<Value> {
let h = targets(s, p)?.first().copied().ok_or_else(|| bad("attedit", "`handle` is required"))?;
let vals = p.get("values").and_then(Value::as_object).cloned().unwrap_or_default();
let Some(EntityKind::Insert(ins)) = s.doc()?.entity(h).map(|e| &e.kind) else {
return Err(bad("attedit", format!("{} is not a block reference", h.hex())));
};
if super::super::curves::is_locked(s, h) {
return Err(bad("attedit", "the reference is on a locked layer"));
}
// Values by place (`at`): one attribute each, where a tag repeats (a DXF reference may carry
// two attributes with one tag; `values` changes both).
let mut at: Vec<(usize, String)> = Vec::new();
if let Some(m) = p.get("at").filter(|v| !v.is_null()) {
let m = m.as_object().ok_or_else(|| bad("attedit", "`at` must be an object of {index: value}"))?;
for (k, v) in m {
let i = k
.trim()
.parse::<usize>()
.ok()
.filter(|i| *i < ins.attribs.len())
.ok_or_else(|| bad("attedit", format!("`at`: {k} is not the index of one of the reference's attributes")))?;
at.push((i, text_of(v).ok_or_else(|| bad("attedit", format!("`at`: the value for {k} must be text")))?));
}
}
let given = |i: usize, tag: &str| at.iter().find(|(j, _)| *j == i).map(|(_, v)| v.clone()).or_else(|| value_for(&vals, tag));
// Constant attributes keep their definition's value.
let constant: Vec<String> =
ins.attribs.iter().enumerate().filter(|(i, a)| a.constant && given(*i, &a.tag).is_some()).map(|(_, a)| a.tag.clone()).collect();
if let Some((_, a)) = ins.attribs.iter().enumerate().find(|(i, a)| given(*i, &a.tag).is_some_and(|v| v.len() > MAX_VALUE)) {
return Err(bad("attedit", format!("the value for {} is longer than {MAX_VALUE} bytes", a.tag)));
}
let mut n = 0;
s.doc_mut()?.modify_entity(h, |e| {
if let EntityKind::Insert(i) = &mut e.kind {
for (j, a) in i.attribs.iter_mut().enumerate().filter(|(_, a)| !a.constant) {
if let Some(v) = given(j, &a.tag) {
for a in &mut i.attribs {
if let Some(v) = value_for(&vals, &a.tag) {
set_value(&mut a.text, v);
n += 1;
}
}
}
})?;
let mut r = with_unknown_tags(s, h, &vals, json!({ "changed": n }));
if !constant.is_empty()
&& let Some(o) = r.as_object_mut()
{
o.insert("constantTags".into(), json!(constant));
}
Ok(r)
}
/// One attribute of a block reference, as the Properties palette and the Edit Attributes dialog
/// list it.
#[derive(Clone, Debug, PartialEq)]
pub struct AttributeRow {
pub tag: String,
/// The definition's prompt (the tag when it has none).
pub prompt: String,
pub value: String,
/// Where the attribute's text is inserted: two attributes can share a tag and a value, and a
/// reorder of the block's definitions moves them.
pub at: Vec3,
/// Not constant: the value can be changed.
pub editable: bool,
pub invisible: bool,
/// A multiline attribute: its value may hold line breaks.
pub multiline: bool,
/// The whole stored attribute this row was made from. The fields above are what a list shows;
/// this is what a pending edit is bound to, so a row is stale when any stored property differs
/// (text height, rotation, alignment point, justification, style, its own layer/colour/
/// linetype/lineweight overrides, its modes, …) and not only when the shown ones do.
pub record: Attrib,
}
/// The attributes of block reference `h`, in order (empty for other objects). The prompt comes
/// from the attribute, else from its definition in the reference's block.
pub fn attributes(d: &cadcraft_doc::Drawing, h: Handle) -> Vec<AttributeRow> {
let Some(EntityKind::Insert(ins)) = d.entity(h).map(|e| &e.kind) else { return Vec::new() };
let block = d.block(&ins.block);
let def_prompt = |tag: &str| {
block.and_then(|b| {
b.entities.iter().find_map(|e| match &e.kind {
EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(tag) && !ad.prompt.is_empty() => Some(ad.prompt.clone()),
_ => None,
})
})
};
ins.attribs
.iter()
.map(|a| AttributeRow {
tag: a.tag.clone(),
prompt: if a.prompt.is_empty() { def_prompt(&a.tag).unwrap_or_else(|| a.tag.clone()) } else { a.prompt.clone() },
value: a.text.value.clone(),
at: a.text.insert,
editable: !a.constant,
invisible: a.invisible,
multiline: a.multiline.is_some(),
record: a.clone(),
})
.collect()
Ok(with_unknown_tags(s, h, &vals, json!({ "changed": n })))
}
/// A block name, tag or value specification: comma-separated wildcard patterns, any case. For
@@ -309,7 +220,7 @@ fn modify_attrib(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut c
}
/// The layer and colour attribute `k` of block reference `h` is drawn with: its own, else its
/// definition's (layer 0 from the definition is the reference's layer).
/// definition's (layer 0 is the reference's layer).
fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color)> {
let d = s.doc().ok()?;
let e = d.entity(h)?;
@@ -319,7 +230,7 @@ fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color)
.block(&ins.block)
.and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag))));
let c = a.props.over(&def.map(|de| de.common.clone()).unwrap_or_else(Common::default));
let layer = if a.props.layer.is_none() && c.layer == "0" { e.common.layer.clone() } else { c.layer };
let layer = if c.layer == "0" { e.common.layer.clone() } else { c.layer };
Some((layer, c.color))
}
@@ -416,14 +327,6 @@ impl Interactive for AtteditM {
fn name(&self) -> &'static str {
"ATTEDIT"
}
/// A selected block reference is taken at once (Edit Attributes from the shortcut menu).
fn begin(&mut self, s: &mut Session) -> Result<Step> {
let pre = s.selection();
if s.settings.pickfirst && !pre.is_empty() && self.pick(s, &pre).is_ok() {
s.set_selection(Vec::new());
}
Ok(Step::Continue)
}
fn prompt(&self, _s: &Session) -> Prompt {
match self.attribs.get(self.values.len()) {
Some((_, tag, cur)) if self.block.is_some() => Prompt::new(format!("Enter value for {tag}"), Accept::TEXT).default(cur.clone()),
+1 -76
View File
@@ -104,17 +104,12 @@ pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec<Attrib>
let m = ins.transform(blk.base.xy());
// The reference's attributes by tag, gathered once for all the definitions (#1923).
let carried = ins.attribs_by_tag();
#[cfg(test)]
let carried = carried.into_iter().map(|(tag, attrib)| (tests::MeasuredTag(tag), attrib)).collect::<std::collections::BTreeMap<_, _>>();
defs.iter()
.map(|ad| {
let mut k = EntityKind::Text(ad.text.clone());
k.transform(&m);
let mut t = if let EntityKind::Text(t) = k { t } else { ad.text.clone() };
let key = TagKey(&ad.tag);
#[cfg(test)]
let key = tests::MeasuredTag(key);
t.value = carried.get(&key).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
Attrib {
tag: ad.tag.clone(),
text: t,
@@ -209,8 +204,6 @@ pub(super) fn sync(s: &mut Session, name: &str) -> Result<(String, usize)> {
let defs = attdefs(&blk);
let d = s.doc_mut()?;
let n = update_references(d, &blk.name, |ins| ins.attribs = synced(&blk, &defs, ins));
// The references have new ATTRIBs: names given to the old ones hold no longer (#1660).
s.state_mut()?.expire_names();
Ok((blk.name.clone(), n))
}
@@ -366,74 +359,6 @@ impl Interactive for AttsyncM {
mod tests {
use super::*;
std::thread_local! {
static SYNC_CROSS_PROBES: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
}
/// Use the actual tag ordering and count only probes between different fixture sets.
pub(super) struct MeasuredTag<'a>(pub(super) TagKey<'a>);
impl MeasuredTag<'_> {
fn record(&self, other: &Self) {
let TagKey(left) = self.0;
let TagKey(right) = other.0;
let sides = (left.as_bytes().first(), right.as_bytes().first());
if matches!(sides, (Some(b'A'), Some(b'D')) | (Some(b'D'), Some(b'A'))) {
SYNC_CROSS_PROBES.with(|count| count.set(count.get().map(|n| n + 1)));
}
}
}
impl PartialEq for MeasuredTag<'_> {
fn eq(&self, other: &Self) -> bool {
self.record(other);
self.0 == other.0
}
}
impl Eq for MeasuredTag<'_> {}
impl PartialOrd for MeasuredTag<'_> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for MeasuredTag<'_> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.record(other);
self.0.cmp(&other.0)
}
}
#[test]
fn sync_uses_indexed_cross_set_tag_matching() {
const N: usize = 512;
let mut s = Session::new();
s.execute("attdef", &json!({"tag":"T", "default":"d", "at":[0, 1], "height":1.0})).unwrap();
s.execute("line", &json!({"points":[[0, 0], [10, 0]]})).unwrap();
let ids: Vec<_> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
s.execute("block", &json!({"name":"B", "base":[0, 0], "keep":"delete", "handles":ids})).unwrap();
let added = s.execute("insert", &json!({"name":"B", "at":[0, 0], "attribs":{"T":"v"}})).unwrap();
let handle = Handle::parse_hex(added["handle"].as_str().unwrap()).unwrap();
let doc = s.doc().unwrap();
let blk = doc.block("B").unwrap();
let base = (*attdefs(blk)[0]).clone();
let EntityKind::Insert(mut ins) = doc.entity(handle).unwrap().kind.clone() else { panic!("insert expected") };
let value = ins.attribs[0].clone();
let defs: Vec<_> = (0..N).map(|i| Attrib { tag: format!("D{i:05}"), ..base.clone() }).collect();
let defs: Vec<_> = defs.iter().collect();
ins.attribs = (0..N).map(|i| Attrib { tag: format!("A{i:05}"), ..value.clone() }).collect();
SYNC_CROSS_PROBES.with(|count| count.set(Some(0)));
let result = synced(blk, &defs, &ins);
let probes = SYNC_CROSS_PROBES.with(|count| count.replace(None).unwrap());
assert_eq!(result.len(), N);
assert!(result.iter().all(|a| a.text.value == "d"));
// No cross-set comparisons means this lookup was bypassed, whereas a scan does N*N.
assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {probes}");
}
#[test]
fn attdisp_keywords_map_to_attmode() {
assert_eq!([attmode("Normal"), attmode("on"), attmode("OFF"), attmode("x")], [Some(1), Some(2), Some(0), None]);
+1 -4
View File
@@ -6,7 +6,7 @@ use cadcraft_doc::{Drawing, Entity, EntityKind};
use serde_json::{Value, json};
use super::attribs::{attdefs, synced, update_reference_entities};
use super::purge::{leader_override_arrows, override_arrows, used_blocks};
use super::purge::{override_arrows, used_blocks};
use super::references_block;
use crate::cmd::curves::KW;
use crate::cmd::machines::{SelOutcome, SelectPhase};
@@ -81,8 +81,6 @@ fn replace(s: &mut Session, old: &str, new: &str, purge: bool) -> Result<(usize,
});
let key = d.blocks.keys().find(|k| k.eq_ignore_ascii_case(&old)).cloned();
let purged = purge && !referenced(d, &old) && key.is_some_and(|k| d.blocks.remove(&k).is_some());
// Replaced references have new ATTRIBs: names given to the old ones hold no longer (#1660).
s.state_mut()?.expire_names();
Ok((n, purged))
}
@@ -96,7 +94,6 @@ fn referenced(d: &Drawing, name: &str) -> bool {
match &e.kind {
EntityKind::Insert(i) => vec![i.block.clone()],
EntityKind::Dimension(dm) => dm.block.iter().cloned().chain(override_arrows(dm)).collect(),
EntityKind::Leader(l) => leader_override_arrows(l).collect(),
EntityKind::MLeader(m) => m.block.iter().map(|b| b.block.clone()).collect(),
_ => Vec::new(),
}
+3 -3
View File
@@ -41,13 +41,13 @@ fn burst_pieces(d: &Drawing, e: &Entity) -> Option<Vec<Entity>> {
}
/// The properties an attribute is drawn with: its own, else those of its definition `def`; layer
/// 0 from the definition is the reference's layer (an attribute set on layer 0 itself stays there)
/// and ByBlock colour the reference's colour, as EXPLODE gives the block's objects.
/// 0 is the reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the
/// block's objects.
fn attrib_common(e: &Entity, def: Option<&Entity>, props: &cadcraft_doc::AttribProps) -> Common {
// An attribute without a definition follows the reference.
let base = def.map(|de| de.common.clone()).unwrap_or_else(|| Common { color: Color::ByBlock, ..Common::default() });
let mut c = props.over(&base);
if props.layer.is_none() && c.layer == "0" {
if c.layer == "0" {
c.layer.clone_from(&e.common.layer);
}
if c.color == Color::ByBlock {
+1 -12
View File
@@ -115,13 +115,7 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
let defs = b.attdefs_by_tag();
out.extend(ins.attribs.iter().filter(|a| !a.invisible).map(|a| {
let def = defs.get(&TagKey(&a.tag)).map(|e| &e.common);
let own = a.props.over(def.unwrap_or(&by_block));
let mut common = under(&own, r);
// An attribute set on layer 0 itself stays there; only layer 0 from its definition is
// the reference's layer.
if a.props.layer.is_some() {
common.layer.clone_from(&own.layer);
}
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
None => EntityKind::Text(a.text.clone()),
@@ -230,9 +224,6 @@ impl Session {
/// UI's click on a dynamic grip). A list grip (visibility, lookup) or a flip grip has no
/// drag: the UI offers the choices, or flips, with `blocks.reference.set`.
pub fn start_dyn_grip(&mut self, handle: Handle, node: i32, part: GripPart) -> Result<()> {
// The value of an expression the frames are working out answers its prompt before the
// command it was typed in is cancelled for the grip.
self.lisp_settle_answer();
if self.running.is_some() {
self.cancel();
}
@@ -283,8 +274,6 @@ mod tests {
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
backwards: false,
upside_down: false,
},
invisible: false,
constant: false,
+17 -28
View File
@@ -14,7 +14,7 @@ use serde_json::{Value, json};
use super::super::file::io;
use super::super::modify::explode_kind;
use super::purge::{Kind, candidates, is_arrow_override, leader_override_arrows, override_arrows, override_name, scan_reads_everything};
use super::purge::{Kind, candidates, is_arrow_override, override_arrows, override_name, scan_reads_everything};
use super::{referenced_block, references_block, valid_block_name};
use crate::cmd::{bad, str_param};
use crate::{EngineError, Result, Session};
@@ -30,10 +30,9 @@ pub(super) struct FileRef {
}
impl FileRef {
/// Whether to ask before redefining: a plain path whose block already exists. EXPERT 2 or
/// more answers Yes without asking.
/// Whether to ask before redefining: a plain path whose block already exists.
pub fn ask_redefine(&self, s: &Session) -> bool {
!self.explicit && s.doc().is_ok_and(|d| d.block(&self.name).is_some() && d.header.i64("EXPERT", 0) < 2)
!self.explicit && s.doc().is_ok_and(|d| d.block(&self.name).is_some())
}
/// Read the file and (re)define its block. Returns the block's name.
@@ -200,10 +199,8 @@ fn reachable(d: &Drawing, roots: Vec<String>) -> BTreeSet<String> {
let Some(b) = d.block(&n) else { continue };
for e in b.entities.iter() {
todo.extend(referenced_block(e));
match &e.kind {
EntityKind::Dimension(dm) => todo.extend(override_arrows(dm)),
EntityKind::Leader(l) => todo.extend(leader_override_arrows(l)),
_ => {}
if let EntityKind::Dimension(dm) = &e.kind {
todo.extend(override_arrows(dm));
}
}
}
@@ -216,10 +213,8 @@ fn needed_blocks(src: &Drawing) -> BTreeSet<String> {
let mut roots: Vec<String> = Vec::new();
for e in src.model.iter() {
roots.extend(referenced_block(e));
match &e.kind {
EntityKind::Dimension(dm) => roots.extend(override_arrows(dm)),
EntityKind::Leader(l) => roots.extend(leader_override_arrows(l)),
_ => {}
if let EntityKind::Dimension(dm) = &e.kind {
roots.extend(override_arrows(dm));
}
}
for st in &src.dim_styles {
@@ -323,20 +318,6 @@ fn rename_style_arrows(d: &mut Drawing, own: &BTreeSet<String>, renames: &Rename
}
}
/// Point the arrowhead blocks a dimension's or a leader's `overrides` name at their renamed
/// blocks. Only a block that was renamed changes the value: a number naming a block that kept
/// its name stays as it was given.
fn rename_override_arrows(overrides: &mut serde_json::Map<String, Value>, renames: &Renames) {
for (key, value) in overrides.iter_mut() {
if is_arrow_override(key)
&& let Some(b) = override_name(value)
&& let Some(n) = renames.get(&b).filter(|n| **n != b)
{
*value = json!(n);
}
}
}
/// A copy of a source entity for this drawing: a fresh handle, block references renamed, and
/// links to other source objects (associative dimension points) dropped.
fn adopt(d: &mut Drawing, src: &Drawing, e: &Entity, renames: &Renames) -> Entity {
@@ -364,9 +345,17 @@ fn adopt(d: &mut Drawing, src: &Drawing, e: &Entity, renames: &Renames) -> Entit
if let Some(n) = dm.block.as_ref().and_then(|b| renames.get(b)) {
dm.block = Some(n.clone());
}
rename_override_arrows(&mut dm.overrides, renames);
for (key, value) in dm.overrides.iter_mut() {
// Only a block that was renamed changes the value: a number naming a block that
// kept its name stays as it was given.
if is_arrow_override(key)
&& let Some(b) = override_name(value)
&& let Some(n) = renames.get(&b).filter(|n| **n != b)
{
*value = json!(n);
}
}
}
EntityKind::Leader(l) => rename_override_arrows(&mut l.overrides, renames),
EntityKind::MLeader(m) => {
if let Some(b) = &mut m.block
&& let Some(n) = renames.get(&b.block)
+4 -22
View File
@@ -147,22 +147,11 @@ pub(in crate::cmd) fn override_name(v: &Value) -> Option<String> {
/// The arrowhead block names a dimension's overrides set.
pub(in crate::cmd) fn override_arrows(dm: &cadcraft_doc::Dimension) -> impl Iterator<Item = String> + '_ {
arrows_in(&dm.overrides)
}
/// The arrowhead block names a leader's overrides set (its DIMLDRBLK), as [`override_arrows`]
/// gives a dimension's.
pub(in crate::cmd) fn leader_override_arrows(l: &cadcraft_doc::Leader) -> impl Iterator<Item = String> + '_ {
arrows_in(&l.overrides)
}
/// The arrowhead block names a set of dimension style overrides names.
fn arrows_in(overrides: &serde_json::Map<String, Value>) -> impl Iterator<Item = String> + '_ {
overrides.iter().filter(|(k, _)| is_arrow_override(k)).filter_map(|(_, v)| override_name(v)).filter(|n| !n.is_empty())
dm.overrides.iter().filter(|(k, _)| is_arrow_override(k)).filter_map(|(_, v)| override_name(v)).filter(|n| !n.is_empty())
}
/// Upper-case names of blocks reachable from model space, the layouts and dimensions, and the
/// arrowhead blocks dimension styles and dimension or leader overrides name.
/// arrowhead blocks dimension styles and dimension overrides name.
pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
let mut used = HashSet::new();
let mut frontier: Vec<String> = Vec::new();
@@ -181,7 +170,6 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
frontier.extend(dm.block.clone());
frontier.extend(override_arrows(dm));
}
EntityKind::Leader(l) => frontier.extend(leader_override_arrows(l)),
EntityKind::MLeader(m) => frontier.extend(m.block.as_ref().map(|b| b.block.clone())),
// A dimension kept as read draws, and is saved with, the block it names (#3438).
EntityKind::Unknown(u) => frontier.extend(u.dimension_block().map(str::to_string)),
@@ -201,7 +189,6 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
frontier.extend(dm.block.clone());
frontier.extend(override_arrows(dm));
}
EntityKind::Leader(l) => frontier.extend(leader_override_arrows(l)),
EntityKind::MLeader(m) => frontier.extend(m.block.as_ref().map(|b| b.block.clone())),
EntityKind::Unknown(u) => frontier.extend(u.dimension_block().map(str::to_string)),
_ => {}
@@ -233,19 +220,14 @@ fn linetypes_inside(e: &cadcraft_doc::Entity) -> Vec<String> {
out
}
/// The linetypes named by objects, layers, dimension styles and multiline styles, and the ones
/// proxy graphics draw with (as for layers: saving names them by their index in the table).
/// The linetypes named by objects, layers, dimension styles and multiline styles.
fn linetypes_in_use(d: &Drawing) -> impl Iterator<Item = String> + '_ {
let objects = entities(d).map(|e| e.common.linetype.clone());
let graphics = entities(d).flat_map(|e| match &e.kind {
EntityKind::Unknown(u) => u.graphics.iter().map(|g| g.common.linetype.clone()).collect(),
_ => Vec::new(),
});
let inside = entities(d).flat_map(|e| linetypes_inside(e));
let layers = d.layers.iter().map(|l| l.linetype.clone());
let dims = d.dim_styles.iter().flat_map(|t| [t.dim_linetype.clone(), t.ext_linetype1.clone(), t.ext_linetype2.clone()]);
let mlines = d.mline_styles.iter().flat_map(|t| t.elements.iter().map(|e| e.linetype.clone()));
objects.chain(graphics).chain(inside).chain(layers).chain(dims).chain(mlines)
objects.chain(inside).chain(layers).chain(dims).chain(mlines)
}
/// Names of the unused objects of a named kind, in table order. This is PURGE's scan; `USAGE`
File diff suppressed because it is too large Load Diff
+11 -69
View File
@@ -134,7 +134,7 @@ struct Ctx {
}
/// The folder of the host drawing at `host` (a file path).
pub(crate) fn folder(host: Option<&Path>) -> Option<PathBuf> {
fn folder(host: Option<&Path>) -> Option<PathBuf> {
let p = host?.parent()?;
Some(if p.as_os_str().is_empty() { PathBuf::from(".") } else { p.to_path_buf() })
}
@@ -293,17 +293,8 @@ fn case_insensitive(p: &Path) -> Result<Option<PathBuf>, ()> {
Ok(out.is_file().then_some(out))
}
/// The first bytes of a file [`read`] keeps with the drawing (enough for a DWG's version and the
/// binary DXF sentinel).
const HEAD_BYTES: usize = 4096;
/// Read a drawing file through the host's io hooks, counting its bytes against the load's total.
/// Also returns the [`Stamp`] of the bytes read: taken from the opened file, so it describes them
/// even when the path is pointed at another file meanwhile; `None` when the file changed while it
/// was read (or the system can't tell its time), so an edit in place refuses until it is reloaded.
/// And the first [`HEAD_BYTES`] of those bytes, so what is told from them (a DWG's version, a
/// binary DXF) describes the same read.
fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>), String> {
fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
let hooks = super::super::super::file::io().ok_or("file formats are not available in this build")?;
#[cfg(not(target_arch = "wasm32"))]
{
@@ -312,9 +303,7 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>),
let left = MAX_XREF_TOTAL_BYTES.saturating_sub(cx.bytes);
let limit = MAX_XREF_BYTES.min(left);
let mut f = std::fs::File::open(file).map_err(|e| e.to_string())?;
let meta = f.metadata().map_err(|e| e.to_string())?;
let len = meta.len();
let before = stamp_of(&meta);
let len = f.metadata().map_err(|e| e.to_string())?.len();
let too_big = || {
if limit < MAX_XREF_BYTES {
format!("the referenced files are larger than {} MB together", MAX_XREF_TOTAL_BYTES >> 20)
@@ -332,10 +321,7 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>),
return Err(too_big());
}
cx.bytes = cx.bytes.saturating_add(n);
let after = f.metadata().ok().as_ref().and_then(stamp_of);
let read_as = before.filter(|b| Some(*b) == after);
let head = bytes.get(..HEAD_BYTES).unwrap_or(&bytes).to_vec();
Ok(((hooks.read)(&bytes, &file.to_string_lossy())?, read_as, head))
(hooks.read)(&bytes, &file.to_string_lossy())
}
#[cfg(target_arch = "wasm32")]
{
@@ -344,33 +330,6 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>),
}
}
/// A file's size and modification time: how an edit in place (REFEDIT) tells whether an xref's
/// file changed since it was read ([`cadcraft_doc::Block::xref_stamp`]). The time is kept as the
/// system gives it: counted from 1970, a file dated before then would have none and always look
/// changed.
pub(crate) type Stamp = (u64, std::time::SystemTime);
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
fn stamp_of(m: &std::fs::Metadata) -> Option<Stamp> {
Some((m.len(), m.modified().ok()?))
}
/// The [`Stamp`] of the file at `file` now.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn stamp(file: &Path) -> Option<Stamp> {
stamp_of(&std::fs::metadata(file).ok()?)
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn stamp(_file: &Path) -> Option<Stamp> {
None
}
/// Read the drawing file `file` (with the size limits of xref loading), with the [`Stamp`] and the
/// first bytes of the bytes read (see [`read`]).
pub(crate) fn read_file(file: &Path) -> Result<(Drawing, Option<Stamp>, Vec<u8>), String> {
read(file, &mut Ctx::new(None))
}
/// Load every xref of `d` that isn't unloaded from the paths saved in it; `host` is the drawing's
/// own path.
pub(crate) fn load_all(d: &mut Drawing, host: Option<&str>) -> Vec<Outcome> {
@@ -434,14 +393,8 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: &
let Some(path) = b.xref_path.clone() else { return (XrefStatus::Unresolved, "not an xref".into()) };
clear(d, &key);
let (status, detail) = match fetch(&path, host, chosen, cx, depth) {
Ok((x, file, read_as)) => match import(d, &key, &x, cx) {
Ok(()) => {
// This drawing's own baseline: another drawing loading the file later doesn't move it.
if let Some(b) = d.blocks.get_mut(&key) {
Arc::make_mut(b).xref_stamp = read_as;
}
(XrefStatus::Loaded, file.to_string_lossy().into_owned())
}
Ok((x, file)) => match import(d, &key, &x, cx) {
Ok(()) => (XrefStatus::Loaded, file.to_string_lossy().into_owned()),
Err(e) => {
// Whatever made it in before the failure goes again. A fetch that failed imported
// nothing, so it doesn't pay for a second scan of the block table.
@@ -456,13 +409,7 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: &
}
/// Read the drawing referenced as `path` and load its own attached xrefs into it.
fn fetch(
path: &str,
host: Option<&Path>,
chosen: bool,
cx: &mut Ctx,
depth: usize,
) -> Result<(Drawing, PathBuf, Option<Stamp>), (XrefStatus, String)> {
fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usize) -> Result<(Drawing, PathBuf), (XrefStatus, String)> {
let unresolved = |m: &str| (XrefStatus::Unresolved, m.to_string());
if depth >= MAX_BLOCK_DEPTH {
return Err(unresolved("xrefs are nested too deeply"));
@@ -476,7 +423,7 @@ fn fetch(
return Err(unresolved("too many referenced files"));
}
cx.files += 1;
let (mut x, read_as, _) = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?;
let mut x = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?;
cx.chain.push(canon);
let nested: Vec<String> =
x.blocks.values().filter(|b| b.xref_path.is_some() && !b.xref_overlay && !b.name.contains('|')).map(|b| b.name.clone()).collect();
@@ -487,20 +434,15 @@ fn fetch(
}
}
cx.chain.pop();
Ok((x, file, read_as))
}
/// The objects loading drawing `x` as an xref counts against [`MAX_XREF_OBJECTS`]: its model
/// space and every block's.
pub(crate) fn object_count(x: &Drawing) -> usize {
x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len()))
Ok((x, file))
}
/// Bring referenced drawing `x` into xref `key`: its model space becomes the block's objects, its
/// symbols and blocks are added as `key|name` (dependent symbols the host already has keep the
/// host's settings, so layer changes survive a reload).
fn import(d: &mut Drawing, key: &str, x: &Drawing, cx: &mut Ctx) -> Result<(), String> {
cx.objects = cx.objects.saturating_add(object_count(x));
let count = x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len()));
cx.objects = cx.objects.saturating_add(count);
if cx.objects > MAX_XREF_OBJECTS {
return Err(format!("more than {MAX_XREF_OBJECTS} objects"));
}
+2 -14
View File
@@ -79,27 +79,17 @@ pub(crate) fn paste(s: &mut Session, m: &Mat3) -> Result<Vec<Handle>> {
let defs = s.clipboard_source.as_ref().map(|c| c.defs.clone());
let space = s.space();
let d = s.doc_mut()?;
let renames = defs.as_ref().map(|x| merge(d, x)).unwrap_or_default();
let renames = defs.map(|x| merge(d, &x)).unwrap_or_default();
let mut out = Vec::new();
let mut copies = Vec::new();
for e in &ents {
let old_h = e.handle;
let mut e = adopt(d, e, &renames);
e.kind.transform(m);
d.ensure_layer(&e.common.layer);
out.push(e.handle);
copies.push((old_h, e.handle));
if let Some(st) = d.space_mut(&space) {
st.push(e);
}
}
if let Some(c) = &defs
&& !c.groups.is_empty()
{
super::groups::replicate_groups_from(d, &c.groups, &copies);
} else {
super::groups::replicate_groups_for_copies(d, &copies);
}
s.set_selection(out.clone());
Ok(out)
}
@@ -280,10 +270,8 @@ fn defs_for(src: &Drawing, ents: &[Entity]) -> Drawing {
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name).into();
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name).into();
d.mleader_styles = pick(&src.mleader_styles, &used.mleader_styles, |t| &t.name);
d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name).into();
d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name);
d.blocks = src.blocks.iter().filter(|(k, _)| used.blocks.contains(&up(k))).map(|(k, b)| (k.clone(), b.clone())).collect();
let ent_handles: HashSet<Handle> = ents.iter().map(|e| e.handle).collect();
d.groups = src.groups.iter().filter(|g| !g.members.is_empty() && g.members.iter().all(|m| ent_handles.contains(m))).cloned().collect();
d.layouts.clear();
d
}
-6
View File
@@ -37,9 +37,6 @@ pub(crate) fn justify_prompt(two_points: bool) -> Prompt {
pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotation: f64, j: (HAlign, VAlign)) -> EntityKind {
let style = s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into());
// New text takes Backwards and Upside down from its style, as AutoCAD's does; later style
// changes don't change them.
let (backwards, upside_down) = s.doc().ok().and_then(|d| d.text_style(&style)).map_or((false, false), |t| (t.backwards, t.upside_down));
let (h, v) = j;
let left = h == HAlign::Left && v == VAlign::Baseline;
EntityKind::Text(Text {
@@ -53,8 +50,6 @@ pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotatio
style,
halign: h,
valign: v,
backwards,
upside_down,
})
}
@@ -97,7 +92,6 @@ pub(super) fn run_mtext(s: &mut Session, p: &Value) -> Result<Value> {
line_spacing: f64_or(p, "lineSpacing", 1.0),
line_spacing_exact: bool_or(p, "lineSpacingExact", false),
columns: crate::cmd::mtext_opts::json_columns(p, height, width)?,
background: None,
});
added(s.add_entity(k)?)
}
+1 -1
View File
@@ -273,7 +273,7 @@ impl Interactive for RectM2 {
let msg = if self.center { "Specify center point for rectangle" } else { "Specify first corner point" };
Prompt::new(msg, Accept::POINT).kw(&["Chamfer", "CEnter", "Elevation", "Fillet", "Thickness", "Width"])
}
Some(p) => Prompt::new("Specify other corner point", Accept::POINT).kw(&["Area", "Dimensions", "Rotation"]).corner(p).xy(),
Some(p) => Prompt::new("Specify other corner point", Accept::POINT).kw(&["Area", "Dimensions", "Rotation"]).corner(p),
}
}
/// Consumes one input: option keywords (`Center` only switches the first point's meaning
+1 -5
View File
@@ -26,10 +26,6 @@ fn default_max_arc_len(s: &Session, min: f64) -> f64 {
s.doc().ok().map_or(min, |d| d.header.f64("CADCRAFT_REVCLOUDMAXARCLEN", min)).max(min)
}
/// The bulge of every arc of a revision cloud (an arc of about 110°). Readers that check
/// `RevcloudProps` xdata and bulge accept a closed polyline whose bulges are within 0.02 of this.
const CLOUD_BULGE: f64 = 0.520567050552;
/// Bulged closed polyline vertices for a revision cloud around `boundary`.
pub(crate) fn cloud_vertices(boundary: &[Vec2], arc_len: f64, per_edge: bool, reverse: bool) -> Option<Vec<PolyVertex>> {
let mut pts: Vec<Vec2> = Vec::new();
@@ -73,7 +69,7 @@ pub(crate) fn cloud_vertices(boundary: &[Vec2], arc_len: f64, per_edge: bool, re
out.extend(chain.at_length_in(&ends, perim * j as f64 / k as f64).map(|x| x.0));
}
}
let b = if reverse { -CLOUD_BULGE } else { CLOUD_BULGE };
let b = if reverse { -0.5 } else { 0.5 };
Some(out.into_iter().map(|p| PolyVertex::with_bulge(p, b)).collect())
}
+17 -39
View File
@@ -63,11 +63,19 @@ enum Order {
Under,
}
fn reorder_store(st: &mut cadcraft_doc::EntityStore, hs: &[Handle], order: Order) -> usize {
/// Move `hs` in the current space's draw order, keeping their order among themselves. Above and
/// Under place them right over the topmost reference object or right under the lowest one.
/// Returns how many objects moved.
fn reorder(s: &mut Session, hs: &[Handle], order: Order, refs: &[Handle]) -> Result<usize> {
let space = s.space();
let d = s.doc_mut()?;
let Some(st) = d.space_mut(&space) else { return Ok(0) };
let index: HashMap<Handle, usize> = st.handles().into_iter().enumerate().map(|(i, h)| (h, i)).collect();
let mut moving: Vec<(usize, Handle)> = hs.iter().filter_map(|h| index.get(h).map(|i| (*i, *h))).collect();
moving.sort_unstable();
moving.dedup();
let set: HashSet<Handle> = moving.iter().map(|m| m.1).collect();
let refs: Vec<(usize, Handle)> = refs.iter().filter(|h| !set.contains(h)).filter_map(|h| index.get(h).map(|i| (*i, *h))).collect();
match order {
Order::Front => {
for (_, h) in &moving {
@@ -79,29 +87,6 @@ fn reorder_store(st: &mut cadcraft_doc::EntityStore, hs: &[Handle], order: Order
st.send_to_back(*h);
}
}
Order::Above | Order::Under => {}
}
moving.len()
}
/// Move `hs` in the current space's draw order, keeping their order among themselves. Above and
/// Under place them right over the topmost reference object or right under the lowest one.
/// Returns how many objects moved.
fn reorder(s: &mut Session, hs: &[Handle], order: Order, refs: &[Handle]) -> Result<usize> {
let space = s.space();
let d = s.doc_mut()?;
let Some(st) = d.space_mut(&space) else { return Ok(0) };
if matches!(order, Order::Front | Order::Back) {
return Ok(reorder_store(st, hs, order));
}
let index: HashMap<Handle, usize> = st.handles().into_iter().enumerate().map(|(i, h)| (h, i)).collect();
let mut moving: Vec<(usize, Handle)> = hs.iter().filter_map(|h| index.get(h).map(|i| (*i, *h))).collect();
moving.sort_unstable();
moving.dedup();
let set: HashSet<Handle> = moving.iter().map(|m| m.1).collect();
let refs: Vec<(usize, Handle)> = refs.iter().filter(|h| !set.contains(h)).filter_map(|h| index.get(h).map(|i| (*i, *h))).collect();
match order {
Order::Front | Order::Back => {}
Order::Above => {
let Some(&(_, mut cur)) = refs.iter().max() else { return Err(EngineError::Other("no reference objects".into())) };
for (_, h) in &moving {
@@ -196,23 +181,15 @@ impl Annot {
}
}
/// Reorder objects across all spaces (model space and all paper space layouts).
fn reorder_all_spaces(s: &mut Session, order: Order, keep: impl Fn(&EntityKind) -> bool) -> Result<usize> {
let d = s.doc_mut()?;
let mut total = 0;
// Model space
let hs: Vec<Handle> = d.model.iter().filter(|e| keep(&e.kind)).map(|e| e.handle).collect();
total += reorder_store(&mut d.model, &hs, order);
// All paper space layouts
for layout in &mut d.layouts {
let hs: Vec<Handle> = layout.entities.iter().filter(|e| keep(&e.kind)).map(|e| e.handle).collect();
total += reorder_store(&mut layout.entities, &hs, order);
}
Ok(total)
/// Every object of the current space that `keep` accepts, in draw order.
fn of_kind(s: &Session, keep: impl Fn(&EntityKind) -> bool) -> Result<Vec<Handle>> {
let d = s.doc()?;
Ok(d.space(&s.space()).map(|st| st.iter().filter(|e| keep(&e.kind)).map(|e| e.handle).collect()).unwrap_or_default())
}
fn annotations_to_front(s: &mut Session, which: Annot) -> Result<Value> {
let n = reorder_all_spaces(s, Order::Front, |k| which.matches(k))?;
let hs = of_kind(s, |k| which.matches(k))?;
let n = reorder(s, &hs, Order::Front, &[])?;
Ok(json!({ "moved": n, "message": format!("{n} object(s) brought to front.") }))
}
@@ -231,7 +208,8 @@ fn run_texttofront(s: &mut Session, p: &Value) -> Result<Value> {
}
fn run_hatchtoback(s: &mut Session, _p: &Value) -> Result<Value> {
let n = reorder_all_spaces(s, Order::Back, |k| matches!(k, EntityKind::Hatch(_)))?;
let hs = of_kind(s, |k| matches!(k, EntityKind::Hatch(_)))?;
let n = reorder(s, &hs, Order::Back, &[])?;
Ok(json!({ "moved": n, "message": format!("{n} hatch object(s) sent to back.") }))
}
-3
View File
@@ -73,10 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
/// A programmatic undo/redo (`engine.execute`, MCP, control channel, scripts) first ends a running
/// command the way Esc does, exactly as `Session::start` does for Cmd+Z, the menu or the command
/// line. Otherwise it would swap the drawing under the command and pop the previous command's step.
/// As there, the value of an expression the frames are working out answers its prompt first: the
/// command it ends is the step to take back.
fn end_running_command(s: &mut Session) {
s.lisp_settle_answer();
if s.running.is_some() {
s.cancel();
}
+5 -37
View File
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("export", "Export...", run_export)
.menu(&["File", "Export..."])
.alias(&["exp"])
.params("{path? (else returns base64 `data`), format?: dxf|dwg|svg|png|pdf (default: the path's extension), version?: 2000|2004|2007|2010|2013|2018 (DXF and DWG; default: the drawing's own), binary?: false (DXF only)} → {format, bytes, version? (DXF and DWG), path? | data, warnings?: what an image draws short of the drawing}")
.params("{path? (else returns base64 `data`), format?: dxf|dwg|svg|png|pdf (default: the path's extension)} → {format, bytes, path? | data}")
.noundo(),
CommandSpec::new("preview", "Plot Preview", run_preview)
.menu(&["File", "Plot Preview"])
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("pdfbook", "Sheet Books to PDF...", run_pdfbook)
.menu(&["File", "Sheet Books to PDF..."])
.alias(&["printpdf", "pdfb"])
.params("{path?: \"DIR/NAME^NAME2.pdf\" (default: the drawing's file; a `^` splits the name into one book name per row of frames; else returns base64 `data` per book), names?: [book names], frameHeight?: mm (default 297), unit?: mm per drawing unit (default 1)} → {books: [{name, pages, bytes, path? | data}], skipped}: closed polylines of the frame height in model space are sheet frames; each row (same lower edge, bottom to top) is one PDF, its frames left to right one page each on the paper (any standard size — ISO, JIS, ANSI — either orientation) they match")
.params("{path?: \"DIR/NAME^NAME2.pdf\" (default: the drawing's file; a `^` splits the name into one book name per row of frames; else returns base64 `data` per book), names?: [book names], frameHeight?: mm (default 297), unit?: mm per drawing unit (default 1)} → {books: [{name, pages, bytes, path? | data}], skipped}: closed polylines of the frame height in model space are sheet frames; each row (same lower edge, bottom to top) is one PDF, its frames left to right one page each on the paper (ISO A-series, either orientation) they match")
.noundo(),
CommandSpec::new("attach", "Attach", |s, p| match str_param(p, "path").map(extension) {
Some(e) if super::image::is_image_ext(&e) => super::image::run_imageattach(s, p),
@@ -123,23 +123,7 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("export", "`format` must be dxf, dwg, svg, png or pdf (or give a `path` with one of those extensions)"));
}
let file = format!("export.{format}");
// DXF and DWG take SAVEAS's version and binary options; the drawing keeps its own version and
// name (an export is not a save).
let opts = super::file::save_options("export", p)?;
let drawing_format = matches!(format.as_str(), "dxf" | "dwg");
if opts.version.is_some() && !drawing_format {
return Err(bad("export", "`version` applies to DXF and DWG files only"));
}
if opts.binary && format != "dxf" {
return Err(bad("export", "`binary` applies to DXF files only"));
}
let (bytes, notes) = if opts.version.is_some() || opts.binary {
let w =
super::file::write_as().ok_or_else(|| bad("export", "exporting at a chosen version or as binary DXF is not available in this build"))?;
(w(s.doc()?, &file, &opts).map_err(|e| bad("export", e))?, Vec::new())
} else {
super::file::write_noted(hooks, s.doc()?, &file).map_err(|e| bad("export", e))?
};
let bytes = (hooks.write)(s.doc()?, &file).map_err(|e| bad("export", e))?;
let folder = path.and_then(super::file::new_folder);
let mut r = match path {
Some(path) => {
@@ -148,12 +132,8 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
}
None => json!({ "data": base64_encode(&bytes), "format": format, "bytes": bytes.len() }),
};
if let (Some(v), Some(o)) = (opts.version, r.as_object_mut()) {
o.insert("version".into(), json!(v.year()));
}
super::file::report_new_folder(s, &mut r, folder);
super::file::report_loss(s, &mut r, &file, opts.version);
super::file::report_notes(s, &mut r, notes);
super::file::report_loss(s, &mut r, &file);
Ok(r)
}
@@ -592,8 +572,7 @@ struct Frame {
landscape: bool,
}
/// The standard paper (ISO, JIS or ANSI) a frame of `w` x `h` mm fits (either orientation), and whether
/// it is landscape.
/// The ISO/ANSI paper a frame of `w` x `h` mm fits (either orientation), and whether it is landscape.
fn paper_for(w: f64, h: f64) -> Option<(&'static str, bool)> {
cadcraft_render::PAPER_SIZES.iter().find_map(|p| {
let (pw, ph) = (p.width_mm, p.height_mm);
@@ -898,17 +877,6 @@ mod tests {
let r = s.execute("preview", &json!({ "layout": "layout1", "paper": "A4", "landscape": true, "width": 600 })).unwrap();
assert_eq!((r["layout"].as_str(), r["width"].as_u64(), r["height"].as_u64()), (Some("Layout1"), Some(600), Some(424)));
assert_eq!(r["paper"], "ISO A4 (210.00 x 297.00 MM)");
// The bare B5 is the ISO size it always was; the JIS sheet needs its explicit name, and the
// Japanese postcards resolve by their names and their Japanese spelling.
let r = s.execute("preview", &json!({ "layout": "layout1", "paper": "B5", "landscape": false, "width": 400 })).unwrap();
assert_eq!(r["paper"], "ISO B5 (176.00 x 250.00 MM)");
assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(400), Some(568)));
let r = s.execute("preview", &json!({ "layout": "layout1", "paper": "B5 (JIS)", "landscape": false, "width": 400 })).unwrap();
assert_eq!(r["paper"], "JIS B5 (182.00 x 257.00 MM)");
assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(400), Some(565)));
let r = s.execute("preview", &json!({ "layout": "layout1", "paper": "はがき", "landscape": false, "width": 200 })).unwrap();
assert_eq!(r["paper"], "Japanese Postcard (100.00 x 148.00 MM)");
assert_eq!(r["height"], 296);
assert!(s.execute("preview", &json!({ "layout": "Nope" })).is_err());
assert!(s.execute("preview", &json!({ "paper": "Nope" })).is_err());
for p in [json!({ "scale": -1, "fit": false }), json!({ "scale": 1e-300, "fit": false }), json!({ "width": -5 }), json!({ "width": 1e30 })] {
+26 -235
View File
@@ -49,47 +49,6 @@ pub fn io() -> Option<&'static IoHooks> {
IO.get()
}
/// [`IoHooks::write`] and [`IoHooks::plot`] that also return what an image (PNG, SVG, PDF) draws
/// short of the drawing because of a render limit, one note each, such as dashed lines drawn
/// continuous past the dash limit (installed by the app with the image writers, a lower layer;
/// see `cadcraft_io::write_framed_noted` and `cadcraft_io::plotter::plot_noted`). EXPORT, QSAVE
/// and SAVEAS to an image, `document.bytes` and PLOT (so PUBLISH and PDFBOOK, sheet by sheet)
/// report them; without the hooks they write through [`IoHooks`] with no such notes. The app
/// installs the same writers as its [`IoHooks`].
pub struct NotedIo {
pub write: fn(&Drawing, &str) -> std::result::Result<(Vec<u8>, Vec<String>), String>,
pub plot: fn(&Drawing, &cadcraft_doc::Space, &Value) -> std::result::Result<(Vec<u8>, Vec<String>), String>,
}
static NOTED_IO: OnceLock<NotedIo> = OnceLock::new();
pub fn set_noted_io(h: NotedIo) {
let _ = NOTED_IO.set(h);
}
/// `d` written as `name` with the image's notes ([`NotedIo::write`]), or through `hooks.write`
/// with none when the app installed no [`NotedIo`].
pub(crate) fn write_noted(hooks: &IoHooks, d: &Drawing, name: &str) -> std::result::Result<(Vec<u8>, Vec<String>), String> {
match NOTED_IO.get() {
Some(n) => (n.write)(d, name),
None => (hooks.write)(d, name).map(|bytes| (bytes, Vec::new())),
}
}
/// `d` plotted with the plot's notes ([`NotedIo::plot`]), or through `hook` with none when the
/// app installed no [`NotedIo`].
pub(crate) fn plot_noted(
hook: PlotHook,
d: &Drawing,
space: &cadcraft_doc::Space,
opts: &Value,
) -> std::result::Result<(Vec<u8>, Vec<String>), String> {
match NOTED_IO.get() {
Some(n) => (n.plot)(d, space, opts),
None => hook(d, space, opts).map(|bytes| (bytes, Vec::new())),
}
}
/// An entity as DXF groups and back, for AutoLISP's `entget`, `entmake` and `entmod`
/// (installed by the app with the DXF reader and writer, a lower layer).
pub struct EntityCodec {
@@ -108,47 +67,6 @@ pub fn entity_codec() -> Option<&'static EntityCodec> {
CODEC.get()
}
/// One record written after an entity's own, at `index` (an INSERT's ATTRIB, then its SEQEND):
/// its type name and the groups of its record, without its `0` group. AutoLISP's `entnext` and
/// `entget` reach an INSERT's attributes through it, one record at a time (the attributes have no
/// handle of their own in the drawing). Installed by the app with the DXF writer, a lower layer;
/// optional, so a host without one simply has no such records ([`EntityCodec`] is unchanged).
pub type EntitySubRecord = fn(&Drawing, &cadcraft_doc::Entity, usize) -> Option<(String, Vec<craft_dxf::Tag>)>;
static SUB_RECORD: OnceLock<EntitySubRecord> = OnceLock::new();
// This thread hid the optional provider ([`without_entity_sub_record`], tests only).
#[cfg(test)]
thread_local! {
static SUB_RECORD_HIDDEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub fn set_entity_sub_record(f: EntitySubRecord) {
let _ = SUB_RECORD.set(f);
}
pub fn entity_sub_record() -> Option<EntitySubRecord> {
#[cfg(test)]
if SUB_RECORD_HIDDEN.with(std::cell::Cell::get) {
return None;
}
SUB_RECORD.get().copied()
}
/// Run `f` as a host that did not install [`EntitySubRecord`]: `entnext` must walk the drawing's
/// entities as it did before the provider existed. Tests only.
#[cfg(test)]
pub(crate) fn without_entity_sub_record<R>(f: impl FnOnce() -> R) -> R {
struct Unhide;
impl Drop for Unhide {
fn drop(&mut self) {
SUB_RECORD_HIDDEN.with(|h| h.set(false));
}
}
SUB_RECORD_HIDDEN.with(|h| h.set(true));
let _unhide = Unhide;
f()
}
/// The drawing's non-graphic records as written (tables, BLOCK records, objects): each one's
/// type, groups after the type and role (see [`cadcraft_doc::foreign::ForeignKey`]). AutoLISP's
/// `namedobjdict`, `tblobjname` and `handent` of non-graphic objects read them (installed by the
@@ -205,11 +123,6 @@ pub fn dwg_notes(d: &Drawing) -> Vec<String> {
/// Say on the command line what the DWG just written keeps only in part (`notes`, from
/// [`dwg_notes`]), and list it in the result's `warnings`.
pub(crate) fn report_dwg_notes(s: &mut Session, r: &mut Value, notes: Vec<String>) {
report_notes(s, r, notes);
}
/// Say each of `notes` on the command line and add them to the result's `warnings`.
pub(crate) fn report_notes(s: &mut Session, r: &mut Value, notes: Vec<String>) {
if notes.is_empty() {
return;
}
@@ -217,12 +130,7 @@ pub(crate) fn report_notes(s: &mut Session, r: &mut Value, notes: Vec<String>) {
s.echo(note.clone());
}
if let Some(o) = r.as_object_mut() {
match o.get_mut("warnings").and_then(Value::as_array_mut) {
Some(list) => list.extend(notes.into_iter().map(Value::String)),
None => {
o.insert("warnings".into(), json!(notes));
}
}
o.insert("warnings".into(), json!(notes));
}
}
@@ -299,7 +207,7 @@ fn version_list() -> String {
/// The `version` and `binary` parameters of a save: a version is a year (2018 or "2018"), "R2018"
/// or an `$ACADVER` code ("AC1032").
pub(super) fn save_options(cmd: &str, p: &Value) -> Result<SaveAs> {
fn save_options(cmd: &str, p: &Value) -> Result<SaveAs> {
let version = match p.get("version") {
None | Some(Value::Null) => None,
Some(v) => {
@@ -330,10 +238,9 @@ fn is_dxf(path: &str) -> bool {
Format::from_path(path) == Some(Format::Dxf)
}
/// The drawing written to `path` with `opts`: an image, or a drawing file with no option set,
/// through [`IoHooks::write`] (with an image's notes, [`write_noted`]); a drawing file at a
/// chosen version or as binary DXF through the [`write_as`] hook.
fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(Vec<u8>, Vec<String>)> {
/// The drawing written to `path` with `opts`: through [`IoHooks::write`] when no option is set,
/// else through the [`write_as`] hook.
fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<Vec<u8>> {
let hooks = io().ok_or_else(|| bad(cmd, "file formats are not available in this build"))?;
if opts.binary && !is_dxf(path) {
return Err(bad(cmd, "binary applies to DXF files only"));
@@ -342,12 +249,11 @@ fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(Vec
let d: &cadcraft_doc::Drawing = if is_drawing_file(path) { s.state()?.drawing() } else { s.doc()? };
let copy = (opts.portable_fonts && is_drawing_file(path)).then(|| Drawing { portable_fonts: true, ..d.clone() });
let d = copy.as_ref().unwrap_or(d);
// An image has no version: `write_as` would write the same bytes without the notes.
let r = if !is_drawing_file(path) || (opts.version.is_none() && !opts.binary) {
write_noted(hooks, d, path)
let r = if opts.version.is_none() && !opts.binary {
(hooks.write)(d, path)
} else {
let w = write_as().ok_or_else(|| bad(cmd, "saving at a chosen version or as binary DXF is not available in this build"))?;
w(d, path, opts).map(|bytes| (bytes, Vec::new()))
w(d, path, opts)
};
r.map_err(|e| bad(cmd, e))
}
@@ -367,10 +273,6 @@ pub fn specs() -> Vec<CommandSpec> {
.params("{path} | {data: base64, name} → {index, entities?, warnings: what reading left out}")
.enabled(always)
.noundo(),
CommandSpec::new("whohas", "Who Has", run_whohas)
.params("{path?: a drawing file (default: the current drawing's)} → {path, holder: {user, host, instance, opened} | null}")
.enabled(always)
.noundo(),
CommandSpec::new("close", "Close", run_close).menu(&["File", "Close"]).key("Cmd+W").params("{index?}").noundo(),
CommandSpec::new("closeall", "Close All", run_closeall).menu(&["File", "Close All"]).enabled(always).noundo(),
CommandSpec::new("qsave", "Save", run_qsave_reporting).menu(&["File", "Save"]).key("Cmd+S").alias(&["save"]).params("{path?}").noundo(),
@@ -382,20 +284,8 @@ 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}")
.params("{format?: dxf, version?: 2000…2018, binary?: bool, portableFonts?: bool} → {data: base64}")
.noundo(),
CommandSpec::new("script", "Run Script...", run_script)
.menu(&["Tools", "Run Script..."])
@@ -609,36 +499,6 @@ fn run_open(s: &mut Session, p: &Value) -> Result<Value> {
Ok(opened(s, i, false))
}
/// WHOHAS: who has a drawing open, from its lock file ([`crate::drawlock`]): the current
/// drawing's, or the file `path`.
fn run_whohas(s: &mut Session, p: &Value) -> Result<Value> {
// Left out (or null): the current drawing's file; anything but text is an error, not the
// current drawing asked about by mistake.
let path = match p.get("path") {
None | Some(Value::Null) => s.state()?.path.clone().ok_or_else(|| bad("whohas", "the drawing has no file yet; pass `path`"))?,
Some(Value::String(path)) => path.clone(),
Some(_) => return Err(bad("whohas", "`path` must be a file path")),
};
// The web has no lock files to look at: an error, not "nobody has it open".
#[cfg(target_arch = "wasm32")]
{
let _ = path;
Err(bad("whohas", "drawing locks are not available on the web"))
}
#[cfg(not(target_arch = "wasm32"))]
{
// Under the automation roots, the lock beside a file outside them is not looked at.
crate::file_access::check_read(&path).map_err(|e| bad("whohas", e))?;
let holder = crate::drawlock::holder(std::path::Path::new(&path));
let msg = match &holder {
Some(h) => format!("{} is open by {}.", file_name(&path), h.describe()),
None => format!("Nobody has {} open (no current lock).", file_name(&path)),
};
s.echo(msg);
Ok(json!({ "path": path, "holder": holder }))
}
}
/// `close [index]`: cancel the running command, remove the drawing (default: active), keep the active index valid, and bump the document epoch; an unknown index is an error.
fn run_close(s: &mut Session, p: &Value) -> Result<Value> {
let i = p.get("index").and_then(Value::as_u64).map(|i| i as usize).unwrap_or(s.active);
@@ -669,27 +529,18 @@ fn run_closeall(s: &mut Session, _p: &Value) -> Result<Value> {
ok()
}
pub(crate) fn save_to(s: &mut Session, path: &str) -> Result<(usize, Vec<String>)> {
pub(crate) fn save_to(s: &mut Session, path: &str) -> Result<usize> {
let opts = SaveAs { binary: s.state()?.binary_dxf && is_dxf(path), ..SaveAs::default() };
save_as(s, "save", path, &opts)
}
/// Save to `path` with `opts`. A drawing file then keeps the version and binary choice: the
/// version goes into the drawing's `$ACADVER`, so later saves (QSAVE) write it again. Also an
/// image's notes ([`write_noted`]).
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(usize, Vec<String>)> {
/// version goes into the drawing's `$ACADVER`, so later saves (QSAVE) write it again.
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<usize> {
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 bytes = write_bytes(s, cmd, path, opts)?;
let n = commit_save(s, path, &bytes, store)?;
if is_drawing_file(path) {
let st = s.state_mut()?;
@@ -701,7 +552,7 @@ fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(usi
st.saved = st.drawing().clone();
}
}
Ok((n, notes))
Ok(n)
}
/// Put saved bytes where the user gets them: natively the file at `path`; on the web, which has
@@ -914,13 +765,12 @@ fn adopt_source_group(out: &std::fs::File, src: &std::fs::Metadata) -> std::io::
/// ([`crate::atomic_write::write_atomic_with`]). Nothing
/// to keep when there is no file yet. A file that doesn't look like a drawing
/// ([`looks_like_drawing`]) is not backed up, and the `.bak` already there is left alone.
/// Returns whether the backup was written. Also used for an xref REFEDIT writes back.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn backup(path: &std::path::Path) -> std::io::Result<bool> {
fn backup(path: &std::path::Path) -> std::io::Result<()> {
let mut src = match std::fs::File::open(path) {
Ok(f) if f.metadata()?.is_file() => f,
Ok(_) => return Ok(false),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Ok(_) => return Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(e) => return Err(e),
};
let (head, tail, len) = ends(&mut src)?;
@@ -929,7 +779,7 @@ pub(crate) fn backup(path: &std::path::Path) -> std::io::Result<bool> {
// the roots (or to another computer) isn't looked at.
if !backup_replaced(&head, &tail, len, std::fs::symlink_metadata(&bak).is_ok()) {
log::warn!("save: {} doesn't look like a whole drawing; its backup is left as it was", path.display());
return Ok(false);
return Ok(());
}
// The backup is no more readable than the drawing, nor than the .bak it replaces (a private
// 0600 drawing or .bak stays private). The mode is set as the new file is created, so a
@@ -955,8 +805,7 @@ pub(crate) fn backup(path: &std::path::Path) -> std::io::Result<bool> {
}
std::io::Write::write_all(out, &head)?;
std::io::copy(&mut src, out).map(|_| ())
})?;
Ok(true)
})
}
/// Store the bytes, then mark the drawing saved under `path`. If storing fails the drawing keeps
@@ -993,18 +842,15 @@ fn run_save(s: &mut Session, p: &Value) -> Result<Value> {
Some(p) => p.to_string(),
None => s.state()?.path.clone().ok_or_else(|| bad("qsave", "drawing has no file name yet; use saveas {path}"))?,
};
let (n, notes) = save_to(s, &path)?;
let mut r = saved(&path, n);
report_notes(s, &mut r, notes);
Ok(r)
let n = save_to(s, &path)?;
Ok(saved(&path, n))
}
fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("saveas", "`path` is required"))?.to_string();
let opts = save_options("saveas", p)?;
let (n, notes) = save_as(s, "saveas", &path, &opts)?;
let n = save_as(s, "saveas", &path, &opts)?;
let mut r = saved(&path, n);
report_notes(s, &mut r, notes);
if is_drawing_file(&path) {
r["version"] = json!(opts.version.unwrap_or_else(|| drawing_version(s, &path)).year());
r["binary"] = json!(opts.binary);
@@ -1048,25 +894,13 @@ 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)?;
let version = opts.version.unwrap_or_else(|| drawing_version(s, &format!("drawing.{fmt}")));
let lost = not_saved_as(s.doc()?, version);
let (bytes, notes) = write_bytes(s, "document.bytes", &format!("drawing.{fmt}"), &opts)?;
let bytes = write_bytes(s, "document.bytes", &format!("drawing.{fmt}"), &opts)?;
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len() });
report_notes(s, &mut r, notes);
if drops_unknown(format!("drawing.{fmt}")) {
report_not_saved(s, &mut r, &lost);
let notes = s.state().map(|st| dwg_notes(st.drawing())).unwrap_or_default();
@@ -1198,10 +1032,10 @@ pub(crate) fn lost_writing(d: &Drawing, path: &str, version: Version) -> std::co
}
/// Report what the file `path`, just written from the active document (what EXPORT writes: the
/// block while the Block Editor is open) at version `asked` (else its own), left out.
pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str, asked: Option<Version>) {
/// block while the Block Editor is open) at its own version, left out.
pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
let Ok(d) = s.doc() else { return };
let version = asked.unwrap_or_else(|| own_version(d, path));
let version = own_version(d, path);
let lost = lost_writing(d, path, version);
let notes = if drops_unknown(path) { dwg_notes(d) } else { Vec::new() };
report_lost(s, r, path, version, &lost);
@@ -1381,22 +1215,6 @@ mod tests {
use crate::Session;
use crate::temp_dir::TempDir;
/// Notes join the warnings a result already has instead of replacing them, and are said on
/// the command line.
#[test]
fn notes_are_added_to_the_warnings_a_result_has() {
let mut s = Session::new();
let mut r = json!({ "warnings": ["kept"] });
super::report_notes(&mut s, &mut r, vec!["added".into()]);
assert_eq!(r["warnings"], json!(["kept", "added"]));
let mut r = json!({});
super::report_notes(&mut s, &mut r, Vec::new());
assert!(r.get("warnings").is_none());
super::report_notes(&mut s, &mut r, vec!["first".into()]);
assert_eq!(r["warnings"], json!(["first"]));
assert!(s.log.ends_with(&["added".to_string(), "first".to_string()]), "{:?}", s.log);
}
/// Whether the `.bak` name is taken is asked without following a link there: a dangling link
/// counts as taken, so a file that doesn't look like a drawing leaves it alone.
#[cfg(unix)]
@@ -1529,33 +1347,6 @@ mod tests {
s.execute("close", &json!({"index": 2})).unwrap();
assert_eq!(active_title(&s), "Drawing2");
}
#[test]
fn next_and_previous_drawing_wrap_round_and_end_the_running_command() {
let mut s = Session::new();
s.execute("new", &json!({})).unwrap();
s.execute("new", &json!({})).unwrap();
assert_eq!((s.docs.len(), s.active), (3, 2));
assert_eq!(s.execute("document.next", &json!({})).unwrap()["index"], 0, "after the last comes the first");
assert_eq!(s.active, 0);
assert_eq!(s.execute("document.prev", &json!({})).unwrap()["index"], 2, "before the first comes the last");
s.execute("document.prev", &json!({})).unwrap();
assert_eq!(s.active, 1);
s.cmdline("line").unwrap();
assert!(s.running.is_some());
s.execute("document.next", &json!({})).unwrap();
assert!(s.running.is_none(), "a command left running belongs to the drawing it started in");
assert_eq!(s.active, 2);
}
#[test]
fn next_drawing_with_one_drawing_open_changes_nothing() {
let mut s = Session::new();
assert_eq!(s.docs.len(), 1);
assert_eq!(s.execute("document.next", &json!({})).unwrap()["index"], 0);
assert_eq!(s.execute("document.prev", &json!({})).unwrap()["index"], 0);
assert_eq!(s.docs.len(), 1);
}
}
#[cfg(test)]
+6 -94
View File
@@ -1,7 +1,7 @@
//! `grip.*` commands: the undoable, scriptable form of grip editing (see `crate::grips`).
use cadcraft_doc::{Entity, EntityKind, Handle};
use cadcraft_geom::{Mat3, Vec2, Vec3};
use cadcraft_geom::{Mat3, Vec2};
use serde_json::{Value, json};
use super::curves;
@@ -78,70 +78,6 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result<Value> {
Ok(json!({ "handle": h.hex(), "handles": edits.iter().map(|(o, _)| o.hex()).collect::<Vec<_>>() }))
}
/// Z coordinate of grip `index` on `kind` (matching `EntityKind::grips()` order), when the
/// entity stores a 3D position for that grip.
pub(super) fn grip_z(kind: &EntityKind, index: usize) -> Option<f64> {
let text_z = |t: &cadcraft_doc::Text| match (t.halign, t.valign) {
(cadcraft_doc::HAlign::Left, cadcraft_doc::VAlign::Baseline) | (cadcraft_doc::HAlign::Aligned | cadcraft_doc::HAlign::Fit, _) => t.insert.z,
_ => t.align_pt.unwrap_or(t.insert).z,
};
let z = match kind {
EntityKind::Line(l) => match index {
0 => Some(l.a.z),
1 => Some((l.a.z + l.b.z) * 0.5),
2 => Some(l.b.z),
_ => None,
},
EntityKind::Point(p) => (index == 0).then_some(p.p.z),
EntityKind::Circle(c) => (index < 5).then_some(c.center.z),
EntityKind::Arc(a) => (index < 4).then_some(a.center.z),
EntityKind::Ellipse(e) => (index < 5).then_some(e.center.z),
EntityKind::LwPolyline(p) => (index < kind.grips().len()).then_some(p.elevation),
EntityKind::Polyline3d(p) => p.points.get(index).map(|q| q.z),
EntityKind::Helix(h) => match index {
0 => Some(h.center.z),
1 => Some(h.start_point().z),
2 => Some(h.end_point().z),
_ => None,
},
EntityKind::Ray(r) | EntityKind::XLine(r) => match index {
0 => Some(r.base.z),
1 => Some(r.base.z + r.dir.z),
_ => None,
},
EntityKind::Text(t) => (index == 0).then(|| text_z(t)),
EntityKind::MText(t) => (index == 0).then_some(t.insert.z),
EntityKind::AttDef(a) => (index == 0).then(|| text_z(&a.text)),
EntityKind::Insert(i) => {
if index == 0 {
Some(i.insert.z)
} else {
i.grip_attribs().nth(index - 1).map(|(_, a)| text_z(&a.text))
}
}
EntityKind::Dimension(d) => match index {
0 => Some(d.p13.z),
1 => Some(d.p14.z),
2 => Some(d.defpt.z),
3 => Some(d.text_mid.z),
_ => None,
},
EntityKind::MLine(m) => m.vertices.get(index).map(|v| v.p.z),
EntityKind::Leader(l) => l.vertices.get(index).map(|v| v.z),
EntityKind::MLeader(m) => m.leaders.iter().flatten().map(|v| v.z).chain(std::iter::once(m.landing.z)).nth(index),
EntityKind::Hatch(h) => (index == 0).then_some(h.elevation),
EntityKind::Solid(s) | EntityKind::Trace(s) => s.corners.get(index).map(|c| c.z),
EntityKind::Face3d(f) => f.corners.get(index).map(|c| c.z),
EntityKind::PolyfaceMesh(m) => m.vertices.get(index).map(|v| v.z),
EntityKind::Viewport(v) => (index < 4).then_some(v.center.z),
EntityKind::Image(i) => (index == 0).then_some(i.insert.z),
EntityKind::Table(t) => (index < kind.grips().len()).then_some(t.insert.z),
EntityKind::Tolerance(t) => (index == 0).then_some(t.insert.z),
EntityKind::Spline(_) | EntityKind::Region(_) | EntityKind::Wipeout(_) | EntityKind::Unknown(_) => None,
};
z.filter(|v| v.is_finite())
}
/// Base point: `base`, or grip `index` of `baseHandle` (default: the first target).
fn base_point(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec2> {
if let Some(b) = point_param(p, "base") {
@@ -155,27 +91,6 @@ fn base_point(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec2>
g.get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))
}
/// 3D base point for SCALE: explicit `base` (with optional Z or ELEVATION), or the selected grip's
/// full 3D position so the grip stays stationary in all three coordinates.
fn base_point_3d(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec3> {
if let Some(b) = point_param(p, "base") {
return match p.get("base").and_then(|v| v.get(2)) {
Some(z) => z.as_f64().filter(|v| v.is_finite()).map(|z| Vec3::new(b.x, b.y, z)).ok_or_else(|| bad(cmd, "`base` Z must be a number")),
None => Ok(super::modify::at_elevation(s, b)),
};
}
let h = curves::handle_param(p, "baseHandle")
.or_else(|| hs.first().copied())
.ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?;
let i = index_param(cmd, p)?;
let e = curves::entity(s, h)?;
let g = e.kind.grips().get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))?;
Ok(match grip_z(&e.kind, i) {
Some(z) => Vec3::new(g.x, g.y, z),
None => super::modify::at_elevation(s, g),
})
}
fn apply(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<Value> {
let r = super::modify::transform_entities(s, hs, m, copy)?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
@@ -337,18 +252,15 @@ fn run_grip_rotate(s: &mut Session, p: &Value) -> Result<Value> {
fn run_grip_scale(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
// Why: Selected grip is the SCALE base point and must remain stationary in all three coordinates.
let base = base_point_3d(s, "grip.scale", p, &hs)?;
let f = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) {
Some(f) if f > 1e-12 => f,
let base = base_point(s, "grip.scale", p, &hs)?;
let m = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) {
Some(f) if f > 0.0 => Mat3::scale_about(base, f),
Some(_) => return Err(bad("grip.scale", "factor must be positive")),
None => {
let f = base.xy().dist(point_req("grip.scale", p, "to")?);
if f.is_finite() && f > 1e-12 { f } else { return Err(bad("grip.scale", "scale factor would be zero")) }
mode_matrix(GripMode::Scale, base, point_req("grip.scale", p, "to")?).ok_or_else(|| bad("grip.scale", "scale factor would be zero"))?
}
};
let r = super::modify::scale_entities(s, &hs, base, f, bool_or(p, "copy", false))?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
apply(s, &hs, &m, bool_or(p, "copy", false))
}
fn run_grip_mirror(s: &mut Session, p: &Value) -> Result<Value> {
+25 -60
View File
@@ -9,12 +9,12 @@
use std::sync::Arc;
use cadcraft_doc::{Drawing, EntityKind, Handle};
use cadcraft_geom::{Mat3, Vec2, Vec3};
use cadcraft_geom::{Mat3, Vec2};
use super::gripcmds::stretch_grips;
use super::helpers::line;
use super::machines::number;
use super::modify::{at_elevation, scale_entities, transform_entities};
use super::modify::transform_entities;
use crate::grips::{GripAction, GripMode, grip_action, grip_actions, mode_matrix};
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Running, Session, Step};
@@ -47,7 +47,6 @@ pub(crate) struct GripEdit {
/// selection that the view being edited shows.
targets: Vec<Handle>,
base: Vec2,
base_z: Option<f64>,
mode: GripMode,
copy: bool,
ask: Ask,
@@ -85,7 +84,6 @@ impl GripEdit {
picking: false,
targets: Vec::new(),
base: Vec2::ZERO,
base_z: None,
mode: GripMode::Stretch,
copy: false,
ask: Ask::Mode,
@@ -111,7 +109,6 @@ impl GripEdit {
}
if self.hot.is_empty() {
self.base = p;
self.base_z = s.doc().ok().and_then(|d| d.entity(h)).and_then(|e| super::gripcmds::grip_z(&e.kind, i));
self.targets.push(h);
self.targets.extend(s.selection().into_iter().filter(|x| *x != h && shown(s, *x)));
} else if !self.targets.contains(&h) {
@@ -223,7 +220,14 @@ impl GripEdit {
}
}
fn finish_edit(&mut self, before: Arc<Drawing>, changed: bool) -> Result<Step> {
/// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes).
fn edit(&mut self, s: &mut Session, to: Vec2, m: Option<Mat3>) -> Result<Step> {
let before = s.state()?.doc.clone();
let changed = match (self.mode, m) {
(GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(),
(_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(),
(_, None) => return Err(other("Invalid point.")),
};
if !changed {
return Err(other("The objects can't be edited that way (locked, or the result would be degenerate)."));
}
@@ -236,33 +240,6 @@ impl GripEdit {
}
}
/// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes).
fn edit(&mut self, s: &mut Session, to: Vec2, m: Option<Mat3>) -> Result<Step> {
let before = s.state()?.doc.clone();
let changed = match (self.mode, m) {
(GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(),
(_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(),
(_, None) => return Err(other("Invalid point.")),
};
self.finish_edit(before, changed)
}
/// Scale `targets` uniformly about `base` in 3D, scaling text heights, elevations and thickness.
fn edit_scale(&mut self, s: &mut Session, f: f64) -> Result<Step> {
if !f.is_finite() || f <= 1e-12 {
return Err(other("Invalid point."));
}
let before = s.state()?.doc.clone();
// Why: Selected grip is the SCALE base point and must remain stationary in all three
// coordinates; fall back to ELEVATION only when the base has no stored 3D Z.
let base = match self.base_z.filter(|z| z.is_finite()) {
Some(z) => Vec3::new(self.base.x, self.base.y, z),
None => at_elevation(s, self.base),
};
let changed = !scale_entities(s, &self.targets, base, f, self.copy)?.is_empty();
self.finish_edit(before, changed)
}
fn mode_input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Keyword(k) => match k.as_str() {
@@ -276,10 +253,9 @@ impl GripEdit {
}
"Undo" => match self.undo.pop() {
Some(doc) => {
// Settings changed meanwhile stay. The drawing put back is an earlier
// one: names of INSERT records end with it.
// Settings changed meanwhile stay.
let header = s.doc()?.header.clone();
s.state_mut()?.restore_drawing(doc);
s.state_mut()?.doc = doc;
s.doc_mut()?.header = header;
Ok(Step::Continue)
}
@@ -309,13 +285,13 @@ impl GripEdit {
s.echo(self.label());
Ok(Step::Continue)
}
Input::Point(p) | Input::Deferred(crate::snap::Deferred { at: p, .. }) => {
if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(p))
} else {
let m = self.matrix(p);
self.edit(s, p, m)
}
Input::Point(p) => {
let m = self.matrix(p);
self.edit(s, p, m)
}
Input::Deferred(d) => {
let m = self.matrix(d.at);
self.edit(s, d.at, m)
}
Input::Text(t) => match self.mode {
GripMode::Rotate => {
@@ -324,7 +300,7 @@ impl GripEdit {
}
GripMode::Scale => {
let f = positive(number(&t))?;
self.edit_scale(s, f)
self.edit(s, self.base, Some(Mat3::scale_about(self.base, f)))
}
_ => Err(other("Requires a point or an option keyword.")),
},
@@ -351,21 +327,14 @@ impl GripEdit {
(Ask::RefFirst, Input::Text(t)) => self.ask = Ask::RefNew(value(&t)?),
(Ask::RefFirst, Input::Enter) => self.ask = Ask::RefNew(if rotate { 0.0 } else { 1.0 }),
(Ask::RefSecond(a), Input::Point(p)) => self.ask = Ask::RefNew(between(a, p)?),
(Ask::RefNew(r), Input::Point(p)) => {
if rotate {
let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?;
return self.edit(s, p, Some(m));
}
let f = positive(Some(self.base.dist(p) / r))?;
return self.edit_scale(s, f);
(Ask::RefNew(_), Input::Point(p)) => {
let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?;
return self.edit(s, p, Some(m));
}
(Ask::RefNew(r), Input::Text(t)) => {
let v = value(&t)?;
if rotate {
return self.edit(s, self.base, Some(Mat3::rotate_about(self.base, v - r)));
}
let f = positive(Some(v / r))?;
return self.edit_scale(s, f);
let m = if rotate { Mat3::rotate_about(self.base, v - r) } else { Mat3::scale_about(self.base, positive(Some(v / r))?) };
return self.edit(s, self.base, Some(m));
}
(_, Input::Enter) => self.ask = Ask::Mode,
_ => {}
@@ -460,7 +429,6 @@ impl Interactive for GripEdit {
Ask::Base => match i {
Input::Point(p) => {
self.base = p;
self.base_z = None;
self.ask = Ask::Mode;
Ok(Step::Continue)
}
@@ -520,9 +488,6 @@ impl Session {
/// view being edited does not show are left out (the first grip left is the base grip), and it
/// is an error when none is left.
pub fn start_grip_edit(&mut self, hot: &[(Handle, usize)]) -> Result<()> {
// The value of an expression the frames are working out answers its prompt before the
// command it was typed in is cancelled for the grips.
self.lisp_settle_answer();
if self.running.is_some() {
self.cancel();
}
-29
View File
@@ -71,35 +71,6 @@ fn next_unnamed(d: &Drawing) -> String {
(1..=d.groups.len() + 1).map(|n| format!("*A{n}")).find(|n| !used.contains(n)).unwrap_or_else(|| format!("*A{}", d.groups.len() + 1))
}
/// When entities are copied, replicate any whole groups whose members were all copied.
pub(crate) fn replicate_groups_from(d: &mut Drawing, src_groups: &[Group], copies: &[(Handle, Handle)]) {
if copies.is_empty() || src_groups.is_empty() {
return;
}
let map: std::collections::HashMap<Handle, Handle> = copies.iter().copied().collect();
let mut new_groups = Vec::new();
for g in src_groups {
let active_members: Vec<Handle> = g.members.iter().copied().filter(|h| d.entity(*h).is_some()).collect();
if !active_members.is_empty() && active_members.iter().all(|h| map.contains_key(h)) {
let new_members: Vec<Handle> = active_members.iter().filter_map(|h| map.get(h).copied()).collect();
new_groups.push((g.description.clone(), g.selectable, new_members));
}
}
for (desc, selectable, members) in new_groups {
if d.groups.len() >= MAX_GROUPS {
break;
}
let name = next_unnamed(d);
d.groups.push(Group { name, description: desc, selectable, members });
}
}
/// When entities in the drawing `d` are copied, replicate any whole groups among them.
pub(crate) fn replicate_groups_for_copies(d: &mut Drawing, copies: &[(Handle, Handle)]) {
let groups = d.groups.clone();
replicate_groups_from(d, &groups, copies);
}
/// `hs` without repeats and without handles of objects that don't exist.
fn existing(d: &Drawing, hs: &[Handle]) -> Vec<Handle> {
let mut seen = std::collections::HashSet::new();
+42 -477
View File
@@ -1,14 +1,12 @@
//! 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 use patfile::{PatternChoice, pattern_choices, pattern_choices_in, register_drawing_patterns};
pub(super) use patfile::{drawing_lines, run_patterns};
pub(super) use patfile::run_patterns;
pub use patfile::{PatternChoice, pattern_choices};
use cadcraft_color::Color;
use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_scale};
use cadcraft_doc::{Drawing, Entity, EntityKind, Gradient, Handle, Hatch, HatchLoop, Space, entity_bounds};
use cadcraft_geom::{Bounds2, PolyVertex, Polyline, Vec2, point_in_polygon};
use serde_json::{Value, json};
@@ -19,7 +17,6 @@ use super::{CommandSpec, bad, bool_or, f64_or, point_param, points_param, size_p
use crate::{Accept, EngineError, Input, Interactive, Picker, Prompt, Result, Session, Step};
mod arcs;
mod assoc;
pub(crate) use assoc::detach;
mod edit;
@@ -28,24 +25,10 @@ use super::has_doc;
pub(crate) use assoc::update as refill_associative;
pub use pick::{HatchPicks, PickMode};
/// HATCH's parameters, for its JSON form and its catalog entry (the same for -HATCH).
const HATCH_PARAMS: &str = "{points?: [[x,y]] (internal points) and/or handles?: [hex] (closed objects), pattern?: \"ANSI31\" (built in, or defined by patternFile | patternText), patternFile?: path to a .pat file | patternText?: its contents (loads the patterns it defines), scale?, angle? (degrees), associative? (HPASSOC), separate? (HPSEPARATE: a hatch per point/object), origin?: [x,y] (HPORIGIN) | originMode?: \"current\"|\"bottomLeft\"|\"bottomRight\"|\"topLeft\"|\"topRight\"|\"center\" (HPORIGINMODE), style?: \"normal\"|\"outer\"|\"ignore\" (HPISLANDDETECTION)} — gaps up to HPGAPTOL close";
pub fn specs() -> Vec<CommandSpec> {
vec![
// An AutoLISP routine's `(command …)` call answers HATCH's published command-line questions
// (pattern, how it is drawn, then the boundary). A person, and a script's own HATCH line,
// get the interface's dialog, or the prompts of AutoCAD's -HATCH when it is off: a script
// keeps picking the boundary first as it always has.
CommandSpec::new("hatch", "Hatch...", run_hatch)
.menu(&["Draw", "Hatch..."])
.alias(&["h", "bh"])
.params(HATCH_PARAMS)
.interactive(|s| Ok(Box::new(HatchM::new(s, false, s.lisp_program_input())))),
// -HATCH: the command-line form, a script's too. Its own id, so a dashed start takes its
// prompts and never the HATCH sequence above.
CommandSpec::new("-hatch", "Hatch", run_hatch).params(HATCH_PARAMS).interactive(|s| Ok(Box::new(HatchM::new(s, false, false)))),
CommandSpec::new("gradient", "Gradient...", run_gradient).menu(&["Draw", "Gradient..."]).alias(&["gd"]).params("{points? and/or handles?, name?: \"LINEAR\"|\"CYLINDER\"|\"CURVED\"|\"SPHERICAL\"|\"HEMISPHERICAL\" or INV… (colours swapped), color1?, color2?, angle? (degrees), centered? (default true)}").interactive(|s| Ok(Box::new(HatchM::new(s, true, false)))),
CommandSpec::new("hatch", "Hatch...", run_hatch).menu(&["Draw", "Hatch..."]).alias(&["h", "bh", "-hatch"]).params("{points?: [[x,y]] (internal points) and/or handles?: [hex] (closed objects), pattern?: \"ANSI31\" (built in, or defined by patternFile | patternText), patternFile?: path to a .pat file | patternText?: its contents (loads the patterns it defines), scale?, angle? (degrees), associative? (HPASSOC), separate? (HPSEPARATE: a hatch per point/object), origin?: [x,y] (HPORIGIN) | originMode?: \"current\"|\"bottomLeft\"|\"bottomRight\"|\"topLeft\"|\"topRight\"|\"center\" (HPORIGINMODE), style?: \"normal\"|\"outer\"|\"ignore\" (HPISLANDDETECTION)} — gaps up to HPGAPTOL close").interactive(|s| Ok(Box::new(HatchM::new(s, false)))),
CommandSpec::new("gradient", "Gradient...", run_gradient).menu(&["Draw", "Gradient..."]).alias(&["gd"]).params("{points? and/or handles?, name?: \"LINEAR\"|\"CYLINDER\"|\"CURVED\"|\"SPHERICAL\"|\"HEMISPHERICAL\" or INV… (colours swapped), color1?, color2?, angle? (degrees), centered? (default true)}").interactive(|s| Ok(Box::new(HatchM::new(s, true)))),
CommandSpec::new("boundary", "Boundary...", run_boundary).menu(&["Draw", "Boundary..."]).alias(&["bo", "bpoly"]).params("{points: [[x,y]]}").interactive(|_| Ok(Box::new(BoundaryM { region: false }))),
CommandSpec::new("region", "Region", run_region)
.menu(&["Draw", "Region"])
@@ -57,10 +40,6 @@ 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)
@@ -75,15 +54,13 @@ pub(super) fn outline_tol(ext: Bounds2) -> f64 {
}
/// Tessellated outlines of every visible curve in the space (hatch boundary candidates), each
/// with the handle of the object it came from and its exact piece ([`arcs::pieces_of`]), and
/// the flattening tolerance.
fn outlines(d: &Drawing, space: &Space, near: Option<Bounds2>) -> (Vec<Vec<Vec2>>, Vec<Handle>, Vec<Option<arcs::Piece>>, f64) {
/// with the handle of the object it came from.
fn outlines(d: &Drawing, space: &Space, near: Option<Bounds2>) -> (Vec<Vec<Vec2>>, Vec<Handle>) {
let Some(store) = d.space(space) else { return (Vec::new(), Vec::new()) };
let ext = d.extents(space);
let tol = outline_tol(ext);
let Some(store) = d.space(space) else { return (Vec::new(), Vec::new(), Vec::new(), tol) };
let mut out = Vec::new();
let mut owners = Vec::new();
let mut pieces = Vec::new();
for e in store.iter() {
if !d.is_visible(e) || matches!(e.kind, EntityKind::Hatch(_) | EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_)) {
continue;
@@ -96,10 +73,9 @@ fn outlines(d: &Drawing, space: &Space, near: Option<Bounds2>) -> (Vec<Vec<Vec2>
}
let polys = object_polys(d, e, tol, ext);
owners.extend(std::iter::repeat_n(e.handle, polys.len()));
pieces.extend(arcs::pieces_of(e, polys.len()));
out.extend(polys);
}
(out, owners, pieces, tol)
(out, owners)
}
/// An object's outline as polylines (tolerance `tol`), infinite lines clipped to a generous
@@ -217,7 +193,7 @@ impl OriginMode {
}
/// The origin for loops: `current` when the mode keeps it.
pub(crate) fn origin(self, loops: &[HatchLoop], current: Vec2) -> Vec2 {
let b = loops_bounds(loops);
let b = Bounds2::from_points(loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p)).filter(|p| p.is_finite()));
if b.is_empty() {
return current;
}
@@ -232,25 +208,6 @@ impl OriginMode {
}
}
/// The extents of hatch loops with their arcs: a bulged edge reaches past its vertices (a circle
/// kept as two half-circle vertices spans its whole height).
fn loops_bounds(loops: &[HatchLoop]) -> Bounds2 {
let mut b = Bounds2::from_points(loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p)).filter(|p| p.is_finite()));
for l in loops {
let vs = &l.vertices;
for (i, v) in vs.iter().enumerate() {
let Some(next) = vs.get((i + 1) % vs.len()) else { continue };
if let Some((arc, _)) = cadcraft_geom::bulge_to_arc(v.p, next.p, v.bulge) {
let ab = arc.bounds();
if ab.min.is_finite() && ab.max.is_finite() {
b = b.union(&ab);
}
}
}
}
b
}
/// Island detection style by name (HPISLANDDETECTION 0 normal, 1 outer, 2 ignore).
pub(crate) fn island_style(t: &str) -> Option<u8> {
match t.trim().to_ascii_lowercase().as_str() {
@@ -267,17 +224,15 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
let space = s.space();
let ext = d.extents(&space);
let tol = ((ext.width() + ext.height()) * 1e-9).max(1e-9);
let (polys, owners, pieces, ftol) = outlines(d, &space, None);
let (polys, owners) = outlines(d, &space, None);
// A line that ends on a flattened curve (an ellipse) can stop short of its chords.
let polys = cadcraft_geom::region::snap_ends(&polys, ftol, tol);
let polys = cadcraft_geom::region::snap_ends(&polys, outline_tol(ext), tol);
let found = cadcraft_geom::region::boundary_at_gap(&polys, p, tol, gap_tolerance(d))
.ok_or_else(|| EngineError::Other("Valid hatch boundary not found.".into()))?;
let outer = found.outer;
let ob = Bounds2::from_points(outer.iter().copied());
let sources = handles_of(&owners, &found.outer_sources);
// The traced outline is flattened: circular runs become arcs again (#1167).
let mut loops =
vec![HatchLoop { vertices: arcs::with_arcs(&outer, &found.outer_edges, &pieces, ftol), outer: true, boundary_flags: None, sources }];
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, boundary_flags: None, sources }];
// Islands: closed objects entirely inside the outer loop that don't contain the pick point.
if let Some(store) = d.space(&space) {
for e in store.iter() {
@@ -306,7 +261,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
if open_curves {
let sources = handles_of(&owners, &island.sources);
loops.push(HatchLoop {
vertices: arcs::with_arcs(&island.outline, &island.edges, &pieces, ftol),
vertices: island.outline.into_iter().map(PolyVertex::new).collect(),
outer: false,
boundary_flags: None,
sources,
@@ -319,9 +274,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
pub(crate) fn loops_from_handles(s: &Session, hs: &[Handle]) -> Result<Vec<HatchLoop>> {
let d = s.doc()?;
let mut loops = Vec::new();
let mut seen = std::collections::HashSet::new();
// An object selected twice is one boundary.
for h in hs.iter().filter(|h| seen.insert(**h)) {
for h in hs {
if let Some(vs) = d.entity(*h).and_then(|e| closed_loop(d, e)) {
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), boundary_flags: None, sources: vec![*h] });
}
@@ -345,15 +298,9 @@ 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.
user_spacing: f64,
angle: f64,
/// A user-defined pattern is doubled ("Double hatch area?", DXF group 77): a second family of
/// lines at right angles to the first.
double: bool,
gradient: Option<Gradient>,
associative: bool,
/// HPSEPARATE: one hatch per picked point or selected object.
@@ -378,15 +325,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,
scale: f64_or(p, "scale", hdr.1).max(1e-9),
angle: p.get("angle").and_then(Value::as_f64).map(f64::to_radians).unwrap_or(hdr.2),
double: false,
gradient: g,
associative: bool_or(p, "associative", s.doc().map_or(true, |d| d.header.i64("HPASSOC", 1) != 0)),
separate: bool_or(p, "separate", s.doc().is_ok_and(|d| d.header.i64("HPSEPARATE", 0) != 0)),
@@ -410,27 +352,24 @@ impl HatchSettings {
loops.iter_mut().for_each(|l| l.sources.clear());
}
let solid = self.gradient.is_some() || self.pattern == "SOLID";
let user_defined = cadcraft_doc::library::is_user_pattern(&self.pattern);
EntityKind::Hatch(Hatch {
pattern: if self.gradient.is_some() { "SOLID".into() } else { self.pattern.clone() },
solid,
origin: self.origin_mode.origin(&loops, self.origin),
loops,
scale: if user_defined { self.user_spacing } else { self.scale },
scale: self.scale,
angle: self.angle,
associative: self.associative,
style: self.style,
elevation: 0.0,
gradient: self.gradient.clone(),
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 { self.lines.clone() },
pattern_lines: patfile::lines_for(&self.pattern),
})
}
}
fn make(s: &mut Session, p: &Value, gradient: bool, loaded: &[String]) -> Result<Value> {
fn make(s: &mut Session, p: &Value, gradient: bool) -> 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" };
@@ -443,10 +382,7 @@ fn make(s: &mut Session, p: &Value, gradient: bool, loaded: &[String]) -> Result
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 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);
}
let st = HatchSettings::from(s, p, gradient);
// 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
@@ -493,18 +429,17 @@ fn same_loop(a: &HatchLoop, b: &HatchLoop) -> bool {
})
}
/// Deduplicate boundary loops that describe the same boundary in the same role. A loop that is
/// one pick's outer loop and another's island (a pick inside a circle and one around it) stays
/// twice: merged, the island would be gone and the even-odd fill would leave the circle empty.
/// Deduplicate boundary loops that describe the same boundary.
fn dedup_loops(loops: &mut Vec<HatchLoop>) {
let mut unique: Vec<HatchLoop> = Vec::with_capacity(loops.len());
for l in loops.drain(..) {
if let Some(existing) = unique.iter_mut().find(|u| u.outer == l.outer && same_loop(u, &l)) {
if let Some(existing) = unique.iter_mut().find(|u| same_loop(u, &l)) {
for s in l.sources {
if !existing.sources.contains(&s) {
existing.sources.push(s);
}
}
existing.outer = existing.outer || l.outer;
} else {
unique.push(l);
}
@@ -545,19 +480,18 @@ fn add_hatches(s: &mut Session, st: &HatchSettings, groups: Vec<Vec<HatchLoop>>)
}
fn run_hatch(s: &mut Session, p: &Value) -> Result<Value> {
let loaded = patfile::load_param(p)?;
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, &loaded)
make(s, p, false)
}
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>> {
@@ -586,9 +520,8 @@ fn run_boundary(s: &mut Session, p: &Value) -> Result<Value> {
for q in pts {
out.extend(boundary_at(s, q)?.into_iter().map(|h| h.hex()));
if out.len() > MAX_BOUNDARY_OUTPUT {
// The refused call leaves no partial result behind. Handles it gave out can
// be given again, so names of INSERT records end.
s.state_mut()?.restore_drawing(before);
// The refused call leaves no partial result behind.
s.state_mut()?.doc = before;
return Err(bad("boundary", format!("more than {MAX_BOUNDARY_OUTPUT} boundary polylines in one call; split the work")));
}
}
@@ -621,12 +554,6 @@ fn pattern_exists(name: &str) -> bool {
cadcraft_doc::library::pattern(name).is_some() || patfile::user_pattern(name).is_some()
}
/// Whether `t` answers the pattern prompt with the user-defined form (U, User, User defined), as
/// AutoCAD's HATCH takes it from an AutoLISP routine.
fn user_pattern_keyword(t: &str) -> bool {
matches!(t.trim().to_ascii_lowercase().replace([' ', '-', '_'], "").as_str(), "u" | "user" | "userdefined")
}
/// The existing pattern `name` means, typed at the pattern prompt: read upper-cased, else a loaded
/// pattern's own name when only its Greek spelling differs in case or accent (σολιδ for ΣΟΛΙΔ).
pub(crate) fn pattern_named(name: &str) -> Option<String> {
@@ -644,22 +571,11 @@ enum HatchAsk {
Pattern,
Scale,
Angle,
/// The user-defined pattern's line angle: the same answer as [`HatchAsk::Angle`], asked as
/// AutoCAD's user-defined hatch asks it.
UserAngle,
/// The user-defined pattern's spacing between its lines (stored as the hatch's scale).
Spacing,
/// "Double hatch area?": a second family of lines at right angles.
Double,
Origin,
}
struct HatchM {
gradient: bool,
/// An AutoLISP routine's `(command …)` call started HATCH ([`Session::lisp_program_input`]): the
/// published command-line sequence (the pattern or the user-defined form, then its values, then the
/// objects) rather than a boundary picked first, as a person and a script's own HATCH line do.
legacy: bool,
settings: HatchSettings,
/// Loops by pick (one hatch each when separate).
loops: Vec<Vec<HatchLoop>>,
@@ -672,10 +588,9 @@ struct HatchM {
}
impl HatchM {
fn new(s: &Session, gradient: bool, legacy: bool) -> Self {
fn new(s: &Session, gradient: bool) -> Self {
HatchM {
gradient,
legacy: legacy && !gradient,
settings: HatchSettings::from(s, &Value::Null, gradient),
loops: Vec::new(),
asking: None,
@@ -705,33 +620,14 @@ impl HatchM {
fn answer(&mut self, s: &mut Session, a: HatchAsk, t: &str) -> Result<bool> {
match a {
HatchAsk::Pattern => {
let t = t.trim();
// "?": the patterns there are, as AutoCAD lists them; the pattern is asked again.
if t == "?" {
s.echo(format!("Available patterns: {}", patfile::names().join(", ")));
return Ok(false);
}
// The user-defined form asks for its lines next, not a named pattern's scale and angle.
if self.legacy && user_pattern_keyword(t) {
self.settings.pattern = cadcraft_doc::library::USER_PATTERN.to_string();
self.settings.user_spacing = s.last_used.hatch_spacing;
self.settings.double = s.last_used.hatch_double;
return Ok(true);
}
let file = patfile::typed_file(s, t);
let explicit = file.is_some();
let up = match file {
let up = match patfile::typed_file(s, t.trim()) {
// 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(),
None => t.trim().to_ascii_uppercase(),
};
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));
if pattern_exists(&up) {
self.settings.pattern = up.clone();
// A named pattern, SOLID included, is not the user-defined one.
self.settings.double = false;
s.doc_mut()?.header.set_str("HPNAME", &up);
} else {
s.echo(format!("Unknown pattern {up}. Available: {}", patfile::names().join(", ")));
@@ -739,35 +635,16 @@ impl HatchM {
}
}
HatchAsk::Scale => {
let Some(v) = super::machines::number(t).filter(|v| v.is_finite() && *v > 0.0) else {
s.echo("Value must be positive and nonzero.");
return Ok(false);
};
s.doc_mut()?.header.set_f64("HPSCALE", v);
let Some(v) = super::machines::number(t).filter(|v| v.is_finite() && *v > 0.0) else { return Ok(false) };
self.settings.scale = v;
s.doc_mut()?.header.set_f64("HPSCALE", v);
}
HatchAsk::Spacing => {
let Some(spacing) = super::machines::number(t).filter(|v| is_supported_hatch_pattern_scale(*v)) else {
s.echo(format!("Hatch spacing must be greater than {MIN_HATCH_PATTERN_SCALE:e} drawing units."));
return Ok(false);
};
self.settings.user_spacing = spacing;
s.last_used.hatch_spacing = spacing;
}
HatchAsk::Angle | HatchAsk::UserAngle => {
HatchAsk::Angle => {
// Turns the pattern from the X axis (not from ANGBASE), clockwise when ANGDIR is 1.
let Some(a) = s.angle_settings().rotation(t).filter(|a| a.is_finite()) else { return Ok(false) };
self.settings.angle = a;
s.doc_mut()?.header.set_f64("HPANG", a);
}
HatchAsk::Double => {
self.settings.double = match t.trim().to_ascii_lowercase().as_str() {
"y" | "yes" => true,
"n" | "no" => false,
_ => return Ok(false),
};
s.last_used.hatch_double = self.settings.double;
}
HatchAsk::Origin => {
let mode = match t {
"Bottom left" => OriginMode::BottomLeft,
@@ -783,27 +660,15 @@ impl HatchM {
Ok(true)
}
/// The angle prompt `msg` with the current angle as its default, offered as it would be typed.
fn angle_prompt(&self, s: &Session, msg: &str) -> Prompt {
let (au, ap) = s.doc().map(|d| (d.header.i64("AUNITS", 0), d.header.i64("AUPREC", 0))).unwrap_or((0, 0));
// Offered as it would be typed: clockwise is positive when ANGDIR is 1.
let a = if s.angle_settings().clockwise { -self.settings.angle } else { self.settings.angle };
Prompt::new(msg, Accept::NUMBER).default(crate::units::format_angle(a, au, ap))
}
/// The sub-prompt that follows `a` (`taken`: its answer was taken). The Pattern option goes
/// on, as AutoCAD 2024's -HATCH Properties does, from the pattern name to its scale and then
/// its angle (a solid fill has neither), and asks again for a pattern or a value it refused.
/// The user-defined form goes instead to its lines' angle, their spacing and the double answer.
fn after(&self, a: HatchAsk, taken: bool) -> Option<HatchAsk> {
if !self.properties {
return None;
}
match a {
_ if !taken => Some(a),
HatchAsk::Pattern if cadcraft_doc::library::is_user_pattern(&self.settings.pattern) => Some(HatchAsk::UserAngle),
HatchAsk::UserAngle => Some(HatchAsk::Spacing),
HatchAsk::Spacing => Some(HatchAsk::Double),
HatchAsk::Pattern if self.settings.pattern != "SOLID" => Some(HatchAsk::Scale),
HatchAsk::Scale => Some(HatchAsk::Angle),
_ => None,
@@ -822,13 +687,6 @@ impl Interactive for HatchM {
self.settings.scale,
self.settings.angle.to_degrees()
));
if self.legacy {
// A routine answers the published questions first: the pattern, how it is drawn, then the
// boundary objects. A person picks the boundary first, and so does a script's own line.
self.asking = Some(HatchAsk::Pattern);
self.properties = true;
self.selecting = true;
}
Ok(Step::Continue)
}
fn prompt(&self, s: &Session) -> Prompt {
@@ -838,26 +696,17 @@ impl Interactive for HatchM {
let p = Prompt::new("Enter a pattern name", Accept::TEXT)
.default(self.settings.pattern.clone())
.picker(Picker::HatchPattern(self.settings.pattern.clone()));
return if self.gradient {
p
} else if self.legacy {
// The published command-line answers: a pattern, a solid fill, the user-defined
// form, or the pattern list.
p.kw(&["?", "Solid", "User defined"])
} else {
p.kw(&["Solid"])
};
return if self.gradient { p } else { p.kw(&["Solid"]) };
}
Some(HatchAsk::Scale) => {
return Prompt::new("Specify a scale for the hatch pattern", Accept::NUMBER).default(format!("{:.4}", self.settings.scale));
}
Some(HatchAsk::Angle) => return self.angle_prompt(s, "Specify an angle for the hatch pattern"),
Some(HatchAsk::UserAngle) => return self.angle_prompt(s, "Specify an angle for the hatch lines"),
Some(HatchAsk::Spacing) => {
return Prompt::new("Specify a spacing between the lines", Accept::NUMBER).default(self.settings.user_spacing.to_string());
}
Some(HatchAsk::Double) => {
return Prompt::new("Double hatch area?", Accept::TEXT).kw(&["Yes", "No"]).default(if self.settings.double { "Y" } else { "N" });
Some(HatchAsk::Angle) => {
let (au, ap) = s.doc().map(|d| (d.header.i64("AUNITS", 0), d.header.i64("AUPREC", 0))).unwrap_or((0, 0));
// Offered as it would be typed: clockwise is positive when ANGDIR is 1.
let a = if s.angle_settings().clockwise { -self.settings.angle } else { self.settings.angle };
let d = crate::units::format_angle(a, au, ap);
return Prompt::new("Specify an angle for the hatch pattern", Accept::NUMBER).default(d);
}
Some(HatchAsk::Origin) => return Prompt::new("Specify the pattern origin", Accept::POINT).kw(&ORIGIN_KW).default("Use current"),
None => {}
@@ -937,10 +786,7 @@ impl Interactive for HatchM {
self.asking = Some(HatchAsk::Pattern);
self.properties = !self.gradient;
}
"sCale" => {
let ask = if cadcraft_doc::library::is_user_pattern(&self.settings.pattern) { HatchAsk::Spacing } else { HatchAsk::Scale };
self.asking = Some(ask);
}
"sCale" => self.asking = Some(HatchAsk::Scale),
"Angle" => self.asking = Some(HatchAsk::Angle),
"Origin" => self.asking = Some(HatchAsk::Origin),
"sEparate" => {
@@ -1008,16 +854,6 @@ mod tests {
d.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some((e.handle.hex(), h.clone())) } else { None }).unwrap()
}
/// How many hatches the drawing has.
fn hatch_count(s: &Session) -> usize {
s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Hatch(_))).count()
}
/// The closed 4000 × 2000 polyline the older LISP routines draw before they hatch it.
fn lisp_rectangle(s: &mut Session) {
s.cmdline("(command \"_.pline\" '(0 0) '(4000 0) '(4000 2000) '(0 2000) \"_c\")").unwrap();
}
#[test]
fn hatchedit_pattern_replaces_gradient() {
let mut s = Session::new();
@@ -1127,277 +963,6 @@ mod tests {
s.cancel();
}
/// HATCH started by a LISP routine takes the published command-line answers in order: the
/// pattern name, its scale and angle, then the boundary objects (issue #3498).
#[test]
fn lisp_hatch_takes_pattern_scale_and_angle_then_the_objects() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"dots\" 50 0 \"_l\" \"\")").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(hatch_count(&s), 1);
let h = only_hatch(&s).1;
assert_eq!((h.pattern.as_str(), h.loops.len()), ("DOTS", 1));
assert!((h.scale - 50.0).abs() < 1e-9, "{}", h.scale);
assert!(h.angle.abs() < 1e-12, "{}", h.angle);
}
/// The user-defined answer (U) asks for the lines' angle, their spacing and whether to double
/// them, as AutoCAD's HATCH does, and makes one hatch of the selection.
#[test]
fn lisp_user_defined_hatch_takes_angle_spacing_and_double() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"_u\" 45 100 \"_n\" \"_l\" \"\")").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(hatch_count(&s), 1);
let h = only_hatch(&s).1;
assert_eq!(h.pattern, cadcraft_doc::library::USER_PATTERN);
assert!(!h.solid);
assert!((h.angle - 45f64.to_radians()).abs() < 1e-12, "{}", h.angle);
assert!((h.scale - 100.0).abs() < 1e-9, "{}", h.scale);
assert_eq!(h.pattern_lines.len(), 1, "not doubled");
let absolute = h.pattern_lines[0].angle + h.angle.to_degrees();
assert!((absolute - 45.0).abs() < 1e-9, "lines at {absolute} degrees");
}
/// A doubled user-defined hatch has a second family of lines at right angles to the first.
#[test]
fn a_doubled_user_defined_hatch_has_a_second_family_at_right_angles() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"_u\" 45 100 \"_y\" \"_l\" \"\")").unwrap();
let h = only_hatch(&s).1;
assert_eq!(h.pattern_lines.len(), 2, "double hatch area: two families");
let absolute = |i: usize| h.pattern_lines[i].angle + h.angle.to_degrees();
assert!((absolute(1) - absolute(0) - 90.0).abs() < 1e-9, "{} and {}", absolute(0), absolute(1));
}
/// Enter at each question takes its default: the current pattern, scale and angle (the
/// user-defined form's angle, spacing and double flag too).
#[test]
fn lisp_hatch_enter_takes_the_current_values() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"\" \"\" \"\" \"_l\" \"\")").unwrap();
let h = only_hatch(&s).1;
assert_eq!((h.pattern.as_str(), h.scale, h.angle), ("ANSI31", 1.0, 0.0));
// The user-defined questions too: ANSI31 is replaced, the current angle and spacing kept,
// and "Double hatch area?" defaults to No.
s.cmdline("(command \"_.hatch\" \"_u\" \"\" \"\" \"\" \"_l\" \"\")").unwrap();
let h = s
.doc()
.unwrap()
.model
.iter()
.filter_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None })
.find(|h| h.pattern == cadcraft_doc::library::USER_PATTERN)
.unwrap();
assert_eq!(h.pattern, cadcraft_doc::library::USER_PATTERN);
assert!((h.scale - 1.0).abs() < 1e-12 && h.angle.abs() < 1e-12, "{} {}", h.scale, h.angle);
assert_eq!(h.pattern_lines.len(), 1, "not doubled");
}
#[test]
fn lisp_user_hatch_reads_spacing_and_double_across_drawings() {
let mut s = Session::new();
s.cmdline("(setvar \"HPSPACE\" 12.5)").unwrap();
s.cmdline("(setvar \"HPDOUBLE\" 1.0)").unwrap();
s.new_drawing(false);
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"_u\" \"\" \"\")").unwrap();
assert!(s.prompt_text().ends_with("<Y>:"), "{}", s.prompt_text());
for answer in ["", "_l", ""] {
s.cmdline(answer).unwrap();
}
let h = only_hatch(&s).1;
assert_eq!((h.scale, h.pattern_lines.len()), (12.5, 2));
}
#[test]
fn lisp_user_hatch_answers_leave_named_scale_unchanged() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(setvar \"HPSCALE\" 2.0)").unwrap();
s.cmdline("(command \"_.hatch\" \"_u\" 45 10 \"_y\" \"_l\" \"\")").unwrap();
assert_eq!(crate::sysvars::get(&s, "HPSCALE"), Some(json!(2.0)));
assert_eq!(crate::sysvars::get(&s, "HPSPACE"), Some(json!(10.0)));
assert_eq!(crate::sysvars::get(&s, "HPDOUBLE"), Some(json!(1)));
}
/// Solid asks neither a scale nor an angle, as it never has.
#[test]
fn lisp_hatch_solid_takes_no_scale_or_angle() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"_s\" \"_l\" \"\")").unwrap();
let h = only_hatch(&s).1;
assert!(h.solid);
assert_eq!(h.pattern, "SOLID");
}
/// "?" lists the patterns and asks again, as AutoCAD does.
#[test]
fn lisp_hatch_question_mark_lists_patterns_and_asks_again() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"?\")").unwrap();
assert!(s.log.iter().any(|l| l.contains("Available patterns") && l.contains("ANSI31")), "{:?}", s.log);
assert!(s.prompt_text().contains("Enter a pattern name"), "{}", s.prompt_text());
for answer in ["ansi31", "", "", "_l", ""] {
s.cmdline(answer).unwrap();
}
assert_eq!(only_hatch(&s).1.pattern, "ANSI31");
}
/// A zero, a negative number, NaN or text answers a scale or spacing question again, changing
/// nothing; the answers after it are read as the values they are, and nothing panics.
#[test]
fn a_refused_hatch_scale_or_spacing_changes_nothing() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"ansi31\" \"0\" \"-5\" \"nan\" \"x\" 2 30 \"_l\" \"\")").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let h = only_hatch(&s).1;
assert_eq!(h.pattern, "ANSI31");
assert!((h.scale - 2.0).abs() < 1e-9, "{}", h.scale);
assert!((h.angle - 30f64.to_radians()).abs() < 1e-12, "{}", h.angle);
assert!(s.log.iter().any(|l| l.contains("Value must be positive and nonzero.")), "{:?}", s.log);
// A spacing refused and then cancelled leaves no hatch behind.
let before = hatch_count(&s);
s.cmdline("(command \"_.hatch\" \"_u\" 45 \"0\")").unwrap();
assert!(s.running.is_some(), "still asking for the spacing");
assert!(s.prompt_text().contains("spacing"), "{}", s.prompt_text());
s.cancel();
assert_eq!(hatch_count(&s), before);
}
#[test]
fn user_hatch_spacing_at_the_limit_is_refused_and_just_above_it_draws_and_saves() {
let limit = MIN_HATCH_PATTERN_SCALE;
let spacing = limit.next_up();
let mut s = Session::new();
lisp_rectangle(&mut s);
s.execute("setvar", &json!({ "name": "HPSPACE", "value": spacing })).unwrap();
for value in [limit / 2.0, limit] {
let result = s.execute("setvar", &json!({ "name": "HPSPACE", "value": value }));
assert!(result.unwrap_err().to_string().contains("greater than"));
}
s.cmdline("(command \"_.hatch\" \"_u\" 0)").unwrap();
for value in [limit / 2.0, limit] {
s.cmdline(&value.to_string()).unwrap();
assert!(s.prompt_text().contains("Specify a spacing"), "{}", s.prompt_text());
}
assert!(s.log.iter().any(|line| line.contains("Hatch spacing must be greater than")), "{:?}", s.log);
let default = s.current_prompt().unwrap().default.unwrap().parse::<f64>().unwrap();
assert_eq!(default, spacing);
assert_eq!(crate::sysvars::get(&s, "HPSPACE"), Some(json!(spacing)));
for answer in ["", "_n", "_l", ""] {
s.cmdline(answer).unwrap();
}
// Draw a strip with room for a few lines so the sweep stays within its line budget.
let opts = cadcraft_render::Options { view: Some(Bounds2::from_points([Vec2::ZERO, Vec2::new(1.0, spacing * 5.0)])), ..Default::default() };
let original = s.doc().unwrap();
let reopened = cadcraft_io::read_dxf(cadcraft_io::write_dxf(original).as_bytes()).unwrap();
for drawing in [original, &reopened] {
let hatch = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap();
let display = cadcraft_render::build(drawing, &Space::Model, &opts);
let lines: Vec<_> = display
.prims
.iter()
.filter(|p| p.handle == hatch.handle && p.kind == cadcraft_render::Kind::Polyline)
.map(|p| display.points(p)[0].y)
.collect();
assert!(lines.len() >= 2, "expected multiple hatch lines, got {lines:?}");
for pair in lines.windows(2) {
let measured = (pair[1] - pair[0]).abs();
assert!((measured / spacing - 1.0).abs() < 1e-12, "drawn spacing {measured}, requested {spacing}");
}
}
}
/// A script's own HATCH line is not a routine's call: it keeps the interface's prompts and picks
/// the boundary first, as it did before a routine's answers were published.
#[test]
fn a_script_hatch_keeps_the_interface_prompts() {
let mut s = Session::new();
s.script("pline 0,0 4000,0 4000,2000 0,2000 c\nhatch\n").unwrap();
// The boundary question comes first: no pattern, scale or angle is asked.
assert!(s.prompt_text().contains("Pick internal point"), "{}", s.prompt_text());
s.cmdline("2000,1000").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let h = only_hatch(&s).1;
assert_eq!((h.pattern.as_str(), h.scale), ("ANSI31", 1.0));
}
/// A routine's `(command …)` inside a script is still a routine's call: it takes the published
/// order, though the script's own HATCH line above does not.
#[test]
fn a_lisp_hatch_call_from_a_script_takes_the_published_order() {
let mut s = Session::new();
s.script("pline 0,0 4000,0 4000,2000 0,2000 c\n(command \"_.hatch\" \"dots\" 50 0 \"_l\" \"\")\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let h = only_hatch(&s).1;
assert_eq!(h.pattern, "DOTS");
assert!((h.scale - 50.0).abs() < 1e-9, "{}", h.scale);
}
/// A script that a routine starts with `(command "_.script" …)` runs its lines as a script: its
/// HATCH line takes the interface's options (A for the angle), not the routine's order.
#[test]
fn a_script_a_routine_starts_keeps_the_interface_prompts() {
let dir = std::env::temp_dir().join(format!("cadcraft-hatch-script-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("angle.scr");
std::fs::write(&file, "hatch A 45\n\n").unwrap();
let mut s = Session::new();
let path = file.to_string_lossy().replace('\\', "/");
s.cmdline(&format!("(command \"_.script\" \"{path}\")")).unwrap();
let a = s.doc().unwrap().header.f64("HPANG", 0.0);
let _ = std::fs::remove_dir_all(&dir);
assert!((a - std::f64::consts::FRAC_PI_4).abs() < 1e-9, "HPANG {a}; {}", s.prompt_text());
assert!(!s.lisp_program_input(), "the routine's flag is restored after the script");
}
/// -HATCH keeps its own questions, a routine's included: it picks the boundary first, and the
/// Properties option takes the pattern, scale and angle as before.
#[test]
fn dash_hatch_keeps_its_pick_boundary_prompts() {
let mut s = Session::new();
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap();
s.cmdline("(command \"_.-hatch\")").unwrap();
assert!(s.prompt_text().contains("Pick internal point"), "{}", s.prompt_text());
s.cancel();
// Typed by a person (the interface's dialog off) it is the same command line.
s.start("hatch").unwrap();
assert!(s.prompt_text().contains("Pick internal point"), "{}", s.prompt_text());
s.cancel();
}
/// A user-defined hatch is saved as one (pattern `_USER`, pattern type 0, its double flag) and
/// read back with its angle, spacing and families.
#[test]
fn a_user_defined_hatch_survives_a_dxf_save_and_read() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"_u\" 45 100 \"_y\" \"_l\" \"\")").unwrap();
let text = cadcraft_io::write_dxf(s.doc().unwrap());
let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
let h = d.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).unwrap();
assert_eq!(h.pattern, cadcraft_doc::library::USER_PATTERN);
assert!(!h.solid);
assert!((h.scale - 100.0).abs() < 1e-9, "{}", h.scale);
assert!((h.angle - 45f64.to_radians()).abs() < 1e-12, "{}", h.angle);
assert_eq!(h.pattern_lines.len(), 2, "the doubled families are made again");
}
#[test]
fn unknown_pattern_error_and_catalog_name_the_pat_file_route() {
let mut s = Session::new();
-147
View File
@@ -1,147 +0,0 @@
//! Exact arcs in traced hatch boundaries (#1167).
//!
//! The boundary search works on flattened curves, so a loop traced around an internal point
//! comes out as chords: a hatch in a circle had 158 straight edges and the wrong area. Each
//! traced edge knows the input polyline it lies on, and each input polyline is one piece of one
//! object (a line, a circle, an arc or one segment of a polyline), so nothing is guessed from
//! nearby geometry: a run of edges on the same circular piece becomes one bulged vertex again,
//! and the corners move onto the exact curves (where a line or another circle crosses).
use cadcraft_doc::{Entity, EntityKind, Prim};
use cadcraft_geom::{Circle, Line, PolyVertex, Segment, Vec2, arc_to_bulge, circle_circle, line_circle, shoelace};
/// The exact curve behind one input polyline.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Piece {
Line(Line),
Circle(Circle),
}
/// The exact piece behind each of `e`'s `n` outline polylines (one per primitive, in order, as
/// `select::hit_polylines` makes them), or `None` for each when `e` isn't made of lines and
/// circular arcs or the count doesn't match.
pub(crate) fn pieces_of(e: &Entity, n: usize) -> Vec<Option<Piece>> {
if !matches!(e.kind, EntityKind::Line(_) | EntityKind::Arc(_) | EntityKind::Circle(_) | EntityKind::LwPolyline(_)) {
return vec![None; n];
}
let prims = e.kind.prims();
if prims.len() != n {
return vec![None; n];
}
prims
.iter()
.map(|p| match p {
Prim::Seg(Segment::Line(l)) => Some(Piece::Line(*l)),
Prim::Seg(Segment::Arc { arc, .. }) => Some(Piece::Circle(Circle::new(arc.center, arc.radius))),
Prim::Circle(c) => Some(Piece::Circle(*c)),
_ => None,
})
.collect()
}
fn same_circle(a: &Circle, b: &Circle) -> bool {
a.center == b.center && a.radius == b.radius
}
/// The loop `pts` (edge `i` from `pts[i]` to the next vertex, closed) with its circular runs
/// as bulged vertices. `edges` names each edge's input polyline, `pieces` each polyline's exact
/// curve; `tol` is the flattening tolerance the polylines were made with. Anything that doesn't
/// check out stays as traced.
pub(crate) fn with_arcs(pts: &[Vec2], edges: &[Option<usize>], pieces: &[Option<Piece>], tol: f64) -> Vec<PolyVertex> {
let n = pts.len();
let plain = || pts.iter().map(|p| PolyVertex::new(*p)).collect::<Vec<_>>();
if n < 3 || edges.len() != n || !(tol.is_finite() && tol > 0.0) || pts.iter().any(|p| !p.is_finite()) {
return plain();
}
let at = |i: usize| pts.get(i % n).copied().unwrap_or_default();
let piece = |i: usize| edges.get(i % n).copied().flatten().and_then(|k| pieces.get(k).copied().flatten());
// A chord of a curve flattened to `tol` stays within `tol` of it; corners split where two
// chords cross may be a little further.
let slack = tol * 4.0;
let near_circle = |c: &Circle, q: Vec2| (c.center.dist(q) - c.radius).abs() <= slack;
// The circle each edge lies on: its piece is a circle and both ends and the middle are on
// it (the middle, so a long chord across the circle doesn't pass for an arc).
let circ: Vec<Option<(usize, Circle)>> = (0..n)
.map(|i| {
let k = edges.get(i).copied().flatten()?;
let Some(Piece::Circle(c)) = piece(i) else { return None };
let (a, b) = (at(i), at(i + 1));
(c.radius.is_finite() && c.radius > slack && near_circle(&c, a) && near_circle(&c, b) && near_circle(&c, a.mid(b))).then_some((k, c))
})
.collect();
let key = |i: usize| circ.get(i % n).copied().flatten().map(|(k, _)| k);
if circ.iter().all(Option::is_none) {
return plain();
}
let ccw = shoelace(pts) > 0.0;
// One whole circle: two half circles, as a hatch made by selecting the circle has.
if let Some(Some((k0, c))) = circ.first().copied()
&& (0..n).all(|i| key(i) == Some(k0))
{
let b = if ccw { 1.0 } else { -1.0 };
return vec![PolyVertex::with_bulge(c.center - Vec2::X * c.radius, b), PolyVertex::with_bulge(c.center + Vec2::X * c.radius, b)];
}
let line_of = |i: usize| match piece(i) {
Some(Piece::Line(l)) if l.a != l.b && [at(i), at(i + 1)].iter().all(|q| ((*q - l.a).cross(l.b - l.a) / l.a.dist(l.b)).abs() <= slack) => {
Some(l)
}
_ => None,
};
let onto = |c: &Circle, q: Vec2| {
let d = q - c.center;
if d.len() > 0.0 { c.center + d.normalized() * c.radius } else { q }
};
// Vertex `i` (between edges `i - 1` and `i`) on the exact curves: where the two pieces
// cross, nearest the traced corner, or else moved onto the circle it is on.
let corner = |i: usize| -> Vec2 {
let p = at(i);
let (prev, next) = (circ.get((i + n - 1) % n).copied().flatten(), circ.get(i % n).copied().flatten());
let crossings: Vec<Vec2> = match (prev, next) {
(Some((_, a)), Some((_, b))) if same_circle(&a, &b) => return onto(&a, p),
(Some((_, a)), Some((_, b))) => circle_circle(&a, &b),
(Some((_, c)), None) => line_of(i).map(|l| line_circle(&l, &c).into_iter().map(|x| x.0).collect()).unwrap_or_default(),
(None, Some((_, c))) => line_of(i + n - 1).map(|l| line_circle(&l, &c).into_iter().map(|x| x.0).collect()).unwrap_or_default(),
(None, None) => return p,
};
// Where two curves cross at a shallow angle, a corner off them by the flattening
// tolerance can be off along them by up to about √(2·r·tolerance): the crossing nearest
// the traced corner is taken within that reach, when no other crossing is as near.
let r = prev.or(next).map_or(0.0, |(_, c)| c.radius);
let reach = slack * 2.0 + (2.0 * r * slack).sqrt();
let mut xs: Vec<(f64, Vec2)> = crossings.into_iter().filter(|x| x.is_finite()).map(|x| (x.dist(p), x)).collect();
xs.sort_by(|a, b| a.0.total_cmp(&b.0));
match (xs.first(), xs.get(1)) {
(Some(&(d, x)), second) if d <= reach && second.is_none_or(|&(d2, _)| d2 > 2.0 * d + slack) => x,
_ => prev.or(next).map_or(p, |(_, c)| onto(&c, p)),
}
};
// Start where a run begins, so no run wraps past the end.
let Some(s) = (0..n).find(|&i| key(i) != key(i + n - 1)) else { return plain() };
let mut out = Vec::with_capacity(n);
let mut i = 0;
while i < n {
let e = (s + i) % n;
let p = corner(e);
let Some((k, c)) = circ.get(e).copied().flatten() else {
out.push(PolyVertex::new(p));
i += 1;
continue;
};
// The angle the run turns through about the centre, edge by edge.
let mut sweep = 0.0;
let mut a = p;
let mut j = i;
while j < n && key(s + j) == Some(k) {
let last = j + 1 >= n || key(s + j + 1) != Some(k);
let b = if last { corner(s + j + 1) } else { at(s + j + 1) };
let (u, v) = (a - c.center, b - c.center);
sweep += u.cross(v).atan2(u.dot(v));
a = b;
j += 1;
}
let bulge = arc_to_bulge(sweep);
out.push(PolyVertex::with_bulge(p, if bulge.is_finite() { bulge } else { 0.0 }));
i = j;
}
if out.len() < 2 { plain() } else { out }
}
+5 -12
View File
@@ -87,14 +87,8 @@ fn refill(before: &Drawing, after: &Drawing, l: &HatchLoop) -> Refill {
return Refill::Open;
}
let tol = super::outline_tol(nb);
let mut polys: Vec<Vec<Vec2>> = Vec::new();
let mut pieces = Vec::new();
for e in live.iter().filter_map(|h| after.entity(*h)) {
let ps = object_polys(after, e, tol, nb);
pieces.extend(super::arcs::pieces_of(e, ps.len()));
polys.extend(ps);
}
let snap = ((nb.width() + nb.height()) * 1e-9).max(1e-9);
let polys: Vec<Vec<Vec2>> = live.iter().filter_map(|h| after.entity(*h)).flat_map(|e| object_polys(after, e, tol, nb)).collect();
let polys = region::snap_ends(&polys, tol, snap);
let gap = gap_tolerance(after);
let found = if l.outer {
@@ -103,14 +97,13 @@ fn refill(before: &Drawing, after: &Drawing, l: &HatchLoop) -> Refill {
let ob = if ob.is_empty() { nb } else { ob };
let old = outline_of(&l.vertices, (ob.width() + ob.height()).max(1e-9) / 20000.0);
region::interior_point(&old)
.and_then(|q| region::enclosing_loop_edges_gap(&polys, map_point(q, &ob, &nb), snap, gap))
.or_else(|| region::outline_edges(&polys, snap, gap))
.and_then(|q| region::enclosing_loop_gap(&polys, map_point(q, &ob, &nb), snap, gap))
.or_else(|| region::outline(&polys, snap, gap))
} else {
region::outline_edges(&polys, snap, gap)
region::outline(&polys, snap, gap)
};
match found {
// Traced again from flattened curves: circular runs become arcs again (#1167).
Some((pts, edges)) => Refill::Loop(super::arcs::with_arcs(&pts, &edges, &pieces, tol)),
Some(pts) => Refill::Loop(pts.into_iter().map(PolyVertex::new).collect()),
None => Refill::Open,
}
}
-205
View File
@@ -1,205 +0,0 @@
//! 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);
}
}
}
+8 -32
View File
@@ -8,7 +8,7 @@ use cadcraft_geom::{Bounds2, Polyline, Vec2, point_in_polygon};
use serde_json::{Value, json};
use super::assoc::{detach, same_shape};
use super::{GRADIENT_NAMES, ORIGIN_KW, OriginMode, closed_loop, dedup_loops, gradient_name, island_style, loops_at, loops_from_handles, same_loop};
use super::{GRADIENT_NAMES, ORIGIN_KW, OriginMode, closed_loop, dedup_loops, gradient_name, island_style, loops_at, loops_from_handles};
use crate::cmd::helpers::lwpoly;
use crate::cmd::{bad, bool_or, point_param, points_param, size_param, str_param, targets};
use crate::{Accept, Input, Interactive, Picker, Prompt, Result, Session, Step};
@@ -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, local: Option<&[cadcraft_doc::library::PatternLine]>) {
fn properties(h: &mut Hatch, p: &Value) {
if let Some(v) = str_param(p, "pattern") {
set_pattern(h, v, local);
set_pattern(h, v);
}
if let Some(x) = p.get("scale").and_then(Value::as_f64).filter(|x| x.is_finite() && *x > 0.0) {
h.scale = x;
@@ -222,12 +222,11 @@ 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, local: Option<&[cadcraft_doc::library::PatternLine]>) -> bool {
pub(crate) fn set_pattern(h: &mut Hatch, name: &str) -> bool {
let name = name.trim();
if name.is_empty() || (local.is_none() && !takes_pattern(h, name)) {
if name.is_empty() || !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
@@ -238,10 +237,6 @@ pub(crate) fn set_pattern(h: &mut Hatch, name: &str, local: Option<&[cadcraft_do
// 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;
}
@@ -425,21 +420,7 @@ fn edit_loops(h: &mut Hatch, added: &[HatchLoop], removed: &[usize]) -> Result<(
return Ok(());
}
h.loops = h.loops.drain(..).enumerate().filter_map(|(i, l)| (!removed.contains(&i)).then_some(l)).collect();
// A boundary the hatch already has is not added again (whatever role it has here): a second
// copy would cancel it under the odd-parity fill. Its objects join the loop there, so picking
// it links an unlinked loop to them.
for a in added {
match h.loops.iter_mut().find(|l| same_loop(l, a)) {
Some(l) => {
for s in &a.sources {
if !l.sources.contains(s) {
l.sources.push(*s);
}
}
}
None => h.loops.push(a.clone()),
}
}
h.loops.extend_from_slice(added);
dedup_loops(&mut h.loops);
if h.loops.is_empty() {
return Err(bad("hatchedit", "a hatch needs at least one boundary loop"));
@@ -484,9 +465,7 @@ 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()?;
@@ -514,7 +493,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, local.as_deref());
properties(&mut h, p);
if let Some(g) = &grad {
g.apply(&mut h);
}
@@ -727,10 +706,7 @@ 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()
&& super::drawing_lines(s.doc()?, &up).is_none()
{
if cadcraft_doc::library::pattern(&up).is_none() && super::patfile::user_pattern(&up).is_none() {
s.echo(format!("Unknown pattern {up}."));
return Ok(Step::Continue);
}
+5 -54
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, is_reserved_pattern_name, standard_patterns};
use cadcraft_doc::library::{PatternLine, pattern, 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 is_reserved_pattern_name(name) {
if pattern(name).is_some() {
return Vec::new();
}
user_pattern(name).map(|p| p.lines).unwrap_or_default()
@@ -70,54 +70,6 @@ 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>) {
@@ -126,7 +78,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 is_reserved_pattern_name(&p.name) {
if pattern(&p.name).is_some() {
warnings.push(format!("{} is a built-in pattern; the built-in definition is kept", p.name));
continue;
}
@@ -145,15 +97,14 @@ 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<Vec<String>> {
pub(super) fn load_param(p: &Value) -> Result<()> {
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(Vec::new())
Ok(())
}
/// A `.pat` file typed at HATCH's pattern prompt: load it and return the pattern to use (the
+2 -21
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; 5] = ["Points", "Objects", "oRigin", "Hatch", "TileRect"];
const MODES: [&str; 4] = ["Points", "Objects", "oRigin", "Hatch"];
/// What HATCHPICK picks.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -22,8 +22,6 @@ 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.
@@ -46,7 +44,6 @@ 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,
@@ -137,10 +134,6 @@ 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),
@@ -157,13 +150,12 @@ impl Interactive for HatchPickM {
};
match (mode, i) {
(_, Input::Cancel) => Ok(Step::Cancel),
(PickMode::Points | PickMode::TileRect | PickMode::Objects, Input::Keyword(k)) if k == "Undo" => {
(PickMode::Points | 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)
@@ -182,17 +174,6 @@ 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> = {
+6 -24
View File
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("status", "Status", run_status).menu(&["Tools", "Inquiry", "Status"]).noundo(),
CommandSpec::new("drawing.inspect", "Inspect Drawing", run_inspect).params("{entities?: bool, limit?: n}").noundo(),
CommandSpec::new("entities", "Query Entities", run_entities)
.params("{type?, layer?, selected?: bool (default false; true = current selection in active space), window?: [[x,y],[x,y]], crossing?: bool (default true; false = entirely inside), xdata?: true | \"APP\" | [\"APP\", …] (add each entity's extended data {\"APP\": [[code, value], …]}; a name also keeps only entities carrying that application's data), limit?, offset?} → {count (all matches), returned, offset, entities}")
.params("{type?, layer?, selected?: bool (default false; true = current selection in active space), window?: [[x,y],[x,y]], crossing?: bool (default true; false = entirely inside), limit?, offset?} → {count (all matches), returned, offset, entities}")
.noundo(),
CommandSpec::new("shapes", "Analyze Shapes", shapes::run).params(shapes::PARAMS).noundo(),
CommandSpec::new("usage", "Analyze Usage", usage::run).params(usage::PARAMS).noundo(),
@@ -532,17 +532,12 @@ pub(super) fn object_area(s: &Session, h: Handle) -> Result<(f64, f64)> {
(cadcraft_geom::PI * a * b, arc.arc_length_from(0.0, cadcraft_geom::TAU))
}
EntityKind::Hatch(hh) => {
// Odd parity, as drawn: a loop nested inside an odd number of other loops is an unfilled
// island. The loops the fill keeps (a repeated loop once; an outer loop and an island
// that are the same boundary cancel), each measured exactly with its arcs.
let kept = cadcraft_render::hatch_fill_loop_indices(hh, 1e-3);
let geoms: Vec<Polyline> =
kept.iter().filter_map(|(i, _)| hh.loops.get(*i)).map(|l| Polyline { vertices: l.vertices.clone(), closed: true }).collect();
let polys: Vec<Vec<Vec2>> = kept.into_iter().map(|(_, p)| p).collect();
// Odd parity, as drawn: a loop nested inside an odd number of other loops is an unfilled island.
let geoms: Vec<Polyline> = hh.loops.iter().map(|l| Polyline { vertices: l.vertices.clone(), closed: true }).collect();
let polys: Vec<Vec<Vec2>> = geoms.iter().map(|g| g.tessellate(1e-3)).collect();
let mut total = (0.0, 0.0);
for (i, g) in geoms.iter().enumerate() {
// As the fill tests nesting: an edge's middle (a vertex may touch the loop around).
let probe = polys.get(i).and_then(|p| cadcraft_render::hatch_loop_probe(p));
let probe = polys.get(i).and_then(|p| p.first().copied());
let depth = probe.map_or(0, |pt| polys.iter().enumerate().filter(|(j, q)| *j != i && cadcraft_geom::point_in_polygon(q, pt)).count());
total.0 += if depth % 2 == 0 { g.area().abs() } else { -g.area().abs() };
total.1 += g.len();
@@ -658,7 +653,6 @@ fn run_entities(s: &mut Session, p: &Value) -> Result<Value> {
.transpose()?;
let crossing = given("crossing").map_or(Ok(true), |v| v.as_bool().ok_or_else(|| bad(CMD, "`crossing` must be true or false")))?;
let selected = given("selected").map_or(Ok(false), |v| v.as_bool().ok_or_else(|| bad(CMD, "`selected` must be true or false")))?;
let xdata = super::props::xdata::XdataSelect::parse(given("xdata")).map_err(|m| bad(CMD, m))?;
let limit = count("limit", 500)?;
let offset = count("offset", 0)?;
let st = s.state()?;
@@ -672,20 +666,8 @@ fn run_entities(s: &mut Session, p: &Value) -> Result<Value> {
.filter(|e| ty.as_ref().is_none_or(|t| e.kind.type_name().to_ascii_lowercase() == *t || e.kind.dxf_name().to_ascii_lowercase() == *t))
.filter(|e| layer.as_ref().is_none_or(|l| e.common.layer.to_ascii_lowercase() == *l))
.filter(|e| window.as_ref().is_none_or(|w| crate::select::in_window(d, e, None, w, crossing, tol)))
.filter(|e| !xdata.filters() || xdata.matches(&e.common.xdata))
.collect();
let page: Vec<Value> = matches
.iter()
.skip(offset)
.take(limit)
.map(|e| {
let mut v = entity_summary(e);
if let (Some(x), Some(o)) = (xdata.json(&e.common.xdata), v.as_object_mut()) {
o.insert("xdata".into(), x);
}
v
})
.collect();
let page: Vec<Value> = matches.iter().skip(offset).take(limit).map(|e| entity_summary(e)).collect();
// `count` is every match; `returned` is this page of them (`offset`, `limit`).
Ok(json!({ "count": matches.len(), "returned": page.len(), "offset": offset, "entities": page }))
}
-31
View File
@@ -251,7 +251,6 @@ fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
*l = updated;
if let Some(nn) = new_name {
l.name = nn.clone();
cadcraft_doc::foreign::Foreign::rename_shared(&mut d.foreign, &["LAYER"], &old, &nn);
// Re-point entities in model space, every layout and every block definition.
repoint(&mut d.model, &old, &nn);
for layout in &mut d.layouts {
@@ -836,36 +835,6 @@ mod tests {
assert_eq!(graphics_layer(&s), "0");
}
/// The same for linetypes: PURGE keeps one only proxy graphics draw with, and RENAME takes
/// the graphics and the file's LTYPE order with it.
#[test]
fn linetypes_proxy_graphics_draw_with_are_in_use_and_renamed() {
let mut s = proxy_on_b();
for name in ["DASHED", "HIDDEN"] {
s.execute("linetype", &json!({ "load": name })).unwrap();
}
let d = s.doc_mut().unwrap();
d.proxy_linetypes = vec!["Continuous".into(), "DASHED".into(), "HIDDEN".into()];
let h = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::Unknown(_))).unwrap().handle;
d.modify_entity(h, |e| {
if let cadcraft_doc::EntityKind::Unknown(u) = &mut e.kind {
u.graphics[0].common.linetype = "DASHED".into();
}
})
.unwrap();
s.execute("purge", &json!({})).unwrap();
let d = s.doc().unwrap();
assert!(d.linetype("DASHED").is_some() && d.linetype("HIDDEN").is_none());
s.execute("rename", &json!({ "table": "linetype", "from": "DASHED", "to": "DASH2" })).unwrap();
let d = s.doc().unwrap();
let linetype = d.model.iter().find_map(|e| match &e.kind {
cadcraft_doc::EntityKind::Unknown(u) => Some(u.graphics[0].common.linetype.clone()),
_ => None,
});
assert_eq!(linetype.as_deref(), Some("DASH2"));
assert_eq!(d.proxy_linetypes, ["Continuous", "DASH2", "HIDDEN"]);
}
#[test]
fn rename_repoints_paper_space_and_block_entities() {
let mut s = Session::new();
+16 -222
View File
@@ -15,7 +15,6 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
use viewports::MviewM;
mod plotstyle;
pub(crate) use plotstyle::keep_used_folder_copies;
mod prompts;
mod viewports;
@@ -27,12 +26,8 @@ pub fn specs() -> Vec<CommandSpec> {
.interactive(|_| Ok(Box::new(prompts::LayoutM::default()))),
CommandSpec::new("layout.new", "New Layout", run_new)
.menu(&["Insert", "Layout", "New Layout"])
.params("{name?, viewport?: bool (default true), window?: [[x1,y1],[x2,y2]] (the model area the viewport shows; default the model extents)} → {name, viewport} (typed: asks the name only; LAYOUT.NEWAREA also asks the area)")
.params("{name?, viewport?: bool (default true)} → {name, viewport}")
.interactive(|_| Ok(Box::new(NewLayoutM))),
CommandSpec::new("layout.newarea", "New Layout from Area...", run_new)
.menu(&["Insert", "Layout", "New Layout from Area..."])
.params("{name?, viewport?: bool (default true), window?: [[x1,y1],[x2,y2]] (the model area the viewport shows; default the model extents)} → {name, viewport} (typed: asks the name, then the area)")
.interactive(|_| Ok(Box::new(NewLayoutAreaM::default()))),
CommandSpec::new("layout.delete", "Delete Layout", run_delete).params("{name}"),
CommandSpec::new("layout.rename", "Rename Layout", run_rename).params("{from?: current layout, to}"),
CommandSpec::new("layout.copy", "Copy Layout", run_copy).params("{from, to?}"),
@@ -83,18 +78,18 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("pagesetup", "Page Setup Manager...", run_pagesetup)
.menu(&["File", "Page Setup Manager..."])
.params(
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|\"B4 (JIS)\"|\"Japanese Postcard\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}; layout \"Model\" keeps only plotStyleTable",
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
),
// PLOT and EXPORTPDF are undoable for what a plot keeps in the drawing (a folder table's
// copy, Model's table); a plot that changes nothing leaves no undo step.
CommandSpec::new("plot", "Print...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "plot")?, "plot"))
.menu(&["File", "Print..."])
.key("Cmd+P")
.alias(&["print"])
.params("{path? (else returns base64 `data`), layout?: current|\"Model\", device?: \"CADCraft PDF\"|\"CADCraft PNG\"|\"CADCraft SVG\" | a plotter from PLOTTERMANAGER | \"None\" (default: a layout's page setup device; Model, or \"None\": no device, PDF; a device sets the output format and the papers), paper?: the device's paper (default: a layout keeps its page setup's; Model takes the device's default), landscape?, fit?: bool, scale?: number | \"1:50\", center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?: bool, plotTransparency?: bool (default: the page setup's; PLOTTRANSPARENCYOVERRIDE 0/2 overrides it), plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]]} (typed or from the menu: the Plot dialog)"),
.params("{path? (else returns base64 `data`), layout?: current|\"Model\", device?: \"CADCraft PDF\"|\"CADCraft PNG\"|\"CADCraft SVG\" | a plotter from PLOTTERMANAGER | \"None\" (default: a layout's page setup device; Model, or \"None\": no device, PDF; a device sets the output format and the papers), paper?: the device's paper (default: a layout keeps its page setup's; Model takes the device's default), landscape?, fit?: bool, scale?: number | \"1:50\", center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?: bool, plotTransparency?: bool (default: the page setup's; PLOTTRANSPARENCYOVERRIDE 0/2 overrides it), plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]]} (typed or from the menu: the Plot dialog)")
.noundo(),
CommandSpec::new("exportpdf", "Export to PDF...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "exportpdf")?, "exportpdf"))
.menu(&["File", "Export to PDF..."])
.params("{path? (else returns base64 `data`), layout?, device? (its papers; the output stays PDF), paper?, landscape?, fit?, scale?, center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?, plotTransparency?, plotArea?, window?} (as PLOT)"),
.params("{path? (else returns base64 `data`), layout?, device? (its papers; the output stays PDF), paper?, landscape?, fit?, scale?, center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?, plotTransparency?, plotArea?, window?} (as PLOT)")
.noundo(),
CommandSpec::new("mspace", "Model Space (in viewport)", run_mspace)
.alias(&["ms"])
.params("{handle?: viewport, at?: [x,y] paper point inside a viewport} (default: the last active or first viewport)")
@@ -230,133 +225,7 @@ impl Interactive for NewLayoutM {
}
}
/// LAYOUT.NEWAREA from the menu or command line: asks for the name (Enter takes the next free one),
/// then for the part of the model the new layout shows. The Model tab is shown for that, so it
/// can be zoomed and panned first; two corners pick the area (Enter takes the whole drawing). The
/// new layout is then shown, zoomed to that area.
#[derive(Default)]
struct NewLayoutAreaM {
/// The checked name, once it has been asked.
name: Option<String>,
/// The first corner of the model area.
first: Option<Vec2>,
/// The tab the command started in, put back when it is cancelled.
from: Option<Space>,
}
impl NewLayoutAreaM {
/// Show tab `space` (`layout.set`).
fn show(s: &mut Session, space: &Space) -> Result<()> {
let set = find_command("layout.set").ok_or_else(|| crate::EngineError::UnknownCommand("layout.set".into()))?;
(set.run)(s, &json!({ "name": space.tab_name() }))?;
Ok(())
}
}
impl Interactive for NewLayoutAreaM {
fn name(&self) -> &'static str {
"LAYOUT"
}
fn prompt(&self, s: &Session) -> Prompt {
match (&self.name, self.first) {
(None, _) => {
let next = s.doc().map(next_layout_name).unwrap_or_else(|_| "Layout1".into());
Prompt::new("Enter name of new layout", Accept::TEXT).default(next)
}
(Some(_), None) => {
Prompt::new("Specify first corner of the model area to show in the layout, or press ENTER for the whole drawing", Accept::POINT)
}
// A window's first corner: with ortho on, the opposite corner is not bent onto it.
(Some(_), Some(a)) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let Some(name) = self.name.clone() else {
let name = match i {
Input::Text(t) if !t.trim().is_empty() => t.trim().to_string(),
Input::Text(_) | Input::Enter => next_layout_name(s.doc()?),
_ => return Ok(Step::Continue),
};
// A taken or invalid name is an error: the session reports it and asks again.
let name = check_name("layout.newarea", s.doc()?, &name, None)?;
// The area is picked in the Model tab, where the drawing can be zoomed and panned.
self.from = Some(s.layout_space());
Self::show(s, &Space::Model)?;
self.name = Some(name);
return Ok(Step::Continue);
};
// The corners are model points. If another tab was shown meanwhile (a tab click, `layout.set`),
// a point would be read in that space, so the command ends and leaves that choice alone.
if s.layout_space() != Space::Model {
self.from = None;
return Ok(Step::Cancel);
}
let window = match (i, self.first) {
(Input::Point(p), None) => {
self.first = Some(p);
return Ok(Step::Continue);
}
(Input::Point(p), Some(a)) => Some([a, p]),
(Input::Enter, None) => None,
_ => return Ok(Step::Continue),
};
let mut p = json!({ "name": name });
if let (Some([a, b]), Some(o)) = (window, p.as_object_mut()) {
o.insert("window".into(), json!([[a.x, a.y], [b.x, b.y]]));
}
// A window without width or height is an error, reported before any layout is added:
// the session asks for the first corner again.
self.first = None;
run_new(s, &p)?;
Self::show(s, &Space::Paper(name))?;
Ok(Step::Done)
}
/// Puts back the tab the command started in.
fn cancelled(&mut self, s: &mut Session) {
// Only if the Model tab is still shown: a tab the user chose since is left alone.
if let Some(from) = self.from.take()
&& s.layout_space() == Space::Model
&& let Err(e) = Self::show(s, &from)
{
s.echo(e.to_string());
}
}
/// The rectangle following the cursor while the second corner is picked.
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
let Some(a) = self.first else { return Vec::new() };
let corners = [a, Vec2::new(c.x, a.y), c, Vec2::new(a.x, c.y), a];
corners
.windows(2)
.filter_map(|w| match w {
[p, q] => Some(super::helpers::line(*p, *q)),
_ => None,
})
.collect()
}
}
/// The model-space window of a `layout.new`, when it has one: `window: [[x1, y1], [x2, y2]]`.
fn window_param(p: &Value) -> Result<Option<Bounds2>> {
let Some(raw) = p.get("window").filter(|w| !w.is_null()) else { return Ok(None) };
let corners = raw.as_array();
let a = corners.and_then(|c| c.first()).and_then(point_value);
let b = corners.and_then(|c| c.get(1)).and_then(point_value);
let (Some(a), Some(b)) = (a, b) else {
return Err(bad("layout.new", "`window` needs two corners: [[x1, y1], [x2, y2]]"));
};
let w = Bounds2::new(a, b);
if w.min.is_finite() && w.max.is_finite() && w.width() > 1e-9 && w.height() > 1e-9 && w.width() < 1e12 && w.height() < 1e12 {
Ok(Some(w))
} else {
Err(bad("layout.new", "the window needs a width and a height"))
}
}
/// LAYOUT.NEW from JSON: add a layout (with a viewport unless `viewport` is false), zoomed to
/// `window` when it has one and to the model extents otherwise.
fn run_new(s: &mut Session, p: &Value) -> Result<Value> {
// Checked before anything is added, so a bad window leaves no layout behind.
let window = window_param(p)?;
let d = s.doc()?;
let name = match str_param(p, "name") {
Some(n) => check_name("layout.new", d, n, None)?,
@@ -367,30 +236,16 @@ fn run_new(s: &mut Session, p: &Value) -> Result<Value> {
s.doc_mut()?.layouts.push(Layout { page, ..Layout::new(&name, order) });
let mut vp = Value::Null;
if bool_or(p, "viewport", true) {
// AutoCAD behaviour: one viewport over the printable area, zoomed to the model extents,
// or to the `window` when it has one.
// AutoCAD behaviour: one viewport over the printable area, zoomed to the model extents.
let space = Space::Paper(name.clone());
let rect = printable(s, &name)?;
if let Some(h) = add_viewports(s, &space, rect, 1, "")?.first() {
if let Some(w) = window {
show_window(s, *h, w)?;
}
vp = json!(h.hex());
}
}
Ok(json!({ "name": name, "viewport": vp }))
}
/// Zoom viewport `h` to the model area `w`.
fn show_window(s: &mut Session, h: Handle, w: Bounds2) -> Result<()> {
s.doc_mut()?.modify_entity(h, |e| {
if let EntityKind::Viewport(v) = &mut e.kind {
(v.view_center, v.view_height) = fit_bounds(w, v.width, v.height);
}
})?;
Ok(())
}
fn run_delete(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("layout.delete", "`name` is required"))?;
let name = layout_name("layout.delete", s.doc()?, name)?;
@@ -467,7 +322,6 @@ fn run_copy(s: &mut Session, p: &Value) -> Result<Value> {
ucs: src.ucs,
ucs_previous: Vec::new(),
limits: src.limits,
flags: src.flags,
});
Ok(json!({ "name": to }))
}
@@ -583,11 +437,6 @@ fn fit_view(d: &Drawing, w: f64, h: f64) -> (Vec2, f64) {
let hi = d.header.point("LIMMAX").map(|p| p.xy()).unwrap_or(Vec2::new(12.0, 9.0));
ext = Bounds2::new(lo, hi);
}
fit_bounds(ext, w, h)
}
/// The view centre and height that show the model area `ext` in a viewport of size `w` × `h`.
fn fit_bounds(ext: Bounds2, w: f64, h: f64) -> (Vec2, f64) {
let aspect = (w / h.max(1e-12)).max(1e-12);
let vh = (ext.height().max(ext.width() / aspect) * 1.02).max(1e-9);
let c = ext.center();
@@ -813,27 +662,13 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
"plotTransparency",
];
let changes = keys.iter().any(|k| p.get(k).is_some());
// Model keeps only its plot style table (the rest of its plot settings are chosen per plot).
if str_param(p, "layout").is_some_and(|n| n.eq_ignore_ascii_case("model")) {
if let Some(k) = keys.iter().find(|k| **k != "plotStyleTable" && p.get(**k).is_some()) {
return Err(bad(cmd, format!("Model keeps only `plotStyleTable`; `{k}` is chosen for each plot")));
}
if let Some(v) = str_param(p, "plotStyleTable")
&& plotstyle::table_choice_changes(s.doc()?, v, true)
&& plotstyle::set_model_table(s.doc_mut()?, v)
{
s.touch();
}
let table = s.doc()?.model_page.as_ref().map(|m| m.plot_style_table.clone()).unwrap_or_default();
return Ok(json!({ "layout": "Model", "page": { "plotStyleTable": table } }));
}
let name = match str_param(p, "layout") {
Some(n) => Some(layout_name(cmd, s.doc()?, n)?),
None => s.space().layout().map(str::to_string),
};
let Some(name) = name else {
if changes {
return Err(bad(cmd, "pass `layout` (Model keeps only its `plotStyleTable`, with `layout: \"Model\"`)"));
return Err(bad(cmd, "pass `layout` (model-space page setups are not stored yet)"));
}
// Report every layout's page setup.
let d = s.doc()?;
@@ -848,21 +683,8 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
// The standard size the layout had before this call, so that resubmitting it (the Plot
// dialog's Apply to Layout always sends `paper`) keeps the layout's paper units.
let old_paper = cadcraft_render::paper_size(&page.paper).map(|ps| ps.name);
let turned = p.get("landscape").and_then(Value::as_bool).filter(|l| *l != page.landscape);
// The orientation first: a paper taken from a device turns its margins to the sheet the page
// names when `page_device` copies them.
if let Some(l) = turned {
page.landscape = l;
}
// A plotter's own papers (with their printable areas) come first.
let device_paper = super::plotters::page_device(cmd, p, &mut page)?;
// A page that keeps its paper keeps its margins, and the margins are measured against the
// sheet's axes: turning the orientation turns them too (#1266). Explicit margins are already
// on the new sheet's axes.
if turned.is_some() && !device_paper && p.get("margins").is_none() {
page.margins_mm =
if page.landscape { super::plotters::landscape_margins(page.margins_mm) } else { super::plotters::portrait_margins(page.margins_mm) };
}
if let Some(paper) = p.get("paper").filter(|_| !device_paper) {
let n = paper.as_str().ok_or_else(|| bad(cmd, "`paper` must be a paper name"))?;
let ps = cadcraft_render::paper_size(n).ok_or_else(|| {
@@ -901,6 +723,9 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
(None, None) if p.get("width").is_none() && p.get("height").is_none() => {}
_ => return Err(bad(cmd, "`width` and `height` (mm, 0-5080) are both required for a custom size")),
}
if let Some(l) = p.get("landscape").and_then(Value::as_bool) {
page.landscape = l;
}
// Paper units: what one paper-space unit is on this layout, whatever the paper's own family
// (an ARCH D sheet can be drawn in millimetres, #3249).
if let Some(v) = p.get("paperUnits") {
@@ -942,8 +767,6 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
}
if let Some(v) = str_param(p, "plotStyleTable") {
page.plot_style_table = v.chars().take(260).collect();
// A table from the user's plot style folder travels with the drawing.
plotstyle::keep_folder_copy(s.doc_mut()?, &page.plot_style_table);
}
if let Some(v) = p.get("displayPlotStyles").and_then(Value::as_bool) {
page.show_plot_styles = v;
@@ -1067,14 +890,14 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
if is_image && sheets.as_ref().is_some_and(|names| names.len() > 1) {
return Err(bad(cmd, "`layouts` with several sheets needs PDF output; PNG and SVG hold one sheet, so plot each layout separately"));
}
let (bytes, notes) = super::file::plot_noted(hook, s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?;
let bytes = hook(s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?;
let layout = match &sheets {
Some(names) => names.first().cloned().unwrap_or_default(),
None => space.tab_name().to_string(),
};
let pages = sheets.as_ref().map_or(1, Vec::len);
let format = opts.get("output").and_then(Value::as_str).map(str::to_ascii_lowercase).unwrap_or_else(|| "pdf".into());
let r = match str_param(p, "path") {
match str_param(p, "path") {
Some(_path) => {
#[cfg(not(target_arch = "wasm32"))]
{
@@ -1086,45 +909,16 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
let mut r = json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_new_folder(s, &mut r, folder);
super::file::report_notes(s, &mut r, notes);
r
Ok(r)
}
#[cfg(target_arch = "wasm32")]
{
super::exchange::deliver_file(cmd, _path, &bytes, super::file::deliver())?;
let mut r = json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_notes(s, &mut r, notes);
r
}
}
None => {
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_notes(s, &mut r, notes);
r
}
};
// A table from the user's plot style folder that a plot used travels with the drawing, as
// one chosen in a page setup does, and Model, which has no page setup dialog of its own,
// remembers the table it last plotted with. A preview (an image with no file) changes nothing,
// and so does a plot whose output was refused or failed: this runs only once it is written.
if let Some(table) = str_param(p, "plotStyleTable")
&& (str_param(p, "path").is_some() || !is_image)
{
// Model is the sheet plotted when `layouts` names it alone, whatever tab is showing.
let model = match sheets.as_deref() {
Some(names) => matches!(names, [only] if only.eq_ignore_ascii_case("model")),
None => matches!(space, Space::Model),
};
// Checked first: `doc_mut` copies the drawing, which records an undo step even for no change.
if plotstyle::table_choice_changes(s.doc()?, table, model) {
let d = s.doc_mut()?;
let changed = if model { plotstyle::set_model_table(d, table) } else { plotstyle::keep_folder_copy(d, table) };
if changed {
s.touch();
Ok(json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format }))
}
}
None => Ok(json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format })),
}
Ok(r)
}
/// The model-space rectangle a plot of `plotArea` covers: `extents` (default) plots everything,
+40 -296
View File
@@ -1,16 +1,9 @@
//! Plot styles: PLOTSTYLE (an object's or the current named plot style) and STYLESMANAGER (the
//! plot style tables: list, view, create, edit, rename, delete, load and save in our own file
//! format).
//! plot style tables: list, view, create, edit, delete, load and save in our own file format).
//!
//! A table lives in the user's plot style folder ([`super::super::plotstyle_folder`]), which
//! every drawing can use, or in the drawing (`Drawing::plot_style_tables`, saved with it). The
//! drawing's table wins over a folder's of the same name, and both over a built-in one. A page
//! setup (a layout's or Model's) or a plot that uses a folder table takes a copy of it into the
//! drawing, which from then on plots with its copy whatever happens to the file. Editing a
//! built-in table stores an edited copy in the drawing.
//!
//! Changes to the folder's files are written at once: UNDO takes back the drawing's copy, not the
//! file.
//! Tables the drawing keeps live in `Drawing::plot_style_tables` and are saved with it; they
//! shadow built-in tables of the same name. Editing a built-in table stores an edited copy in
//! the drawing.
use cadcraft_doc::{Drawing, PlotStyle, PlotStyleKind, PlotStyleTable};
use serde_json::{Value, json};
@@ -28,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("stylesmanager", "Plot Style Manager...", run_stylesmanager)
.menu(&["File", "Plot Styles..."])
.params(
"{action?: list (default)|get|new|set|rename|delete|load|save|reload, name?: table (\"x.ctb\"/\"x.stb\"), where?: folder|drawing (new, load: default drawing; get, set, rename, delete: default the drawing's table, else the folder's), kind?: colorDependent|named (new), from?: table to copy (new), fromWhere?: folder|drawing (new: where `from` is; default the drawing's table, else the folder's, else built-in), description?, style?: {name, color?: \"#rrggbb\"|null, grayscale?, screening?: 0-100, linetype?: name|null, lineweight?: mm|null, end?, join?, fill?, description?} (set), removeStyle?: name (set, named tables), to?: new name (rename), path? (load/save; save without one returns `text`), text? (load)} (folder tables are files in the settings folder's `plotstyles` folder; list reports it in `folder`)",
"{action?: list (default)|get|new|set|delete|load|save, name?: table (\"x.ctb\"/\"x.stb\"), kind?: colorDependent|named (new), from?: table to copy (new), description?, style?: {name, color?: \"#rrggbb\"|null, grayscale?, screening?: 0-100, linetype?: name|null, lineweight?: mm|null, end?, join?, fill?, description?} (set), removeStyle?: name (set, named tables), path? (load/save; save without one returns `text`), text? (load)}",
),
]
}
@@ -100,165 +93,18 @@ fn run_plotstyle(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- STYLESMANAGER ----------
fn in_drawing(d: &Drawing, name: &str) -> bool {
d.plot_style_tables.iter().any(|x| x.name.eq_ignore_ascii_case(name.trim()))
}
fn in_folder(name: &str) -> bool {
cadcraft_doc::plot_style_folder_table(name).is_some()
}
fn table_summary(d: &Drawing, t: &PlotStyleTable) -> Value {
let drawing = in_drawing(d, &t.name);
let folder = in_folder(&t.name);
let in_drawing = d.plot_style_tables.iter().any(|x| x.name.eq_ignore_ascii_case(&t.name));
json!({
"name": t.name,
"description": t.description,
"kind": if t.is_color_dependent() { "colorDependent" } else { "named" },
"styles": t.styles.len(),
"source": if drawing { "drawing" } else if folder { "folder" } else { "builtin" },
"inFolder": folder,
"inDrawing": drawing,
"builtin": PlotStyleTable::builtin(&t.name).is_some() && !drawing && !folder,
"inDrawing": in_drawing,
"builtin": PlotStyleTable::builtin(&t.name).is_some() && !in_drawing,
})
}
/// Where a table goes or comes from.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Where {
Folder,
Drawing,
}
fn where_param(cmd: &str, p: &Value) -> Result<Option<Where>> {
place_param(cmd, p, "where")
}
/// A place parameter (`where`, or `fromWhere` for `new`'s `from`): folder or drawing.
fn place_param(cmd: &str, p: &Value, key: &str) -> Result<Option<Where>> {
match str_param(p, key).map(str::to_ascii_lowercase).as_deref() {
None => Ok(None),
Some("folder") => Ok(Some(Where::Folder)),
Some("drawing") => Ok(Some(Where::Drawing)),
Some(_) => Err(bad(cmd, format!("`{key}` must be folder or drawing"))),
}
}
/// `name` with the ending a table of `t`'s kind needs (added when it has none), at most 255
/// characters with it: the length every action that looks a table up reads (`table_name`).
fn with_ending(cmd: &str, t: &PlotStyleTable, name: &str) -> Result<String> {
let ext = if t.is_color_dependent() { ".ctb" } else { ".stb" };
let lower = name.to_ascii_lowercase();
if !lower.ends_with(ext) && (lower.ends_with(".ctb") || lower.ends_with(".stb")) {
return Err(bad(cmd, format!("a {} table's name ends in {ext}", if ext == ".ctb" { "colour-dependent" } else { "named" })));
}
let full = if lower.ends_with(ext) { name.to_string() } else { format!("{name}{ext}") };
if full.chars().count() > 255 {
return Err(bad(cmd, "a plot style table's name is at most 255 characters, with its ending"));
}
Ok(full)
}
/// Write `t` to the plot style folder.
fn write_folder(cmd: &str, t: &PlotStyleTable) -> Result<()> {
super::super::plotstyle_folder::write(t).map_err(|e| bad(cmd, e))
}
/// Copy the folder's table `name` into `d` when `d` has no table of that name: a layout that
/// chooses a folder table takes it into the drawing, and the drawing then plots with its copy
/// whatever later happens to the file. A table the drawing already has is left as it is.
/// Returns whether a copy was taken.
pub(super) fn keep_folder_copy(d: &mut Drawing, name: &str) -> bool {
let name = name.trim();
if !needs_folder_copy(d, name) {
return false;
}
match cadcraft_doc::plot_style_folder_table(name) {
Some(t) => {
store(d, t);
true
}
None => false,
}
}
/// Whether the drawing lacks the folder table `name`, which `keep_folder_copy` would copy in.
fn needs_folder_copy(d: &Drawing, name: &str) -> bool {
let name = name.trim();
!cadcraft_doc::no_plot_style_table(name) && !in_drawing(d, name) && cadcraft_doc::plot_style_folder_table(name).is_some()
}
/// `name` as Model's page setup keeps it: empty for no table.
fn model_name(name: &str) -> String {
let name: String = name.trim().chars().take(260).collect();
if cadcraft_doc::no_plot_style_table(&name) { String::new() } else { name }
}
/// Whether Model's table is something other than `name` (as `model_name` keeps it).
fn model_differs(d: &Drawing, name: &str) -> bool {
let current = d.model_page.as_ref().map(|p| p.plot_style_table.trim()).unwrap_or_default();
!current.eq_ignore_ascii_case(name)
}
/// Whether choosing `name` would change `d`: Model's table (`model`), or a folder copy the
/// drawing lacks. Read first, as changing the drawing copies it and records an undo step.
pub(crate) fn table_choice_changes(d: &Drawing, name: &str, model: bool) -> bool {
(model && model_differs(d, &model_name(name))) || needs_folder_copy(d, name)
}
/// Remember `name` as Model's plot style table. Model keeps no other page settings here, so its
/// page setup is the one the DXF writer gives it otherwise, with this table; `"None"` or an empty
/// name clears it. A folder table is copied into the drawing. Returns whether anything changed.
pub(crate) fn set_model_table(d: &mut Drawing, name: &str) -> bool {
let name = model_name(name);
let changed = model_differs(d, &name);
if changed {
d.model_page
.get_or_insert_with(|| cadcraft_doc::PageSetup { plot_area: "extents".into(), scale_to_fit: true, ..Default::default() })
.plot_style_table = name.clone();
}
keep_folder_copy(d, &name) || changed
}
/// Copy into `d` every folder table its page setups (each layout's and Model's) use that it
/// doesn't have yet, so a saved drawing carries all its plot style tables (like the built-in
/// ones, it then plots the same on a computer without the files). Returns whether anything was
/// copied.
pub(crate) fn keep_used_folder_copies(d: &mut Drawing) -> bool {
let used: Vec<String> = d.layouts.iter().map(|l| &l.page).chain(d.model_page.as_ref()).map(|page| page.plot_style_table.clone()).collect();
let mut copied = false;
for name in used {
copied |= keep_folder_copy(d, &name);
}
copied
}
/// Which table `name` an action works on: `where` when given, else the drawing's (the one its
/// layouts plot with), else the folder's. `None` for a table in neither (a built-in one).
fn place_of(cmd: &str, s: &Session, p: &Value, name: &str) -> Result<Option<Where>> {
Ok(match where_param(cmd, p)? {
Some(w) => Some(w),
None if in_drawing(s.doc()?, name) => Some(Where::Drawing),
None if in_folder(name) => Some(Where::Folder),
None => None,
})
}
/// Table `name` from `place`, or as the drawing sees it when `place` is `None`.
fn table_at(cmd: &str, d: &Drawing, name: &str, place: Option<Where>) -> Result<PlotStyleTable> {
let found = match place {
Some(Where::Drawing) => d.plot_style_tables.iter().find(|t| t.name.eq_ignore_ascii_case(name.trim())).cloned(),
Some(Where::Folder) => cadcraft_doc::plot_style_folder_table(name.trim()),
None => cadcraft_doc::plot_style_table(d, name),
};
let here = match place {
Some(Where::Drawing) => " in the drawing",
Some(Where::Folder) => " in the plot style folder",
None => "",
};
found.ok_or_else(|| bad(cmd, format!("no plot style table `{name}`{here}")))
}
fn table_name(cmd: &str, p: &Value) -> Result<String> {
let n = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "`name` (the table) is required"))?;
Ok(n.chars().take(255).collect())
@@ -346,30 +192,18 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "stylesmanager";
let action = str_param(p, "action").unwrap_or("list").to_ascii_lowercase();
match action.as_str() {
"list" | "reload" => {
if action == "reload" {
super::super::plotstyle_folder::reload();
for st in &mut s.docs {
st.revision += 1;
}
}
"list" => {
let d = s.doc()?;
let tables: Vec<Value> = cadcraft_doc::plot_style_table_names(d)
.iter()
.filter_map(|n| cadcraft_doc::plot_style_table(d, n))
.map(|t| table_summary(d, &t))
.collect();
Ok(json!({
"tables": tables,
"folder": super::super::plotstyle_folder::location(),
"warnings": super::super::plotstyle_folder::warnings(),
}))
Ok(json!({ "tables": tables }))
}
"get" => {
let name = table_name(cmd, p)?;
let place = where_param(cmd, p)?;
let d = s.doc()?;
let t = table_at(cmd, d, &name, place)?;
let t = find_table(cmd, d, &table_name(cmd, p)?)?;
let mut v = serde_json::to_value(&t).unwrap_or(Value::Null);
if let (Some(o), Value::Object(sum)) = (v.as_object_mut(), table_summary(d, &t)) {
o.insert("inDrawing".into(), sum.get("inDrawing").cloned().unwrap_or(Value::Null));
@@ -381,8 +215,7 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
let mut name = table_name(cmd, p)?;
let d = s.doc()?;
let mut t = match str_param(p, "from") {
// A name both the drawing and the folder hold: `fromWhere` says which to copy.
Some(from) => table_at(cmd, d, from, place_param(cmd, p, "fromWhere")?)?,
Some(from) => find_table(cmd, d, from)?,
None => {
let named = match str_param(p, "kind").map(str::to_ascii_lowercase).as_deref() {
None if name.to_ascii_lowercase().ends_with(".stb") => true,
@@ -393,13 +226,15 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
if named { PlotStyleTable::named("", "", Vec::new()) } else { PlotStyleTable::color_dependent("", "", |_| None) }
}
};
name = with_ending(cmd, &t, &name)?;
let place = where_param(cmd, p)?.unwrap_or(Where::Drawing);
let taken = match place {
Where::Folder => in_folder(&name),
Where::Drawing => in_drawing(d, &name),
};
if taken {
let ext = if t.is_color_dependent() { ".ctb" } else { ".stb" };
let lower = name.to_ascii_lowercase();
if !lower.ends_with(ext) {
if lower.ends_with(".ctb") || lower.ends_with(".stb") {
return Err(bad(cmd, format!("a {} table's name ends in {ext}", if ext == ".ctb" { "colour-dependent" } else { "named" })));
}
name.push_str(ext);
}
if d.plot_style_tables.iter().any(|x| x.name.eq_ignore_ascii_case(&name)) {
return Err(bad(cmd, format!("plot style table `{name}` already exists")));
}
t.name = name;
@@ -407,19 +242,13 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
t.description = desc.chars().take(255).collect();
}
let t = t.sanitized();
match place {
Where::Folder => {
write_folder(cmd, &t)?;
s.touch();
}
Where::Drawing => store(s.doc_mut()?, t.clone()),
}
Ok(table_summary(s.doc()?, &t))
let out = table_summary(d, &t);
store(s.doc_mut()?, t);
Ok(out)
}
"set" => {
let name = table_name(cmd, p)?;
let place = place_of(cmd, s, p, &name)?;
let mut t = table_at(cmd, s.doc()?, &name, place)?;
let mut t = find_table(cmd, s.doc()?, &name)?;
if let Some(desc) = str_param(p, "description") {
t.description = desc.chars().take(255).collect();
}
@@ -477,18 +306,19 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
o.insert("removedStyle".into(), json!(r.trim()));
}
}
// The folder's file is written, and the drawings that keep a copy of it keep their copy;
// a built-in table edited keeps an edited copy in the drawing.
if place == Some(Where::Folder) {
write_folder(cmd, &t)?;
s.touch();
} else {
store(s.doc_mut()?, t);
}
store(s.doc_mut()?, t);
Ok(out)
}
"rename" => run_rename(s, p, cmd),
"delete" => run_delete(s, p, cmd),
"delete" => {
let name = table_name(cmd, p)?;
let d = s.doc_mut()?;
let before = d.plot_style_tables.len();
d.plot_style_tables.retain(|t| !t.name.eq_ignore_ascii_case(&name));
if d.plot_style_tables.len() == before {
return Err(bad(cmd, format!("the drawing keeps no plot style table `{name}` (built-in tables can't be deleted)")));
}
Ok(json!({ "deleted": name }))
}
"load" => {
let text = match (str_param(p, "text"), str_param(p, "path")) {
(Some(t), _) => t.to_string(),
@@ -512,15 +342,9 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
if t.name.is_empty() {
return Err(bad(cmd, "the table has no name: pass `name`"));
}
t.name = with_ending(cmd, &t, &t.name.clone())?;
match where_param(cmd, p)?.unwrap_or(Where::Drawing) {
Where::Folder => {
write_folder(cmd, &t)?;
s.touch();
}
Where::Drawing => store(s.doc_mut()?, t.clone()),
}
Ok(table_summary(s.doc()?, &t))
let out = table_summary(s.doc()?, &t);
store(s.doc_mut()?, t);
Ok(out)
}
"save" => {
let name = table_name(cmd, p)?;
@@ -540,86 +364,6 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
other => Err(bad(cmd, format!("unknown action `{other}` (list, get, new, set, rename, delete, load, save, reload)"))),
other => Err(bad(cmd, format!("unknown action `{other}` (list, get, new, set, delete, load, save)"))),
}
}
/// STYLESMANAGER rename: the folder's file, or the drawing's table and the layouts (and Model)
/// of this drawing that use it. Renaming the file leaves the drawings' copies as they are.
fn run_rename(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
let name = table_name(cmd, p)?;
let to = str_param(p, "to").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "`to` (the new name) is required"))?;
let Some(place) = place_of(cmd, s, p, &name)? else {
return Err(bad(
cmd,
format!("no plot style table `{name}` in the folder or the drawing (built-in tables can't be renamed: copy one with `new` and `from`)"),
));
};
let mut t = table_at(cmd, s.doc()?, &name, Some(place))?;
let old = t.name.clone();
let to = with_ending(cmd, &t, to)?;
let same = to.eq_ignore_ascii_case(&old);
let taken = match place {
Where::Folder => in_folder(&to),
Where::Drawing => in_drawing(s.doc()?, &to),
};
if !same && taken {
return Err(bad(cmd, format!("plot style table `{to}` already exists")));
}
t.name = to.clone();
let mut layouts = 0usize;
match place {
Where::Folder => {
write_folder(cmd, &t)?;
if !same && let Err(e) = super::super::plotstyle_folder::delete(&old) {
// Take the new file back, so the table isn't held twice and the rename can be tried again.
let undone = super::super::plotstyle_folder::delete(&to);
let left = if undone.is_ok() { "the table keeps its old name" } else { "both files now hold the table" };
return Err(bad(cmd, format!("can't remove `{old}` from the plot style folder ({e}); {left}")));
}
s.touch();
}
Where::Drawing => {
let d = s.doc_mut()?;
for x in d.plot_style_tables.iter_mut().filter(|x| x.name.eq_ignore_ascii_case(&old)) {
x.name = to.clone();
}
for l in d.layouts.iter_mut().filter(|l| l.page.plot_style_table.trim().eq_ignore_ascii_case(&old)) {
l.page.plot_style_table = to.clone();
layouts += 1;
}
if let Some(m) = d.model_page.as_mut().filter(|m| m.plot_style_table.trim().eq_ignore_ascii_case(&old)) {
m.plot_style_table = to.clone();
}
}
}
Ok(json!({ "name": to, "renamed": old, "layouts": layouts, "where": if place == Where::Folder { "folder" } else { "drawing" } }))
}
/// STYLESMANAGER delete: the drawing's table or the folder's file.
fn run_delete(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
let name = table_name(cmd, p)?;
let place = match where_param(cmd, p)? {
Some(w) => w,
None if in_drawing(s.doc()?, &name) => Where::Drawing,
None if in_folder(&name) => Where::Folder,
None => {
return Err(bad(cmd, format!("no plot style table `{name}` in the folder or the drawing (built-in tables can't be deleted)")));
}
};
match place {
Where::Folder => {
super::super::plotstyle_folder::delete(&name).map_err(|e| bad(cmd, e))?;
s.touch();
}
Where::Drawing => {
let d = s.doc_mut()?;
let before = d.plot_style_tables.len();
d.plot_style_tables.retain(|t| !t.name.eq_ignore_ascii_case(&name));
if d.plot_style_tables.len() == before {
return Err(bad(cmd, format!("the drawing keeps no plot style table `{name}` (built-in tables can't be deleted)")));
}
}
}
Ok(json!({ "deleted": name, "where": if place == Where::Folder { "folder" } else { "drawing" } }))
}
-252
View File
@@ -88,7 +88,6 @@ fn new_layout_from_the_menu_asks_for_a_name() {
s.cmdline("Layout1").unwrap();
assert!(s.running.is_some(), "a taken name asks again");
s.cmdline("Sheet A").unwrap();
// The name is all it asks: no model area, no tab change.
assert!(s.running.is_none());
s.start("layout.new").unwrap();
s.cmdline("").unwrap();
@@ -96,141 +95,6 @@ fn new_layout_from_the_menu_asks_for_a_name() {
assert!(d.layout("Sheet A").is_some() && d.layout("Layout3").is_some(), "Enter takes the default name");
}
/// LAYOUT.NEWAREA asks the name, then the area; Enter takes the whole drawing.
#[test]
fn new_layout_from_area_asks_a_name_then_the_area() {
let mut s = session_with_model();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet A").unwrap();
assert!(s.running.is_some() && s.current_prompt().is_some_and(|p| p.message.contains("first corner of the model area")));
s.cmdline("").unwrap();
assert!(s.running.is_none());
assert!(s.doc().unwrap().layout("Sheet A").is_some());
}
/// The viewport of layout `name`.
fn only_viewport(s: &Session, name: &str) -> Viewport {
let v = viewports(s, name);
assert_eq!(v.len(), 1, "one viewport");
v.into_iter().next().map(|(_, v)| v).unwrap()
}
/// A `window` zooms the new layout's viewport to that part of the model.
#[test]
fn a_new_layout_can_show_a_window_of_the_model() {
let mut s = session_with_model();
s.execute("layout.new", &json!({"name": "Sheet W", "window": [[10, 10], [30, 20]]})).unwrap();
let v = only_viewport(&s, "Sheet W");
assert!(v.view_center.dist(Vec2::new(20.0, 15.0)) < 1e-9, "centred on the window: {:?}", v.view_center);
let aspect = v.width / v.height;
assert!(v.view_height >= 10.0 && v.view_height * aspect >= 20.0, "the whole window is in view");
assert!(v.view_height <= (10.0_f64).max(20.0 / aspect) * 1.02 + 1e-9, "and not much more: {}", v.view_height);
// Without a window the viewport shows the model extents, as before.
s.execute("layout.new", &json!({"name": "Sheet E"})).unwrap();
let e = only_viewport(&s, "Sheet E");
assert!(e.view_height > v.view_height * 2.0, "extents are larger than the window");
}
/// A window without area, or not two corners, is an error that leaves no layout behind.
#[test]
fn a_bad_layout_window_adds_no_layout() {
let mut s = session_with_model();
let before = s.doc().unwrap().layouts.len();
for w in [
json!([[1, 1], [1, 9]]),
json!([[1, 1], [9, 1]]),
json!([[1, 1]]),
json!("all"),
json!([[1, 1], ["a", 2]]),
json!([[f64::MAX, 0], [-f64::MAX, 1]]),
] {
assert!(s.execute("layout.new", &json!({"name": "Bad", "window": w})).is_err(), "{w}");
}
assert_eq!(s.doc().unwrap().layouts.len(), before, "no layout is left behind");
}
/// The interactive command shows the Model tab, takes two corners and shows the new layout.
#[test]
fn new_layout_picks_the_model_area_in_the_model_tab() {
let mut s = session_with_model();
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet P").unwrap();
assert_eq!(s.space(), Space::Model, "the Model tab is shown to pick the area");
s.cmdline("10,10").unwrap();
assert!(s.current_prompt().is_some_and(|p| p.message == "Specify opposite corner"));
// A window without width re-asks for the first corner and adds nothing.
s.cmdline("10,30").unwrap();
assert!(s.current_prompt().is_some_and(|p| p.message.contains("first corner")), "{:?}", s.current_prompt().map(|p| p.message));
assert!(s.doc().unwrap().layout("Sheet P").is_none());
s.cmdline("10,10").unwrap();
s.cmdline("30,20").unwrap();
assert!(s.running.is_none());
assert_eq!(s.space(), Space::Paper("Sheet P".into()), "the new layout is shown");
let v = only_viewport(&s, "Sheet P");
assert!(v.view_center.dist(Vec2::new(20.0, 15.0)) < 1e-9, "{:?}", v.view_center);
s.undo().unwrap();
assert!(s.doc().unwrap().layout("Sheet P").is_none(), "one undo step");
}
/// A tab shown while the corners are picked ends the command instead of reading points in that space.
#[test]
fn new_layout_ends_if_another_tab_is_shown_while_picking() {
let mut s = session_with_model();
let before = s.doc().unwrap().layouts.len();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet T").unwrap();
assert_eq!(s.space(), Space::Model);
// A tab shown meanwhile: the next point must not be taken for a model corner.
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.cmdline("10,10").unwrap();
assert!(s.running.is_none(), "the command ended");
assert_eq!(s.layout_space(), Space::Paper("Layout1".into()), "the tab that was shown stays");
assert_eq!(s.doc().unwrap().layouts.len(), before, "no layout was added");
}
/// The opposite-corner prompt is a window corner, so ortho does not bend it.
#[test]
fn the_opposite_corner_is_not_bent_by_ortho() {
let mut s = session_with_model();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet O").unwrap();
s.cmdline("10,10").unwrap();
let p = s.current_prompt().unwrap();
assert!(p.corner && p.base == Some(Vec2::new(10.0, 10.0)), "a window's opposite corner prompt");
}
/// Esc puts back the tab the command started in and adds no layout.
#[test]
fn cancelling_new_layout_puts_the_tab_back() {
let mut s = session_with_model();
s.execute("layout.set", &json!({"name": "Layout2"})).unwrap();
let before = s.doc().unwrap().layouts.len();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet C").unwrap();
assert_eq!(s.space(), Space::Model);
s.cancel();
assert!(s.running.is_none());
assert_eq!(s.space(), Space::Paper("Layout2".into()), "back in the tab it started in: {:?}", s.log);
assert_eq!(s.doc().unwrap().layouts.len(), before);
// Esc at the name prompt changes nothing either.
s.start("layout.newarea").unwrap();
s.cancel();
assert_eq!(s.space(), Space::Paper("Layout2".into()));
}
/// Esc after the user chose another tab leaves that tab shown, not the one the command started in.
#[test]
fn cancelling_new_layout_keeps_a_tab_chosen_meanwhile() {
let mut s = session_with_model();
s.execute("layout.set", &json!({"name": "Layout2"})).unwrap();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet K").unwrap();
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.cancel();
assert!(s.running.is_none());
assert_eq!(s.space(), Space::Paper("Layout1".into()), "the tab chosen meanwhile stays: {:?}", s.log);
}
#[test]
fn mview_arrangements_and_interactive() {
let mut s = session_with_model();
@@ -602,119 +466,3 @@ fn plot_path_extension_picks_the_format_like_export() {
assert!(!dir.join("w.png").exists(), "nothing written when `output` and the path disagree");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn layout_set_frames_extents_away_from_origin() {
let mut s = Session::new();
s.doc_mut().unwrap().layouts.push(cadcraft_doc::Layout::new("COVER", 2));
let paper = Space::Paper("COVER".into());
s.doc_mut()
.unwrap()
.add(
&paper,
cadcraft_doc::Common::default(),
cadcraft_doc::EntityKind::Line(cadcraft_doc::Line {
a: cadcraft_geom::Vec3::new(12049.0, 4307.0, 0.0),
b: cadcraft_geom::Vec3::new(12449.0, 4594.0, 0.0),
}),
)
.unwrap();
s.execute("layout.set", &json!({"name": "COVER"})).unwrap();
let v = s.state().unwrap().view();
assert!((v.center.x - 12249.0).abs() < 1e-6, "center.x={}", v.center.x);
assert!((v.center.y - 4450.5).abs() < 1e-6, "center.y={}", v.center.y);
assert!(v.height >= 287.0, "height={}", v.height);
}
#[test]
fn layout_set_ignores_off_layer_entities_far_from_visible_content() {
let mut s = Session::new();
let paper = Space::Paper("COVER".into());
{
let doc = s.doc_mut().unwrap();
doc.layouts.push(cadcraft_doc::Layout::new("COVER", 2));
let mut off_layer = cadcraft_doc::Layer::new("HIDDEN_REF");
off_layer.on = false;
doc.layers.push(off_layer);
doc.add(
&paper,
cadcraft_doc::Common::default(),
cadcraft_doc::EntityKind::Polyline3d(cadcraft_doc::Polyline3d {
points: vec![
cadcraft_geom::Vec3::new(12000.0, 4000.0, 0.0),
cadcraft_geom::Vec3::new(12400.0, 4000.0, 0.0),
cadcraft_geom::Vec3::new(12400.0, 4300.0, 0.0),
cadcraft_geom::Vec3::new(12000.0, 4300.0, 0.0),
],
closed: true,
}),
)
.unwrap();
doc.add(
&paper,
cadcraft_doc::Common { layer: "HIDDEN_REF".into(), ..Default::default() },
cadcraft_doc::EntityKind::Line(cadcraft_doc::Line {
a: cadcraft_geom::Vec3::new(1_000_000.0, 1_000_000.0, 0.0),
b: cadcraft_geom::Vec3::new(1_000_100.0, 1_000_100.0, 0.0),
}),
)
.unwrap();
}
s.execute("layout.set", &json!({"name": "COVER"})).unwrap();
let v = s.state().unwrap().view();
assert!((v.center.x - 12200.0).abs() < 1e-6, "center.x={}", v.center.x);
assert!((v.center.y - 4150.0).abs() < 1e-6, "center.y={}", v.center.y);
assert!(v.height >= 300.0 && v.height < 2000.0, "height={}", v.height);
// Explicit ZOOM Extents continues to include entities on turned-off layers.
s.execute("zoom", &json!({"mode": "extents"})).unwrap();
let after_zoom = s.state().unwrap().view();
assert!(after_zoom.center.x > 100_000.0, "zoom extents center.x={}", after_zoom.center.x);
assert!(after_zoom.height > v.height * 100.0, "zoom extents height={}", after_zoom.height);
}
#[test]
fn layout_set_falls_back_to_sheet_when_all_layers_hidden() {
let mut s = Session::new();
let paper = Space::Paper("ALL_OFF".into());
{
let doc = s.doc_mut().unwrap();
doc.layouts.push(cadcraft_doc::Layout::new("ALL_OFF", 2));
let mut off_layer = cadcraft_doc::Layer::new("OFF_LAYER");
off_layer.on = false;
doc.layers.push(off_layer);
let mut frozen_layer = cadcraft_doc::Layer::new("FROZEN_LAYER");
frozen_layer.frozen = true;
doc.layers.push(frozen_layer);
doc.add(
&paper,
cadcraft_doc::Common { layer: "OFF_LAYER".into(), ..Default::default() },
cadcraft_doc::EntityKind::Line(cadcraft_doc::Line {
a: cadcraft_geom::Vec3::new(12000.0, 4000.0, 0.0),
b: cadcraft_geom::Vec3::new(12400.0, 4300.0, 0.0),
}),
)
.unwrap();
doc.add(
&paper,
cadcraft_doc::Common { layer: "FROZEN_LAYER".into(), ..Default::default() },
cadcraft_doc::EntityKind::Line(cadcraft_doc::Line {
a: cadcraft_geom::Vec3::new(15000.0, 5000.0, 0.0),
b: cadcraft_geom::Vec3::new(15400.0, 5300.0, 0.0),
}),
)
.unwrap();
}
let (expected_center, expected_height) = {
let doc = s.doc().unwrap();
let page = doc.layout("ALL_OFF").map(|l| l.page.clone()).unwrap_or_default();
let (w, h) = if page.landscape { (page.height_mm, page.width_mm) } else { (page.width_mm, page.height_mm) };
let unit = if doc.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 1.0 / 25.4 };
(cadcraft_geom::Vec2::new(w * unit / 2.0, h * unit / 2.0), h * unit * 1.15)
};
s.execute("layout.set", &json!({"name": "ALL_OFF"})).unwrap();
let v = s.state().unwrap().view();
assert!((v.center.x - expected_center.x).abs() < 1e-6, "center.x={}", v.center.x);
assert!((v.center.y - expected_center.y).abs() < 1e-6, "center.y={}", v.center.y);
assert!((v.height - expected_height).abs() < 1e-6, "height={}", v.height);
}

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