mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-29 21:59:47 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e040c88b9 | ||
|
|
525774865e | ||
|
|
39c33f8572 | ||
|
|
4c5cd40520 | ||
|
|
7b63755af8 |
@@ -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",
|
||||
|
||||
@@ -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.')
|
||||
@@ -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.
|
||||
|
||||
@@ -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,20 +0,0 @@
|
||||
name: Notify Services on Release Change
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
- unpublished
|
||||
- created
|
||||
- edited
|
||||
- deleted
|
||||
- prereleased
|
||||
- released
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
|
||||
secrets:
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
@@ -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' }}
|
||||
|
||||
|
||||
@@ -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
-1
@@ -87,7 +87,7 @@ Generated-in-code assets are original and have no file to list:
|
||||
| `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) | 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/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 chosen with a native speaker, full proofreading pending |
|
||||
| `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) |
|
||||
|
||||
|
||||
Generated
+84
-1280
File diff suppressed because it is too large
Load Diff
+32
-37
@@ -14,12 +14,11 @@ repository = "https://github.com/storytold/cadcraft"
|
||||
# internal
|
||||
cadcraft-geom = { path = "crates/geom" }
|
||||
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
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" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "219c1d0b14177af6f291395d6587f61a5e09043a" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
cadcraft-color = { path = "crates/color" }
|
||||
cadcraft-doc = { path = "crates/doc" }
|
||||
cadcraft-constraints = { path = "crates/constraints" }
|
||||
@@ -29,19 +28,19 @@ cadcraft-io = { path = "crates/io" }
|
||||
cadcraft-engine = { path = "crates/engine" }
|
||||
cadcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
cadcraft-mcp = { path = "crates/mcp" }
|
||||
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
# SVG/SVGZ import and export geometry (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
# Which paths stored in a drawing (xrefs, data links) may be opened.
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
|
||||
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
|
||||
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
|
||||
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
|
||||
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
|
||||
# Delimited text (CSV/TSV) parsing (shared Craft library).
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
clap_complete = "4.6.11"
|
||||
clap_mangen = { version = "0.3.3", features = ["env"] }
|
||||
@@ -75,12 +74,8 @@ encoding_rs = "0.8.35"
|
||||
quick-xml = "0.42"
|
||||
|
||||
# ui
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["serde"] }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
|
||||
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
|
||||
egui_extras = { version = "0.37", default-features = false }
|
||||
@@ -90,7 +85,7 @@ egui-wgpu = "0.37"
|
||||
# Monotonic time on native and web (performance.now on wasm).
|
||||
web-time = "1.1"
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
|
||||
rfd = "0.17"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
|
||||
@@ -122,23 +117,23 @@ debug = 0
|
||||
# PDF backends for craft-pdf: pinned to the same reviewed craft-libs revision as craft-pdf itself
|
||||
# (Cargo ignores dependency-local patches).
|
||||
[patch.crates-io]
|
||||
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
@@ -89,15 +89,9 @@
|
||||
line, prompts with clickable `[Keywords]`, AutoComplete, object snaps, polar tracking, ortho,
|
||||
direct distance entry, window and crossing selection, grips, and right-click-to-repeat behave
|
||||
the way decades of drafting habit expect.
|
||||
- **Open files.** DXF is read natively (R12 through 2018, with binary support from R13) and
|
||||
written as 2000 through 2018 (ASCII and binary). DWG files (R13 through 2018; R13 and R14
|
||||
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 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.
|
||||
- **Open files.** DXF is read and written natively (ASCII and binary, R12 through 2018), and DWG
|
||||
files (R13 through 2018) open and save through the open-source acadrust library. 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.
|
||||
- **Built for agents.** Every menu item, tool and prompt is a command. Agents can type at the
|
||||
@@ -120,7 +114,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 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 |
|
||||
| Files | DXF read (R12–2018, ASCII and binary) and write (R2000), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library) and write (R2000); 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) |
|
||||
| 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 |
|
||||
|
||||
@@ -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())
|
||||
@@ -66,7 +60,6 @@ fn install_io() {
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
|
||||
}
|
||||
|
||||
/// `path` as text, for the engine and io calls that take a file name as a string.
|
||||
|
||||
@@ -145,22 +145,15 @@ 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) {
|
||||
io.errln(format_args!("{m}"));
|
||||
}
|
||||
for note in cadcraft_engine::cmd::file::dwg_notes(d) {
|
||||
io.errln(format_args!("{note}"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
//! `convert` to DWG says, in one warning, how many linetypes the DWG keeps with only their first
|
||||
//! 255 dash elements (#1923, F-05); converting to DXF keeps them whole and says nothing.
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
fn cli(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
|
||||
}
|
||||
|
||||
/// A DXF with a 256-element linetype and a line drawn with it.
|
||||
fn dxf() -> String {
|
||||
let mut s = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLTYPE\n70\n1\n0\nLTYPE\n2\nLONG\n70\n0\n3\nLong\n72\n65\n73\n256\n40\n192\n");
|
||||
for i in 0..256 {
|
||||
s.push_str(if i % 2 == 0 { "49\n1\n74\n0\n" } else { "49\n-0.5\n74\n0\n" });
|
||||
}
|
||||
s.push_str("0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n6\nLONG\n10\n0\n20\n0\n11\n10\n21\n0\n0\nENDSEC\n0\nEOF\n");
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_dwg_notes_the_linetypes_it_cuts() {
|
||||
let dir = std::env::temp_dir().join(format!("cc-cli-ltype-dwg-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let source = dir.join("long.dxf");
|
||||
std::fs::write(&source, dxf()).unwrap();
|
||||
let source = source.to_str().unwrap();
|
||||
let notes =
|
||||
|out: &Output| String::from_utf8_lossy(&out.stderr).lines().filter(|l| l.contains("dash elements")).map(str::to_string).collect::<Vec<_>>();
|
||||
|
||||
let out = cli(&["convert", source, dir.join("long.dwg").to_str().unwrap()]);
|
||||
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
|
||||
assert!(
|
||||
matches!(notes(&out).as_slice(), [note] if note.contains("1 linetype") && note.contains("255")),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
|
||||
let out = cli(&["convert", source, dir.join("copy.dxf").to_str().unwrap()]);
|
||||
assert!(out.status.success() && notes(&out).is_empty(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -1,10 +1,6 @@
|
||||
mod cli;
|
||||
mod dash_limit_note;
|
||||
mod drafting_spacing;
|
||||
mod help;
|
||||
// DWG output needs craft-dwg's bridge.
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
mod ltype_dwg_note;
|
||||
mod mcp_connect;
|
||||
mod pdf_import;
|
||||
mod skipped_records;
|
||||
|
||||
@@ -21,8 +21,8 @@ cadcraft-io = { workspace = true }
|
||||
cadcraft-fonts = { workspace = true }
|
||||
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
|
||||
# The page command API (storytold/craft-libs#413): window.cadcraft over the control channel.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
|
||||
egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -54,12 +54,11 @@ mod web {
|
||||
if let Some(bridge) = &self.2 {
|
||||
bridge.report_dirty(&self.0);
|
||||
}
|
||||
self.0.close_path(ctx);
|
||||
}
|
||||
/// Forward raw input to the web `CadApp` and hand the frame's root values to the UI runtime.
|
||||
/// Forward raw input to the web `CadApp` and capture Tab at the command line.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.0.raw_input_hook(ctx, raw);
|
||||
self.0.before_input(ctx);
|
||||
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
|
||||
}
|
||||
/// Preferences and validated panel placement survive reloads; egui memory is not kept.
|
||||
fn save(&mut self, storage: &mut dyn eframe::Storage) {
|
||||
@@ -120,12 +119,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())
|
||||
@@ -141,7 +134,6 @@ mod web {
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
|
||||
let Some(canvas) = app_canvas() else {
|
||||
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
|
||||
return;
|
||||
@@ -174,7 +166,6 @@ mod web {
|
||||
canvas,
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
cadcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
|
||||
// Embedded, the host sends the drawing: start on the Start tab, not Drawing1.
|
||||
let session = if app_bridge.is_some() { Session::empty() } else { Session::new() };
|
||||
let control = crate::api::install(cc.egui_ctx.clone());
|
||||
|
||||
@@ -94,7 +94,7 @@ mod tests {
|
||||
let mut ui = UiState::default();
|
||||
let before = serde_json::to_value(&ui).unwrap();
|
||||
let mut invalid = ui.clone();
|
||||
invalid.docking = cadcraft_ui_egui::docking::Workspace::default();
|
||||
invalid.docking.layout.root = None;
|
||||
assert!(save(&invalid).is_err());
|
||||
let mut record: Value = serde_json::from_str(&save(&ui).unwrap()).unwrap();
|
||||
record["docking"] = serde_json::to_value(&invalid.docking).unwrap();
|
||||
|
||||
@@ -24,7 +24,6 @@ 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`).
|
||||
@@ -42,18 +41,22 @@ winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
zbus = { version = "=5.19.0", default-features = false, features = ["async-io", "blocking-api"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# Floating panels open in their own OS windows on the desktop; the web build keeps them in the page.
|
||||
craft-ui = { workspace = true, features = ["native-windows"] }
|
||||
craft-update = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
sys-locale = "0.3"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# `title_bar::sync_movable`: AppKit's title-band drag leaves the window still under the row's
|
||||
# controls and under floating panels.
|
||||
craft-window = { workspace = true }
|
||||
muda = { version = "0.21", default-features = false }
|
||||
# Quit CADCraft as a close request of the main window, so the unsaved-changes question runs (#2157).
|
||||
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: the system's Reduce motion
|
||||
# (system_animations.rs). Already in Cargo.lock through muda.
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility"] }
|
||||
# The same winit eframe uses (the storytold fork, patched in the workspace).
|
||||
# The same winit eframe uses (the storytold fork, patched in the workspace): its opt-in that turns
|
||||
# AppKit's terminate (Cmd+Q, Dock Quit) into a close request, so unsaved changes are asked about.
|
||||
# `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
|
||||
|
||||
@@ -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,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);
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
+62
-75
@@ -61,6 +61,9 @@ struct App {
|
||||
/// `CADCRAFT_NO_NATIVE_MENU`: the menus stay inside the window.
|
||||
#[cfg(target_os = "macos")]
|
||||
menus_in_window: bool,
|
||||
/// The `movable` flag last set on the main window.
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: Option<bool>,
|
||||
/// Drawings and quit requests from Finder, the Dock and `open -a` (see `apple_events`).
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events: fmv_macos_events::Inbox,
|
||||
@@ -138,18 +141,17 @@ impl eframe::App for App {
|
||||
if std::mem::take(&mut self.cad.quit_requested) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
self.cad.close_path(ctx);
|
||||
}
|
||||
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and hand the frame's root values to the UI
|
||||
/// runtime.
|
||||
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and capture Tab at the command line.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
follow_desktop(raw, self.desktop_theme.current());
|
||||
self.cad.raw_input_hook(ctx, raw);
|
||||
self.cad.before_input(ctx);
|
||||
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
|
||||
}
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
cadcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
self.cad.guarded_ui(ui);
|
||||
#[cfg(target_os = "macos")]
|
||||
craft_window::title_bar::sync_movable(ui.ctx(), &mut self.movable);
|
||||
}
|
||||
/// A normal exit: the workspace is saved, and this run's autosave files are not needed (a
|
||||
/// crash leaves them for recovery).
|
||||
@@ -182,12 +184,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())
|
||||
@@ -203,7 +199,6 @@ pub fn install_io() {
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
|
||||
}
|
||||
|
||||
fn services() -> Services {
|
||||
@@ -307,15 +302,17 @@ 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 ([`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()))
|
||||
.with_inner_size([1600.0, 1000.0])
|
||||
.with_min_inner_size(MIN_INNER_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
.with_app_id(os_window::app_id());
|
||||
fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
|
||||
eframe::NativeOptions {
|
||||
viewport: cadcraft_ui_egui::framework::apply_frame(viewport, frame),
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title(os_window::name_for(os_window::identity()))
|
||||
.with_inner_size([1600.0, 1000.0])
|
||||
.with_min_inner_size(MIN_INNER_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
.with_fullsize_content_view(true)
|
||||
.with_titlebar_shown(false)
|
||||
.with_title_shown(false)
|
||||
.with_app_id(os_window::app_id()),
|
||||
// The size, position and maximized state are kept between sessions (#2595); eframe keeps a
|
||||
// restored window on the monitors that are connected now.
|
||||
persist_window: true,
|
||||
@@ -393,23 +390,14 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit
|
||||
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1))
|
||||
}
|
||||
|
||||
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
|
||||
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
|
||||
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
|
||||
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
|
||||
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
|
||||
build_flavor::needs_native_error(flavor, desktop_session) && !macos
|
||||
}
|
||||
|
||||
/// A refused launch profile ends with a native dialog where a modal renders without the app's run
|
||||
/// loop (Windows, X11/Wayland), and with the reason on standard error everywhere else: a headless
|
||||
/// runner must never wait for a modal, and on macOS one opened before the event loop never appears.
|
||||
/// A refused launch profile ends with a native dialog on a desktop, and with the reason on standard
|
||||
/// error everywhere else (a headless runner must never wait for a modal).
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
eprintln!("CADCraft launch profile: {error}");
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
|
||||
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
eprintln!("CADCraft launch profile: {error}");
|
||||
return;
|
||||
@@ -428,30 +416,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.
|
||||
@@ -551,9 +544,6 @@ fn main() -> eframe::Result {
|
||||
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);
|
||||
let persistence_path = vars
|
||||
.portable_storage_file
|
||||
.clone()
|
||||
@@ -563,7 +553,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()), stencil, frame.as_ref())
|
||||
..window_options(restores_window(persistence_path.as_deref()), stencil)
|
||||
};
|
||||
if let Some(icon) = app_icon() {
|
||||
options.viewport = options.viewport.with_icon(icon);
|
||||
@@ -586,12 +576,22 @@ fn main() -> eframe::Result {
|
||||
// manager showed a "no" cursor. Run through XWayland when it's there; CADCRAFT_WAYLAND=1
|
||||
// keeps the native Wayland backend.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if forced_x11 {
|
||||
if std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On {
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
use winit::platform::x11::EventLoopBuilderExtX11;
|
||||
b.with_x11();
|
||||
}));
|
||||
}
|
||||
// macOS: Quit CADCraft (Cmd+Q), the Dock's Quit and logout end the app through AppKit's
|
||||
// terminate, which would skip the unsaved-changes prompt (#2157). winit turns each into a
|
||||
// close request for the window instead, so it asks first, as the close button does.
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
use winit::platform::macos::EventLoopBuilderExtMacOS;
|
||||
b.with_close_requested_on_terminate(true);
|
||||
}));
|
||||
}
|
||||
// Registered before the event loop starts, so it catches the Finder event that launched us as
|
||||
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -604,7 +604,6 @@ fn main() -> eframe::Result {
|
||||
os_window::name_for(os_window::identity()),
|
||||
options,
|
||||
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
|
||||
// it, so nothing after `run_native` can be relied on there.
|
||||
@@ -667,7 +666,7 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
app.session.set_lisp_support_dir(Some(support));
|
||||
}
|
||||
app.integrated_titlebar = cadcraft_ui_egui::framework::draws_title_row(frame.as_ref());
|
||||
app.integrated_titlebar = cfg!(target_os = "macos");
|
||||
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
|
||||
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
|
||||
}
|
||||
@@ -718,6 +717,8 @@ fn main() -> eframe::Result {
|
||||
#[cfg(target_os = "macos")]
|
||||
menus_in_window: vars.no_native_menu == Switch::On,
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: None,
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events,
|
||||
}))
|
||||
}),
|
||||
@@ -755,7 +756,7 @@ mod tests {
|
||||
/// #1129: the first launch opens centred, not cascaded from the top-left corner.
|
||||
#[test]
|
||||
fn the_first_launch_opens_centred() {
|
||||
let o = window_options(false, STENCIL_BITS, None);
|
||||
let o = window_options(false, STENCIL_BITS);
|
||||
assert!(o.centered, "centred on launch");
|
||||
assert!(o.persist_window, "the window state is saved for the next launch");
|
||||
}
|
||||
@@ -763,7 +764,7 @@ mod tests {
|
||||
/// #2595: a saved window state (size, position, maximized) is restored, not centred over.
|
||||
#[test]
|
||||
fn a_saved_window_reopens_where_it_was() {
|
||||
let o = window_options(true, STENCIL_BITS, None);
|
||||
let o = window_options(true, STENCIL_BITS);
|
||||
assert!(!o.centered, "centring would move a restored window");
|
||||
assert!(o.persist_window);
|
||||
}
|
||||
@@ -788,8 +789,8 @@ mod tests {
|
||||
#[test]
|
||||
fn the_window_carries_the_chosen_stencil_bits() {
|
||||
for bits in [0, STENCIL_BITS] {
|
||||
assert_eq!(window_options(false, bits, None).stencil_buffer, bits);
|
||||
assert_eq!(window_options(true, bits, None).stencil_buffer, bits);
|
||||
assert_eq!(window_options(false, bits).stencil_buffer, bits);
|
||||
assert_eq!(window_options(true, bits).stencil_buffer, bits);
|
||||
}
|
||||
let format = |bits| eframe::egui_wgpu::depth_format_from_bits(0, bits);
|
||||
assert_eq!(format(0), None, "no stencil: the canvas builds no clip pipelines");
|
||||
@@ -843,17 +844,3 @@ mod tests {
|
||||
assert_eq!(raw.system_theme, None);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod refusal_dialog_tests {
|
||||
use super::refusal_dialog;
|
||||
use crate::build_flavor::BuildFlavor;
|
||||
|
||||
#[test]
|
||||
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
|
||||
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
|
||||
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,9 +15,6 @@ pub struct NativeMenu {
|
||||
items: HashMap<String, (String, String, MenuItem)>,
|
||||
submenus: Vec<(String, Submenu)>,
|
||||
predefined: Vec<(&'static str, PredefinedMenuItem)>,
|
||||
/// Quit CADCraft: a close request of the main window, so unsaved drawings are asked about first.
|
||||
/// muda's predefined Quit ends the process through `terminate:` without asking.
|
||||
quit: MenuItem,
|
||||
language: &'static str,
|
||||
/// Monotonic time of the last enablement refresh. `NEG_INFINITY` makes the first poll refresh
|
||||
/// immediately: `now_ms` starts near zero, so the old `0.0` sentinel suppressed the first
|
||||
@@ -61,6 +58,7 @@ impl NativeMenu {
|
||||
("Hide CADCraft", PredefinedMenuItem::hide(Some(i18n::tr(language, "Hide CADCraft")))),
|
||||
("Hide Others", PredefinedMenuItem::hide_others(Some(i18n::tr(language, "Hide Others")))),
|
||||
("Show All", PredefinedMenuItem::show_all(Some(i18n::tr(language, "Show All")))),
|
||||
("Quit CADCraft", PredefinedMenuItem::quit(Some(i18n::tr(language, "Quit CADCraft")))),
|
||||
];
|
||||
// The Mac place for preferences: CADCraft ▸ Settings… (⌘,) opens the Options dialog.
|
||||
let settings = MenuItem::with_id("cc-settings", i18n::tr(language, "Settings..."), true, accel("Cmd+Comma"));
|
||||
@@ -71,8 +69,6 @@ impl NativeMenu {
|
||||
let _ = app_menu.append(&PredefinedMenuItem::separator());
|
||||
}
|
||||
}
|
||||
let quit = MenuItem::with_id(craft_quit::QUIT_MENU_ID, i18n::tr(language, "Quit CADCraft"), true, accel("Cmd+Q"));
|
||||
let _ = app_menu.append(&quit);
|
||||
items.insert("cc-about".into(), ("ui.dialog.about".into(), "About CADCraft".into(), about));
|
||||
items.insert("cc-discord".into(), ("ui.discord".into(), "Join the ArtCraft Discord…".into(), discord));
|
||||
items.insert("cc-settings".into(), ("options".into(), "Settings...".into(), settings));
|
||||
@@ -89,7 +85,6 @@ impl NativeMenu {
|
||||
items,
|
||||
submenus,
|
||||
predefined,
|
||||
quit,
|
||||
language,
|
||||
last_refresh: f64::NEG_INFINITY,
|
||||
recent: app.ui.recent_files.clone(),
|
||||
@@ -119,9 +114,7 @@ impl NativeMenu {
|
||||
/// Drain queued menu events into commands (Discord opens externally), rebuild Open Recent, retranslate on a language change and refresh enablement when 300 ms have elapsed.
|
||||
pub fn poll(&mut self, app: &mut CadApp, ctx: &egui::Context) {
|
||||
while let Ok(ev) = self.events.try_recv() {
|
||||
if craft_quit::on_menu_event(ctx, ev.id.as_ref()) {
|
||||
ctx.request_repaint();
|
||||
} else if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
|
||||
if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
|
||||
if cmd == "ui.discord" {
|
||||
ctx.open_url(egui::OpenUrl::new_tab("https://discord.gg/artcraft"));
|
||||
} else {
|
||||
@@ -140,7 +133,6 @@ impl NativeMenu {
|
||||
for (label, item) in &self.predefined {
|
||||
item.set_text(i18n::tr(language, label));
|
||||
}
|
||||
self.quit.set_text(i18n::tr(language, "Quit CADCraft"));
|
||||
for (label, submenu) in &self.submenus {
|
||||
submenu.set_text(i18n::tr_menu(language, label));
|
||||
}
|
||||
|
||||
+561
-172
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,7 +252,7 @@ mod tests {
|
||||
app.run("ui.dock", json!({"operation":"move", "panel":"layers", "target":"properties", "zone":"left"})).unwrap();
|
||||
app.run("ui.dock", json!({"operation":"float", "panel":"properties", "rect":[120,90,340,410]})).unwrap();
|
||||
ui.docking = app.ui.docking;
|
||||
ui.docking.set_visible(Panel::ToolSets, false, None, false, permissions).unwrap();
|
||||
ui.docking.set_visible(Panel::ToolSets, false, None, permissions).unwrap();
|
||||
ui.show_toolsets = false;
|
||||
store.save_if_changed(&ui, Instant::now()).unwrap();
|
||||
let saved: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
|
||||
@@ -263,9 +263,9 @@ mod tests {
|
||||
assert_eq!(serde_json::to_value(&reloaded.docking).unwrap(), serde_json::to_value(&ui.docking).unwrap());
|
||||
assert!(!reloaded.show_toolsets);
|
||||
reveal_panel(&mut reloaded.docking, Panel::ToolSets).unwrap();
|
||||
let tools = reloaded.docking.layout().location(&Panel::ToolSets).unwrap();
|
||||
let tools = reloaded.docking.layout.location(&Panel::ToolSets).unwrap();
|
||||
assert_eq!(serde_json::to_value(&tools.group).unwrap()["column"]["side"], json!("Start"), "{tools:?}");
|
||||
assert_eq!(reloaded.docking.layout().floating[0].rect, egui::Rect::from_min_size(egui::pos2(120.0, 90.0), egui::vec2(340.0, 410.0)));
|
||||
assert_eq!(reloaded.docking.layout.floating[0].rect, [120.0, 90.0, 340.0, 410.0]);
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
@@ -293,8 +293,8 @@ mod tests {
|
||||
assert_eq!(ui.toolset_tab, "Modeling");
|
||||
assert_eq!(ui.history_lines, 4);
|
||||
assert!(!ui.show_toolsets && ui.show_palettes && !ui.show_toolbar);
|
||||
assert_eq!(ui.docking.layout(), default_workspace().layout());
|
||||
assert!(ui.docking.hidden().is_empty(), "{:?}", ui.docking.hidden());
|
||||
assert_eq!(ui.docking.layout, default_workspace().layout);
|
||||
assert!(ui.docking.hidden.is_empty(), "{:?}", ui.docking.hidden);
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
|
||||
@@ -2,4 +2,7 @@ allow-unwrap-in-tests = true
|
||||
allow-expect-in-tests = true
|
||||
allow-panic-in-tests = true
|
||||
allow-indexing-slicing-in-tests = true
|
||||
disallowed-types = [
|
||||
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
|
||||
]
|
||||
cognitive-complexity-threshold = 30
|
||||
|
||||
@@ -238,9 +238,8 @@ mod tests {
|
||||
assert!(f.t.near(g.t, 1e-3), "{f:?} {g:?}");
|
||||
assert!((f.k - g.k).abs() < 1e-2, "{f:?} {g:?}");
|
||||
}
|
||||
// An unclamped spline has no ends: one whose control points wrap round.
|
||||
let fit = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)];
|
||||
let closed = GSpline::fit_with(&fit, true, cadcraft_geom::FitOptions { knots: cadcraft_geom::KnotParam::Uniform, ..Default::default() });
|
||||
assert!(closed.wraps() && spline_end(&closed, false).is_none());
|
||||
// An unclamped (periodic) spline has no ends.
|
||||
let closed = GSpline::from_fit_points_closed(&[Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)]);
|
||||
assert!(spline_end(&closed, false).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ mod proxy;
|
||||
mod text;
|
||||
mod wipeout;
|
||||
|
||||
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal};
|
||||
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, 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};
|
||||
@@ -399,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;
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::common::{Common, Lineweight};
|
||||
use super::text::{MText, Text};
|
||||
use super::{Color, Deserialize, EntityKind, Mat3, Serialize, Vec2, Vec3};
|
||||
@@ -145,43 +142,6 @@ impl AttribProps {
|
||||
}
|
||||
}
|
||||
|
||||
/// An attribute tag as attributes are matched to their definitions and to each other: ASCII
|
||||
/// letters in either case are the same tag, other characters must be equal. As an ordered map key
|
||||
/// it finds the match in a logarithmic number of comparisons, where comparing each attribute with
|
||||
/// each definition costs their product on a block with many of both (#1923). It orders, rather
|
||||
/// than hashes, so the cost doesn't depend on hash keys a crafted file could predict (the web
|
||||
/// build's `RandomState`), as in the layer and block name index.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct TagKey<'a>(pub &'a str);
|
||||
|
||||
impl TagKey<'_> {
|
||||
/// 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> + '_ {
|
||||
self.0.bytes().map(|b| b.to_ascii_lowercase())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for TagKey<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.0.eq_ignore_ascii_case(other.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for TagKey<'_> {}
|
||||
|
||||
impl Ord for TagKey<'_> {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
self.folded().cmp(other.folded())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for TagKey<'_> {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Insert {
|
||||
@@ -244,31 +204,4 @@ impl Insert {
|
||||
.then_before(Mat3::scale(self.scale.x, self.scale.y))
|
||||
.then_before(Mat3::translate(-base))
|
||||
}
|
||||
|
||||
/// The reference's attributes by tag: of several with one tag (in any ASCII case), the first.
|
||||
/// Built once, it tells whether the reference carries a definition's tag, and its value, in
|
||||
/// one lookup instead of a pass over the attributes per definition (#1923).
|
||||
pub fn attribs_by_tag(&self) -> BTreeMap<TagKey<'_>, &Attrib> {
|
||||
let mut by_tag = BTreeMap::new();
|
||||
for a in &self.attribs {
|
||||
by_tag.entry(TagKey(a.tag.as_str())).or_insert(a);
|
||||
}
|
||||
by_tag
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Block {
|
||||
/// The block's attribute definitions by tag: of several with one tag (in any ASCII case), the
|
||||
/// first in the block's order, the one an attribute of that tag takes its properties from.
|
||||
/// Built once for all of a reference's attributes, it matches each in one lookup instead of a
|
||||
/// pass over the block per attribute (#1923).
|
||||
pub fn attdefs_by_tag(&self) -> BTreeMap<TagKey<'_>, &crate::Entity> {
|
||||
let mut by_tag = BTreeMap::new();
|
||||
for e in self.entities.iter() {
|
||||
if let EntityKind::AttDef(a) = &e.kind {
|
||||
by_tag.entry(TagKey(a.tag.as_str())).or_insert(e.as_ref());
|
||||
}
|
||||
}
|
||||
by_tag
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
+17
-20
@@ -1,10 +1,10 @@
|
||||
//! Approximate entity bounds (used for extents, zoom and selection pre-filtering).
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use cadcraft_geom::{Arc, Bounds2, EPS, Polyline, Vec2, bulge_to_arc};
|
||||
|
||||
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim, TagKey};
|
||||
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim};
|
||||
|
||||
/// Nested block references deeper than this are ignored (cyclic or hostile files).
|
||||
pub const MAX_BLOCK_DEPTH: usize = 16;
|
||||
@@ -283,33 +283,33 @@ fn layer_counts(d: &Drawing, layer: &str, off_counts: bool) -> bool {
|
||||
}
|
||||
|
||||
/// The layer an insert's attribute draws on, as the renderer takes it: its own, else its
|
||||
/// definition's, from the block's definitions by tag `defs` (layer "0" being the insert's).
|
||||
fn attrib_layer<'a>(defs: Option<&BTreeMap<TagKey<'a>, &'a Entity>>, a: &'a crate::Attrib) -> &'a str {
|
||||
a.props.layer.as_deref().unwrap_or_else(|| defs.and_then(|defs| defs.get(&TagKey(&a.tag))).map_or("0", |be| be.common.layer.as_str()))
|
||||
/// definition's (layer "0" being the insert's).
|
||||
fn attrib_layer<'a>(d: &'a Drawing, ins: &crate::Insert, a: &'a crate::Attrib) -> &'a str {
|
||||
a.props.layer.as_deref().unwrap_or_else(|| {
|
||||
d.block(&ins.block)
|
||||
.and_then(|blk| blk.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag))))
|
||||
.map_or("0", |be| be.common.layer.as_str())
|
||||
})
|
||||
}
|
||||
|
||||
/// The bounds of a block's contents, in block coordinates: its geometry, which every reference to
|
||||
/// the block shows, and the value of each constant attribute definition ATTMODE shows, by tag, which
|
||||
/// only a block reference draws (a dimension's block does not), and only when the reference
|
||||
/// carries no attribute of that tag. They are kept apart so that the one cache serves every
|
||||
/// reference, whichever asks first. Also the block's attribute definitions by tag, for the layer
|
||||
/// of an attribute that has none of its own.
|
||||
/// reference, whichever asks first.
|
||||
struct Contents<'a> {
|
||||
geometry: Bounds2,
|
||||
constants: Vec<(&'a str, Bounds2)>,
|
||||
defs: BTreeMap<TagKey<'a>, &'a Entity>,
|
||||
}
|
||||
|
||||
impl Contents<'_> {
|
||||
/// What reference `ins` shows of the block: its geometry and the constant values `ins` has
|
||||
/// no attribute for (that attribute is drawn instead, and counted with the attributes).
|
||||
fn in_reference(&self, ins: &crate::Insert) -> Bounds2 {
|
||||
if self.constants.is_empty() {
|
||||
return self.geometry;
|
||||
}
|
||||
// The reference's tags are gathered once, not scanned again for each constant (#1923).
|
||||
let carried = ins.attribs_by_tag();
|
||||
self.constants.iter().filter(|(tag, _)| !carried.contains_key(&TagKey(tag))).fold(self.geometry, |b, (_, c)| b.union(c))
|
||||
self.constants
|
||||
.iter()
|
||||
.filter(|(tag, _)| !ins.attribs.iter().any(|r| r.tag.eq_ignore_ascii_case(tag)))
|
||||
.fold(self.geometry, |b, (_, c)| b.union(c))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,7 +323,7 @@ fn contents<'a, 'm>(
|
||||
) -> Option<&'m Contents<'a>> {
|
||||
let key = (blk.name.as_str(), depth);
|
||||
if !blocks.contains_key(&key) {
|
||||
let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new(), defs: blk.attdefs_by_tag() };
|
||||
let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new() };
|
||||
// ATTMODE, as the renderer applies it to a constant value: 0 shows none, 1 the visible
|
||||
// ones, 2 all of them.
|
||||
let attmode = d.header.i64("ATTMODE", 1);
|
||||
@@ -487,12 +487,9 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
|
||||
// one draws nothing, so it contributes nothing: ZOOM Extents must not fly off to its
|
||||
// insertion point. Attributes below still count.
|
||||
let mut b = Bounds2::EMPTY;
|
||||
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, off_counts);
|
||||
defs = c.map(|c| &c.defs);
|
||||
let inner = c.map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
|
||||
let inner = contents(d, blk, depth, blocks, off_counts).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).
|
||||
@@ -514,7 +511,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
|
||||
}
|
||||
}
|
||||
for a in &ins.attribs {
|
||||
if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts) {
|
||||
if !a.invisible && layer_counts(d, attrib_layer(d, ins, a), off_counts) {
|
||||
b = b.union(&match a.multiline_text() {
|
||||
Some(m) => mtext_box(&m),
|
||||
None => text_box(&a.text, a.text.value.chars().count()),
|
||||
|
||||
@@ -113,43 +113,6 @@ impl Foreign {
|
||||
&& 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> {
|
||||
@@ -427,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")));
|
||||
}
|
||||
}
|
||||
|
||||
+22
-39
@@ -14,7 +14,6 @@ mod format;
|
||||
mod gdt;
|
||||
mod header;
|
||||
pub mod library;
|
||||
mod names;
|
||||
mod plotstyle;
|
||||
mod plotter;
|
||||
mod raster;
|
||||
@@ -37,7 +36,6 @@ pub use extents::{
|
||||
pub use format::Format;
|
||||
pub use gdt::*;
|
||||
pub use header::{HVal, Header};
|
||||
pub use names::{Named, NamedList, NamedMap};
|
||||
pub use plotstyle::*;
|
||||
pub use plotter::*;
|
||||
pub use raster::{Raster, Rasters};
|
||||
@@ -103,26 +101,19 @@ pub struct Drawing {
|
||||
pub header: Header,
|
||||
/// File data CADCraft does not model, written back on save.
|
||||
pub foreign: std::sync::Arc<foreign::Foreign>,
|
||||
/// Layers in table order; [`Drawing::layer`] looks them up by name.
|
||||
pub layers: NamedList<Layer>,
|
||||
/// Linetypes in table order; [`Drawing::linetype`] looks them up by name.
|
||||
pub linetypes: NamedList<Linetype>,
|
||||
/// Text styles in table order; [`Drawing::text_style`] looks them up by name.
|
||||
pub text_styles: NamedList<TextStyle>,
|
||||
/// Dimension styles in table order; [`Drawing::dim_style`] looks them up by name.
|
||||
pub dim_styles: NamedList<DimStyle>,
|
||||
pub layers: Vec<Layer>,
|
||||
pub linetypes: Vec<Linetype>,
|
||||
pub text_styles: Vec<TextStyle>,
|
||||
pub dim_styles: Vec<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.
|
||||
pub blocks: NamedMap<std::sync::Arc<Block>>,
|
||||
pub blocks: BTreeMap<String, std::sync::Arc<Block>>,
|
||||
pub model: EntityStore,
|
||||
/// Model layout's page setup, or the default extents-to-fit setup for a new drawing.
|
||||
pub model_page: Option<PageSetup>,
|
||||
/// Layouts in list order (`tab_order` orders the tabs); [`Drawing::layout`] looks them up by name.
|
||||
pub layouts: NamedList<Layout>,
|
||||
pub layouts: Vec<Layout>,
|
||||
/// The layout a file marks active (its block is `*Paper_Space`, the others `*Paper_SpaceN`),
|
||||
/// written active again. `None`, or a layout that no longer exists: the first by tab order.
|
||||
pub active_layout: Option<String>,
|
||||
@@ -196,7 +187,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
|
||||
}
|
||||
@@ -204,22 +195,21 @@ impl Drawing {
|
||||
Drawing {
|
||||
header: Header::default(),
|
||||
foreign: std::sync::Arc::default(),
|
||||
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }].into(),
|
||||
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }],
|
||||
linetypes: vec![
|
||||
Linetype { name: "ByBlock".into(), description: String::new(), pattern: Vec::new() },
|
||||
Linetype { name: "ByLayer".into(), description: String::new(), pattern: Vec::new() },
|
||||
Linetype::continuous(),
|
||||
]
|
||||
.into(),
|
||||
text_styles: vec![TextStyle::default()].into(),
|
||||
dim_styles: vec![DimStyle::default()].into(),
|
||||
],
|
||||
text_styles: vec![TextStyle::default()],
|
||||
dim_styles: vec![DimStyle::default()],
|
||||
mleader_styles: vec![MLeaderStyle::default()],
|
||||
table_styles: vec![TableStyle::default()].into(),
|
||||
table_styles: vec![TableStyle::default()],
|
||||
mline_styles: vec![MLineStyle::default()],
|
||||
blocks: NamedMap::default(),
|
||||
blocks: BTreeMap::new(),
|
||||
model: EntityStore::new(),
|
||||
model_page: None,
|
||||
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)].into(),
|
||||
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
|
||||
active_layout: None,
|
||||
views: Vec::new(),
|
||||
vports: Vec::new(),
|
||||
@@ -323,25 +313,20 @@ impl Drawing {
|
||||
}
|
||||
}
|
||||
|
||||
/// The first layer named `name`, without case.
|
||||
pub fn layer(&self, name: &str) -> Option<&Layer> {
|
||||
self.layers.by_name(name)
|
||||
self.layers.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
/// The first layer named `name`, without case, to change.
|
||||
pub fn layer_mut(&mut self, name: &str) -> Option<&mut Layer> {
|
||||
self.layers.by_name_mut(name)
|
||||
self.layers.iter_mut().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
/// The first linetype named `name`, without case.
|
||||
pub fn linetype(&self, name: &str) -> Option<&Linetype> {
|
||||
self.linetypes.by_name(name)
|
||||
self.linetypes.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
/// The first text style named `name`, without case.
|
||||
pub fn text_style(&self, name: &str) -> Option<&TextStyle> {
|
||||
self.text_styles.by_name(name)
|
||||
self.text_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
/// The first dimension style named `name`, without case.
|
||||
pub fn dim_style(&self, name: &str) -> Option<&DimStyle> {
|
||||
self.dim_styles.by_name(name)
|
||||
self.dim_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// The DIM* variables in the header that differ from the current dimension style, as
|
||||
@@ -409,13 +394,11 @@ impl Drawing {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The block named exactly `name`, else the first by name order named `name` without case.
|
||||
pub fn block(&self, name: &str) -> Option<&std::sync::Arc<Block>> {
|
||||
self.blocks.by_name(name)
|
||||
self.blocks.get(name).or_else(|| self.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v))
|
||||
}
|
||||
/// The first layout named `name`, without case.
|
||||
pub fn layout(&self, name: &str) -> Option<&Layout> {
|
||||
self.layouts.by_name(name)
|
||||
self.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// Add a layer if missing; returns whether it was created.
|
||||
|
||||
@@ -1,575 +0,0 @@
|
||||
//! 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.
|
||||
//!
|
||||
//! [`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
|
||||
//! every layout is looked up on each change. Scanning the table on each made a file of N layers,
|
||||
//! or of N blocks, linetypes or styles and N objects naming ones it does not have, cost N² name
|
||||
//! comparisons: tens of seconds to open or draw at a few tens of thousands (#1924, F-04).
|
||||
//!
|
||||
//! Each table keeps an index from a name with its ASCII letters lower-cased to the table's first
|
||||
//! entry of that name, so a lookup returns what a scan in table order returns. The index is ordered
|
||||
//! by those bytes, not hashed: a lookup costs a logarithmic number of name comparisons whatever
|
||||
//! the names are, also where a file could predict a hash's keys (the web build's `RandomState`).
|
||||
//! Every change to a table goes through `DerefMut`, which drops the index, so it can never be
|
||||
//! stale. The index is built only once a table has been scanned [`SCANS_BEFORE_INDEX`] times since
|
||||
//! it last changed: a table changed between every few hundred lookups costs at most about 2.5 times
|
||||
//! what scanning it always did, and one looked up many times in between is indexed once.
|
||||
|
||||
use std::collections::{BTreeMap, btree_map};
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
/// Tables with fewer entries than this are always scanned: a search of the index costs about what a
|
||||
/// scan of 100 names does (measured), so a smaller table gains nothing from one.
|
||||
const MIN_INDEXED: usize = 128;
|
||||
/// Lookups that scan a table after it changed before its index is built. A build costs about 100
|
||||
/// to 350 scans (measured on tables of 100 to 40 000 names), so a table changed after every few
|
||||
/// hundred lookups costs at most about 2.5 times what scanning it always did.
|
||||
const SCANS_BEFORE_INDEX: u32 = 256;
|
||||
|
||||
/// From a name with its ASCII letters lower-cased to the first entry, in table order, of that name.
|
||||
struct Index<V>(BTreeMap<Box<[u8]>, V>);
|
||||
|
||||
impl<V> Index<V> {
|
||||
fn build<'a>(entries: impl Iterator<Item = (&'a str, V)>) -> Self {
|
||||
let mut map = BTreeMap::new();
|
||||
for (name, v) in entries {
|
||||
map.entry(name.to_ascii_lowercase().into_bytes().into_boxed_slice()).or_insert(v);
|
||||
}
|
||||
Index(map)
|
||||
}
|
||||
|
||||
/// The first entry named `name`, without case.
|
||||
fn get(&self, name: &str) -> Option<&V> {
|
||||
with_folded(name, |folded| self.0.get(folded))
|
||||
}
|
||||
}
|
||||
|
||||
/// `f` of the bytes of `name` with its ASCII letters lower-cased, which are equal for the names
|
||||
/// `eq_ignore_ascii_case` finds equal. A short name is folded on the stack.
|
||||
fn with_folded<R>(name: &str, f: impl FnOnce(&[u8]) -> R) -> R {
|
||||
let mut buf = [0u8; 64];
|
||||
match buf.get_mut(..name.len()) {
|
||||
Some(short) => {
|
||||
short.copy_from_slice(name.as_bytes());
|
||||
short.make_ascii_lowercase();
|
||||
f(short)
|
||||
}
|
||||
None => f(name.to_ascii_lowercase().as_bytes()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A table's index: built on demand, shared by copies of the unchanged table (an undo snapshot),
|
||||
/// dropped when the table changes.
|
||||
struct Lazy<V> {
|
||||
index: OnceLock<Arc<Index<V>>>,
|
||||
/// Lookups that scanned the table since it last changed.
|
||||
scans: AtomicU32,
|
||||
}
|
||||
|
||||
impl<V> Lazy<V> {
|
||||
/// The index of a table of `len` entries, built with `build` once the table has been scanned
|
||||
/// often enough since it changed; `None` while it is to be scanned.
|
||||
fn get(&self, len: usize, build: impl FnOnce() -> Index<V>) -> Option<&Index<V>> {
|
||||
if let Some(ix) = self.index.get() {
|
||||
return Some(ix);
|
||||
}
|
||||
if len < MIN_INDEXED || self.scans.fetch_add(1, Ordering::Relaxed) < SCANS_BEFORE_INDEX {
|
||||
return None;
|
||||
}
|
||||
Some(self.index.get_or_init(|| Arc::new(build())))
|
||||
}
|
||||
|
||||
/// Forget the index: the table may change.
|
||||
fn clear(&mut self) {
|
||||
self.index = OnceLock::new();
|
||||
*self.scans.get_mut() = 0;
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Default for Lazy<V> {
|
||||
fn default() -> Self {
|
||||
Lazy { index: OnceLock::new(), scans: AtomicU32::new(0) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Clone for Lazy<V> {
|
||||
fn clone(&self) -> Self {
|
||||
Lazy { index: self.index.clone(), scans: AtomicU32::new(0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// An entry of a [`NamedList`]: what it is looked up by.
|
||||
pub trait Named {
|
||||
fn name(&self) -> &str;
|
||||
}
|
||||
|
||||
/// Entries named by their `name` field.
|
||||
macro_rules! named_by_field {
|
||||
($($t:ty),*) => {$(
|
||||
impl Named for $t {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
)*};
|
||||
}
|
||||
named_by_field!(crate::Layer, crate::Linetype, crate::TextStyle, crate::DimStyle, crate::TableStyle, 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.
|
||||
pub struct NamedList<T> {
|
||||
list: Vec<T>,
|
||||
index: Lazy<usize>,
|
||||
}
|
||||
|
||||
impl<T: Named> NamedList<T> {
|
||||
/// The position of the first entry named `name`, without case.
|
||||
pub fn position_by_name(&self, name: &str) -> Option<usize> {
|
||||
match self.index.get(self.list.len(), || Index::build(self.list.iter().enumerate().map(|(i, t)| (t.name(), i)))) {
|
||||
Some(ix) => ix.get(name).copied(),
|
||||
None => self.list.iter().position(|t| t.name().eq_ignore_ascii_case(name)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first entry named `name`, without case.
|
||||
pub fn by_name(&self, name: &str) -> Option<&T> {
|
||||
self.position_by_name(name).and_then(|i| self.list.get(i))
|
||||
}
|
||||
|
||||
/// The first entry named `name`, without case, to change (which drops the index).
|
||||
pub fn by_name_mut(&mut self, name: &str) -> Option<&mut T> {
|
||||
let i = self.position_by_name(name)?;
|
||||
self.get_mut(i)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for NamedList<T> {
|
||||
type Target = Vec<T>;
|
||||
fn deref(&self) -> &Vec<T> {
|
||||
&self.list
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> DerefMut for NamedList<T> {
|
||||
fn deref_mut(&mut self) -> &mut Vec<T> {
|
||||
self.index.clear();
|
||||
&mut self.list
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for NamedList<T> {
|
||||
fn default() -> Self {
|
||||
Vec::new().into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone> Clone for NamedList<T> {
|
||||
fn clone(&self) -> Self {
|
||||
NamedList { list: self.list.clone(), index: self.index.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: std::fmt::Debug> std::fmt::Debug for NamedList<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.list.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PartialEq> PartialEq for NamedList<T> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.list == other.list
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<Vec<T>> for NamedList<T> {
|
||||
fn from(list: Vec<T>) -> Self {
|
||||
NamedList { list, index: Lazy::default() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<NamedList<T>> for Vec<T> {
|
||||
fn from(l: NamedList<T>) -> Self {
|
||||
l.list
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: serde::Serialize> serde::Serialize for NamedList<T> {
|
||||
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
self.list.serialize(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> FromIterator<T> for NamedList<T> {
|
||||
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
|
||||
Vec::from_iter(iter).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> IntoIterator for NamedList<T> {
|
||||
type Item = T;
|
||||
type IntoIter = std::vec::IntoIter<T>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.list.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> IntoIterator for &'a NamedList<T> {
|
||||
type Item = &'a T;
|
||||
type IntoIter = std::slice::Iter<'a, T>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.list.iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> IntoIterator for &'a mut NamedList<T> {
|
||||
type Item = &'a mut T;
|
||||
type IntoIter = std::slice::IterMut<'a, T>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.deref_mut().iter_mut()
|
||||
}
|
||||
}
|
||||
|
||||
/// Entries by name, in name order (the drawing's block definitions). It reads and changes as a
|
||||
/// `BTreeMap`; [`NamedMap::by_name`] finds an entry by its exact name, else the first in name
|
||||
/// order whose name matches without case.
|
||||
pub struct NamedMap<V> {
|
||||
map: BTreeMap<String, V>,
|
||||
index: Lazy<Box<str>>,
|
||||
}
|
||||
|
||||
impl<V> NamedMap<V> {
|
||||
/// The entry named exactly `name`, else the first in name order named `name` without case.
|
||||
pub fn by_name(&self, name: &str) -> Option<&V> {
|
||||
if let Some(v) = self.map.get(name) {
|
||||
return Some(v);
|
||||
}
|
||||
match self.index.get(self.map.len(), || Index::build(self.map.keys().map(|k| (k.as_str(), Box::from(k.as_str()))))) {
|
||||
Some(ix) => ix.get(name).and_then(|k| self.map.get(&**k)),
|
||||
None => self.map.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Deref for NamedMap<V> {
|
||||
type Target = BTreeMap<String, V>;
|
||||
fn deref(&self) -> &BTreeMap<String, V> {
|
||||
&self.map
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> DerefMut for NamedMap<V> {
|
||||
fn deref_mut(&mut self) -> &mut BTreeMap<String, V> {
|
||||
self.index.clear();
|
||||
&mut self.map
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Default for NamedMap<V> {
|
||||
fn default() -> Self {
|
||||
BTreeMap::new().into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: Clone> Clone for NamedMap<V> {
|
||||
fn clone(&self) -> Self {
|
||||
NamedMap { map: self.map.clone(), index: self.index.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: std::fmt::Debug> std::fmt::Debug for NamedMap<V> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.map.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: PartialEq> PartialEq for NamedMap<V> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.map == other.map
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> From<BTreeMap<String, V>> for NamedMap<V> {
|
||||
fn from(map: BTreeMap<String, V>) -> Self {
|
||||
NamedMap { map, index: Lazy::default() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> FromIterator<(String, V)> for NamedMap<V> {
|
||||
fn from_iter<I: IntoIterator<Item = (String, V)>>(iter: I) -> Self {
|
||||
BTreeMap::from_iter(iter).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> IntoIterator for NamedMap<V> {
|
||||
type Item = (String, V);
|
||||
type IntoIter = btree_map::IntoIter<String, V>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.map.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, V> IntoIterator for &'a NamedMap<V> {
|
||||
type Item = (&'a String, &'a V);
|
||||
type IntoIter = btree_map::Iter<'a, String, V>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.map.iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, V> IntoIterator for &'a mut NamedMap<V> {
|
||||
type Item = (&'a String, &'a mut V);
|
||||
type IntoIter = btree_map::IterMut<'a, String, V>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.deref_mut().iter_mut()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::{MIN_INDEXED, Named, NamedList};
|
||||
use crate::{Block, DimStyle, Drawing, Layer, Layout, Linetype, TextStyle};
|
||||
|
||||
/// Names to look up: each given name as it is, upper-cased, lower-cased and with a character
|
||||
/// added (a miss).
|
||||
fn probes<'a>(names: impl Iterator<Item = &'a str>) -> Vec<String> {
|
||||
names.flat_map(|n| [n.to_string(), n.to_ascii_uppercase(), n.to_ascii_lowercase(), format!("{n}?")]).collect()
|
||||
}
|
||||
|
||||
fn layers_indexed(d: &Drawing) -> bool {
|
||||
d.layers.index.index.get().is_some()
|
||||
}
|
||||
|
||||
fn indexed<T>(list: &NamedList<T>) -> bool {
|
||||
list.index.index.get().is_some()
|
||||
}
|
||||
|
||||
/// Every lookup through `find` finds what a scan of `list` in table order finds (the first of a
|
||||
/// name without case), by pointer, for the list's names and `extra`.
|
||||
fn check_list<'a, T: Named>(list: &'a NamedList<T>, find: impl Fn(&str) -> Option<&'a T>, extra: &[&str]) {
|
||||
let names: Vec<String> = list.iter().map(|t| t.name().to_string()).collect();
|
||||
for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) {
|
||||
let want = list.iter().find(|t| t.name().eq_ignore_ascii_case(&p)).map(std::ptr::from_ref);
|
||||
assert_eq!(find(&p).map(std::ptr::from_ref), want, "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The linetype, text style, dimension style and layout lookups each find what a scan in table
|
||||
/// order finds (the first of a name without case): while they scan, once the table is indexed,
|
||||
/// and after `by_name_mut` (RENAME, STYLE, DIMSTYLE, a .lin file reloaded, a layout's UCS)
|
||||
/// changed the first of a name and dropped the index.
|
||||
#[test]
|
||||
fn linetype_style_and_layout_lookups_find_the_first_of_a_name() {
|
||||
let names: Vec<String> = (0..150).map(|i| format!("N{i}")).chain(["n7", "Dash", "DASH"].map(String::from)).collect();
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.linetypes = names.iter().map(|n| Linetype::simple(n, "", &[0.5, -0.25])).collect();
|
||||
d.text_styles = names.iter().map(|n| TextStyle { name: n.clone(), ..TextStyle::default() }).collect();
|
||||
d.dim_styles = names.iter().map(|n| DimStyle { name: n.clone(), ..DimStyle::default() }).collect();
|
||||
d.layouts = names.iter().zip(1..).map(|(n, tab)| Layout::new(n, tab)).collect();
|
||||
let check = |d: &Drawing, extra: &[&str]| {
|
||||
check_list(&d.linetypes, |n| d.linetype(n), extra);
|
||||
check_list(&d.text_styles, |n| d.text_style(n), extra);
|
||||
check_list(&d.dim_styles, |n| d.dim_style(n), extra);
|
||||
check_list(&d.layouts, |n| d.layout(n), extra);
|
||||
};
|
||||
let all_indexed = |d: &Drawing| indexed(&d.linetypes) && indexed(&d.text_styles) && indexed(&d.dim_styles) && indexed(&d.layouts);
|
||||
// The first round scans until the index is built; the second reads only the index.
|
||||
check(&d, &["dash", "missing"]);
|
||||
assert!(all_indexed(&d));
|
||||
check(&d, &["dash", "missing"]);
|
||||
|
||||
// The first of a name changes, and the later one of that name is found after it.
|
||||
d.linetypes.by_name_mut("n7").unwrap().name = "Seven".into();
|
||||
d.text_styles.by_name_mut("n7").unwrap().name = "Seven".into();
|
||||
d.dim_styles.by_name_mut("n7").unwrap().name = "Seven".into();
|
||||
d.layouts.by_name_mut("n7").unwrap().name = "Seven".into();
|
||||
assert!(!indexed(&d.linetypes) && !indexed(&d.text_styles) && !indexed(&d.dim_styles) && !indexed(&d.layouts));
|
||||
assert_eq!(d.linetype("N7").map(|l| l.name.as_str()), Some("n7"));
|
||||
assert_eq!(d.text_style("N7").map(|s| s.name.as_str()), Some("n7"));
|
||||
assert_eq!(d.dim_style("N7").map(|s| s.name.as_str()), Some("n7"));
|
||||
assert_eq!(d.layout("N7").map(|l| (l.name.as_str(), l.tab_order)), Some(("n7", 151)));
|
||||
assert_eq!(d.linetypes.get(7).map(|l| l.name.as_str()), Some("Seven"));
|
||||
check(&d, &["SEVEN", "n7"]);
|
||||
assert!(all_indexed(&d));
|
||||
// A miss changes nothing and keeps the index.
|
||||
assert!(d.dim_styles.by_name_mut("none").is_none());
|
||||
assert!(indexed(&d.dim_styles));
|
||||
check(&d, &["dash"]);
|
||||
}
|
||||
|
||||
fn blocks_indexed(d: &Drawing) -> bool {
|
||||
d.blocks.index.index.get().is_some()
|
||||
}
|
||||
|
||||
/// `layer_mut` finds the first layer of a name and drops the index, as the table may change
|
||||
/// through it. Then every layer lookup finds what a scan in table order finds (the first of a
|
||||
/// name without case), and a large table looked up this often is left indexed.
|
||||
fn check_layers(d: &mut Drawing, extra: &[&str]) {
|
||||
let p = extra.first().copied().unwrap_or("L1");
|
||||
let want = d.layers.iter().position(|l| l.name.eq_ignore_ascii_case(p)).and_then(|i| d.layers.get(i)).map(std::ptr::from_ref);
|
||||
assert_eq!(d.layer_mut(p).map(|l| std::ptr::from_ref(&*l)), want, "{p}");
|
||||
assert!(want.is_none() || !layers_indexed(d));
|
||||
let names: Vec<String> = d.layers.iter().map(|l| l.name.clone()).collect();
|
||||
for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) {
|
||||
let want = d.layers.iter().position(|l| l.name.eq_ignore_ascii_case(&p));
|
||||
assert_eq!(d.layers.position_by_name(&p), want, "{p}");
|
||||
let at = want.and_then(|i| d.layers.get(i)).map(std::ptr::from_ref);
|
||||
assert_eq!(d.layer(&p).map(std::ptr::from_ref), at, "{p}");
|
||||
}
|
||||
assert_eq!(layers_indexed(d), d.layers.len() >= MIN_INDEXED);
|
||||
}
|
||||
|
||||
/// Every block lookup finds what `Drawing::block` always found: the block of that exact name,
|
||||
/// else the first in name order of that name without case. Only names that miss an exact name
|
||||
/// count towards building the index, so the names are looked up twice.
|
||||
fn check_blocks(d: &Drawing, extra: &[&str]) {
|
||||
let names: Vec<String> = d.blocks.keys().cloned().collect();
|
||||
for p in probes(names.iter().chain(&names).map(String::as_str).chain(extra.iter().copied())) {
|
||||
let want = d.blocks.get(&p).or_else(|| d.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(&p)).map(|(_, v)| v));
|
||||
assert_eq!(d.block(&p).map(std::ptr::from_ref), want.map(std::ptr::from_ref), "{p}");
|
||||
}
|
||||
assert_eq!(blocks_indexed(d), d.blocks.len() >= MIN_INDEXED);
|
||||
}
|
||||
|
||||
/// The index answers by itself, with no scan to fall back on: every name finds the first entry
|
||||
/// of its name without case, also names that differ only after a long shared prefix, names
|
||||
/// that fill the stack buffer or are longer, and names with non-ASCII letters (which keep their
|
||||
/// case). Names are compared, not hashed, so no two names can share a slot.
|
||||
#[test]
|
||||
fn the_index_alone_finds_the_first_entry_of_every_name() {
|
||||
let long = "x".repeat(100);
|
||||
let names: Vec<String> = vec![
|
||||
"Door".into(),
|
||||
"DOOR".into(),
|
||||
"door2".into(),
|
||||
format!("{long}A"),
|
||||
format!("{long}a"),
|
||||
format!("{long}B"),
|
||||
format!("{}b", "P".repeat(63)),
|
||||
format!("{}B", "p".repeat(63)),
|
||||
"Ärea".into(),
|
||||
"ärea".into(),
|
||||
"ÄREA".into(),
|
||||
String::new(),
|
||||
];
|
||||
let ix = super::Index::build(names.iter().enumerate().map(|(i, n)| (n.as_str(), i)));
|
||||
for p in names.iter().flat_map(|n| [n.clone(), n.to_ascii_uppercase(), n.to_ascii_lowercase(), format!("{n}?")]) {
|
||||
let want = names.iter().position(|n| n.eq_ignore_ascii_case(&p));
|
||||
assert_eq!(ix.get(&p).copied(), want, "{p:?}");
|
||||
}
|
||||
assert_eq!(ix.get(&format!("{long}a")), Some(&3));
|
||||
assert_eq!(ix.get("ärea"), Some(&9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_lookups_find_the_first_of_a_name_through_every_change() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.layers = (0..200).map(|i| Layer::new(&format!("L{i}"))).chain([Layer::new("l5"), Layer::new("Doors")]).collect();
|
||||
check_layers(&mut d, &["l5", "missing"]);
|
||||
|
||||
// Renamed through layer_mut (RENAME).
|
||||
d.layer_mut("l7").unwrap().name = "Seven".into();
|
||||
assert!(!layers_indexed(&d));
|
||||
assert!(d.layer("L7").is_none());
|
||||
check_layers(&mut d, &["SEVEN", "L7"]);
|
||||
// Added (LAYER New, or a file's later record of a name it already has).
|
||||
d.layers.push(Layer::new("SEVEN"));
|
||||
assert!(!layers_indexed(&d));
|
||||
check_layers(&mut d, &["seven"]);
|
||||
// Removed (PURGE, LAYDEL): the later `l5` becomes the first of that name.
|
||||
d.layers.retain(|l| l.name != "L5");
|
||||
assert!(!layers_indexed(&d));
|
||||
assert_eq!(d.layer("L5").map(|l| l.name.as_str()), Some("l5"));
|
||||
check_layers(&mut d, &["L5"]);
|
||||
// Inserted before an earlier layer of the same name.
|
||||
d.layers.insert(0, Layer::new("l9"));
|
||||
assert!(!layers_indexed(&d));
|
||||
assert_eq!(d.layer("L9").map(|l| l.name.as_str()), Some("l9"));
|
||||
check_layers(&mut d, &["L9"]);
|
||||
// Changed by position, and by a loop over all of them.
|
||||
d.layers[3].name = "Third".into();
|
||||
assert!(!layers_indexed(&d));
|
||||
check_layers(&mut d, &["third"]);
|
||||
for l in &mut d.layers {
|
||||
l.name.make_ascii_uppercase();
|
||||
}
|
||||
assert!(!layers_indexed(&d));
|
||||
check_layers(&mut d, &["doors"]);
|
||||
|
||||
// Undo: a snapshot keeps the table it was taken with, and its index.
|
||||
let names = |d: &Drawing| d.layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();
|
||||
assert!(layers_indexed(&d));
|
||||
let (snap, before) = (d.clone(), names(&d));
|
||||
d.layers.clear();
|
||||
d.layers.push(Layer::new("Only"));
|
||||
check_layers(&mut d, &["only", "L1"]);
|
||||
d = snap;
|
||||
assert!(layers_indexed(&d));
|
||||
assert_eq!(names(&d), before);
|
||||
check_layers(&mut d, &["THIRD"]);
|
||||
// The whole table replaced (LAYERP, LAYUNISO).
|
||||
d.layers = vec![Layer::new("0"), Layer::new("A"), Layer::new("a")].into();
|
||||
check_layers(&mut d, &["a"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_lookups_find_an_exact_name_else_the_first_without_case_through_every_change() {
|
||||
let block = |name: &str| Arc::new(Block::new(name));
|
||||
let mut d = Drawing::new_imperial();
|
||||
for name in (0..150).map(|i| format!("B{i}")).chain(["Door", "DOOR", "door"].map(String::from)) {
|
||||
d.blocks.insert(name.clone(), block(&name));
|
||||
}
|
||||
check_blocks(&d, &["dOOR", "missing"]);
|
||||
// An exact name wins; otherwise the first in name order ("DOOR" < "Door" < "door").
|
||||
assert_eq!(d.block("door").map(|b| b.name.as_str()), Some("door"));
|
||||
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("DOOR"));
|
||||
|
||||
// Removed (PURGE, a definition replaced under another name).
|
||||
d.blocks.remove("DOOR");
|
||||
assert!(!blocks_indexed(&d));
|
||||
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("Door"));
|
||||
check_blocks(&d, &["dOOR"]);
|
||||
// Added before the first of that name.
|
||||
d.blocks.insert("DoOr".into(), block("DoOr"));
|
||||
assert!(!blocks_indexed(&d));
|
||||
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("DoOr"));
|
||||
check_blocks(&d, &["dOOR"]);
|
||||
// Renamed (RENAME takes the definition out and puts it back under the new name).
|
||||
let b1 = d.blocks.remove("B1").unwrap();
|
||||
d.blocks.insert("Renamed".into(), b1);
|
||||
assert!(d.block("b1").is_none() && d.block("RENAMED").is_some());
|
||||
check_blocks(&d, &["b1", "RENAMED"]);
|
||||
// Redefined in place, and changed through get_mut: the names stay.
|
||||
d.blocks.insert("Door".into(), block("Door"));
|
||||
assert!(!blocks_indexed(&d));
|
||||
check_blocks(&d, &["DOOR"]);
|
||||
Arc::make_mut(d.blocks.get_mut("B2").unwrap()).description = "changed".into();
|
||||
assert!(!blocks_indexed(&d));
|
||||
check_blocks(&d, &["b2"]);
|
||||
// Many removed at once.
|
||||
d.blocks.retain(|k, _| !k.starts_with("B9"));
|
||||
assert!(!blocks_indexed(&d));
|
||||
check_blocks(&d, &["b9", "b90"]);
|
||||
// A loop over all of them.
|
||||
for (_, b) in &mut d.blocks {
|
||||
Arc::make_mut(b).description = "looped".into();
|
||||
}
|
||||
assert!(!blocks_indexed(&d));
|
||||
check_blocks(&d, &["b3"]);
|
||||
|
||||
// Undo: a snapshot keeps the table it was taken with, and its index.
|
||||
let snap = d.clone();
|
||||
d.blocks.clear();
|
||||
d.blocks.insert("Only".into(), block("Only"));
|
||||
check_blocks(&d, &["only", "door"]);
|
||||
d = snap;
|
||||
assert!(blocks_indexed(&d));
|
||||
check_blocks(&d, &["DOOR", "only"]);
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -1018,8 +1018,8 @@ impl LayerState {
|
||||
pub const ALL: u32 = 2047;
|
||||
|
||||
/// A state of every property of `layers`, with `current` the layer restoring makes current.
|
||||
pub fn new(name: impl Into<String>, layers: impl Into<Vec<Layer>>, current: impl Into<String>) -> Self {
|
||||
LayerState { name: name.into(), layers: layers.into(), current: current.into(), ..LayerState::default() }
|
||||
pub fn new(name: impl Into<String>, layers: Vec<Layer>, current: impl Into<String>) -> Self {
|
||||
LayerState { name: name.into(), layers, current: current.into(), ..LayerState::default() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-196
@@ -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));
|
||||
}
|
||||
|
||||
@@ -271,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();
|
||||
@@ -930,158 +890,3 @@ fn constant_values_count_in_extents_as_attmode_shows_them() {
|
||||
assert!(top(1, true) < 40.0);
|
||||
assert!(top(2, true) > 40.0, "ATTMODE 2 shows an invisible one");
|
||||
}
|
||||
|
||||
#[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
|
||||
// attribute without a layer of its own (in a third case) lies on the first one's.
|
||||
let top = |defs: [(&str, &str); 2]| {
|
||||
let mut d = Drawing::new_imperial();
|
||||
let mut frozen = Layer::new("AFRZ");
|
||||
frozen.frozen = true;
|
||||
d.layers.push(frozen);
|
||||
let mut blk = Block::new("B");
|
||||
blk.entities.push(on_layer("0", line((0.0, 0.0), (1.0, 1.0)), 1));
|
||||
for (h, (layer, tag)) in (2..).zip(defs) {
|
||||
blk.entities.push(on_layer(layer, EntityKind::AttDef(plain_attrib(tag)), h));
|
||||
}
|
||||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||||
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
|
||||
let mut a = plain_attrib("Tag");
|
||||
a.text.insert = Vec3::new(0.0, 500.0, 0.0);
|
||||
ins.attribs.push(a);
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
extents_pair(&d).1.y
|
||||
};
|
||||
assert!(top([("AFRZ", "TAG"), ("0", "tag")]) < 100.0, "on the first definition's frozen layer");
|
||||
assert!(top([("0", "tag"), ("AFRZ", "TAG")]) > 400.0, "on the first definition's layer 0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_definitions_of_one_tag_all_count_unless_the_reference_carries_the_tag() {
|
||||
// Two constant definitions of one tag, in different case: a reference draws both values,
|
||||
// unless it carries an attribute of that tag (in a third case), which stands for both.
|
||||
let max = |attribs: Vec<Attrib>| {
|
||||
let mut d = Drawing::new_imperial();
|
||||
let mut blk = Block::new("B");
|
||||
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
|
||||
for (h, tag, at) in [(2, "C", Vec3::new(0.0, 5000.0, 0.0)), (3, "c", Vec3::new(7000.0, 0.0, 0.0))] {
|
||||
let mut a = plain_attrib(tag);
|
||||
a.text.insert = at;
|
||||
a.constant = true;
|
||||
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a)));
|
||||
}
|
||||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||||
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
|
||||
ins.attribs = attribs;
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
extents_pair(&d).1
|
||||
};
|
||||
for shown in [max(vec![]), max(vec![plain_attrib("D")])] {
|
||||
assert!(shown.x > 6000.0 && shown.y > 4000.0, "both values count: {shown:?}");
|
||||
}
|
||||
let carried = max(vec![plain_attrib("D"), plain_attrib("Cc"), plain_attrib("C")]);
|
||||
assert!(carried.x < 100.0 && carried.y < 100.0, "neither value counts: {carried:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() {
|
||||
// #1923: one reference with N attributes (none with a layer of its own) of a block with N
|
||||
// constant definitions, the tags N long ones alike up to their last characters, no attribute's
|
||||
// a definition's. Comparing each attribute with each definition, for its layer and for which
|
||||
// constant values the reference carries, cost N x N comparisons of whole tags (many seconds
|
||||
// here); one lookup per attribute or definition costs milliseconds.
|
||||
const N: usize = 4000;
|
||||
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
|
||||
let mut d = Drawing::new_imperial();
|
||||
let mut blk = Block::new("B");
|
||||
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
|
||||
for (h, i) in (2..).zip(0..N) {
|
||||
let mut a = plain_attrib(&tag('D', i));
|
||||
a.constant = true;
|
||||
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a)));
|
||||
}
|
||||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||||
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 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
|
||||
/// blocks and N references to blocks it does not have, opened in N² name comparisons (#1924).
|
||||
#[test]
|
||||
fn layer_and_block_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
const N: usize = 60_000;
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.layers = (0..N).map(|i| Layer::new(&format!("L{i}"))).collect();
|
||||
for i in 0..N {
|
||||
let name = format!("B{i}");
|
||||
d.blocks.insert(name.clone(), std::sync::Arc::new(Block::new(&name)));
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
for i in 0..N {
|
||||
assert!(d.layer(&format!("l{i}")).is_some() && d.layer(&format!("M{i}")).is_none());
|
||||
assert!(d.block(&format!("b{i}")).is_some() && d.block(&format!("Z{i}")).is_none());
|
||||
}
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
}
|
||||
|
||||
/// Table entries for the cost tests below.
|
||||
const NAMED: usize = 40_000;
|
||||
|
||||
/// A name of 54 bytes whose first 48 every such name of `kind` shares, so comparing two costs
|
||||
/// about 50 bytes and not a length check, as in a crafted file.
|
||||
fn long_name(kind: &str, tail: &str) -> String {
|
||||
format!("{kind}{}{tail}", "x".repeat(48 - kind.len()))
|
||||
}
|
||||
|
||||
/// The [`NAMED`] names `long_name(kind, "000000")`, `..."000001"`, ...
|
||||
fn long_names(kind: &str) -> impl Iterator<Item = String> + '_ {
|
||||
(0..NAMED).map(move |i| long_name(kind, &format!("{i:06}")))
|
||||
}
|
||||
|
||||
/// Each of a table's [`NAMED`] names is looked up in other case (found) and as a missing name of
|
||||
/// the same length, well within a bound that scanning the table for each lookup misses: a file of
|
||||
/// N entries and N objects naming one it lacks, or names in other case, drew in N² name
|
||||
/// comparisons (#1924).
|
||||
fn lookups_by_name_are_quick(kind: &str, found: impl Fn(&str) -> bool) {
|
||||
let started = std::time::Instant::now();
|
||||
for i in 0..NAMED {
|
||||
assert!(found(&long_name(kind, &format!("{i:06}")).to_ascii_uppercase()), "{kind} {i}");
|
||||
assert!(!found(&long_name(kind, &format!("z{i:05}"))), "{kind} {i}");
|
||||
}
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linetype_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.linetypes = long_names("LT").map(|n| Linetype::simple(&n, "", &[0.5, -0.25])).collect();
|
||||
lookups_by_name_are_quick("LT", |n| d.linetype(n).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_style_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.text_styles = long_names("S").map(|name| TextStyle { name, ..TextStyle::default() }).collect();
|
||||
lookups_by_name_are_quick("S", |n| d.text_style(n).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dim_style_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.dim_styles = long_names("D").map(|name| DimStyle { name, ..DimStyle::default() }).collect();
|
||||
lookups_by_name_are_quick("D", |n| d.dim_style(n).is_some());
|
||||
}
|
||||
|
||||
/// Each change to a drawing looks up every layout of the drawing before it by name (the check for
|
||||
/// non-finite results), so a drawing of N layouts cost N² name comparisons per command.
|
||||
#[test]
|
||||
fn layout_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.layouts = long_names("L").zip(1..).map(|(n, tab)| Layout::new(&n, tab)).collect();
|
||||
lookups_by_name_are_quick("L", |n| d.layout(n).is_some());
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Dimensions and leaders: DIMLINEAR, DIMALIGNED, DIMRADIUS, DIMDIAMETER, DIMANGULAR, DIMARC,
|
||||
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, QLEADER, DIMOVERRIDE,
|
||||
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, DIMOVERRIDE,
|
||||
//! DIMREASSOCIATE / DIMDISASSOCIATE, DIMTEDIT, DIMSPACE; DIMEDIT, DIMJOGGED, DIMJOGLINE,
|
||||
//! DIMBREAK and DIMINSPECT in `annotate_dimedit.rs`.
|
||||
|
||||
@@ -19,7 +19,6 @@ mod edit;
|
||||
mod leader;
|
||||
mod linear;
|
||||
mod mleader;
|
||||
mod qleader;
|
||||
mod radial;
|
||||
|
||||
use angular::{AngularM, ArcLenM, run_angular, run_arclen};
|
||||
@@ -28,7 +27,6 @@ use common::{DimText, add_dim, assoc_enabled, circle_of, dim, pick_at};
|
||||
use edit::{DimSpaceM, OverrideM, dims_of, run_dimspace, run_dimtedit, run_disassociate, run_override, run_reassociate, run_tedit, run_update};
|
||||
use linear::{ChainM, LinearM, MAX_CHAIN, OrdinateM, run_aligned, run_baseline, run_continue, run_linear, run_ordinate};
|
||||
use mleader::{MLeaderM, run_leader, run_mleader};
|
||||
use qleader::{QLeaderM, run_qleader};
|
||||
use radial::{RadialM, run_diameter, run_radius};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -95,10 +93,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.alias(&["lead"])
|
||||
.params("{points: [[x,y]...], text?}")
|
||||
.interactive(|_| Ok(Box::new(leader::LeaderM::default()))),
|
||||
CommandSpec::new("qleader", "Quick Leader", run_qleader)
|
||||
.alias(&["le"])
|
||||
.params("{points: [[x,y], [x,y], [x,y]?] (2 or 3), width?: text width (default 0), text?: lines split at \\n}")
|
||||
.interactive(|_| Ok(Box::new(QLeaderM::default()))),
|
||||
CommandSpec::new("dimstyle.update", "Update", run_update)
|
||||
.menu(&["Dimension", "Update"])
|
||||
.params("{handles?}")
|
||||
|
||||
@@ -42,13 +42,8 @@ pub(super) struct LeaderM {
|
||||
}
|
||||
|
||||
/// What follows the leader.
|
||||
pub(super) enum Annotation {
|
||||
enum Annotation {
|
||||
Text(Vec<String>),
|
||||
/// QLEADER's text: its lines and its width.
|
||||
Quick {
|
||||
lines: Vec<String>,
|
||||
width: f64,
|
||||
},
|
||||
/// A copy of a text or multiline text: its contents, height, width and style.
|
||||
Copy(MText),
|
||||
None,
|
||||
@@ -268,13 +263,13 @@ pub(super) fn json_leader(s: &mut Session, pts: &[Vec2], text: Option<&str>) ->
|
||||
}
|
||||
|
||||
/// Draw the leader through `pts` and its annotation, as AutoCAD 2024 places them; their handles.
|
||||
pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
|
||||
fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
|
||||
let (Some(&end), Some(&before)) = (pts.last(), pts.len().checked_sub(2).and_then(|i| pts.get(i))) else { return Ok(Vec::new()) };
|
||||
let z = sizes(s);
|
||||
// The side the leader runs to: right unless its last segment runs left.
|
||||
let dir = if end.x < before.x { -1.0 } else { 1.0 };
|
||||
let mut vertices = pts.to_vec();
|
||||
if let Annotation::Text(_) | Annotation::Quick { .. } | Annotation::Copy(_) = ann {
|
||||
if let Annotation::Text(_) | Annotation::Copy(_) = ann {
|
||||
let d = end - before;
|
||||
// A copied text is centred on its line, and with DIMTAD on that line is above the leader:
|
||||
// the leader ends half the text height lower.
|
||||
@@ -315,23 +310,6 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
|
||||
columns: None,
|
||||
}))?)
|
||||
}
|
||||
Annotation::Quick { lines, width } => {
|
||||
// The middle of the first line level with the end on the right, of the last line on
|
||||
// the left, whatever DIMTAD.
|
||||
let (attach, lift) = if dir > 0.0 { (1, z.text / 2.0) } else { (9, -z.text / 2.0) };
|
||||
Some(s.add_entity(EntityKind::MText(MText {
|
||||
insert: v3(end + Vec2::new(dir * z.gap, lift)),
|
||||
height: z.text,
|
||||
width,
|
||||
attach,
|
||||
rotation: 0.0,
|
||||
style: z.text_style,
|
||||
contents: lines.join("\\P"),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
}))?)
|
||||
}
|
||||
Annotation::Copy(m) => {
|
||||
let lift = if z.above { z.gap } else { 0.0 };
|
||||
let attach = if dir > 0.0 { 4 } else { 6 };
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
//! QLEADER at the command line, as AutoCAD 2024 runs it with its default settings (accoreconsole,
|
||||
//! synthetic drawings): up to three points, a text width, then lines of text.
|
||||
//!
|
||||
//! The leader is LEADER's, with an arrow and a hook line DIMASZ long when its last segment is more
|
||||
//! than 15° off horizontal and text follows. The multiline text sits DIMGAP past the leader's end,
|
||||
//! as wide as the width given: with the middle of its first line level with the end when the
|
||||
//! leader runs right, and of its last line when it runs left, whatever DIMTAD. Enter at the first
|
||||
//! line of text leaves the leader without text. The Settings dialog isn't available yet.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::leader::{Annotation, add_leader};
|
||||
use super::{Accept, Input, Interactive, Prompt, Result, Session, Step, Vec2, bad, points_param, str_param};
|
||||
use crate::cmd::size_param;
|
||||
|
||||
/// QLEADER's default number of leader points.
|
||||
const MAX_POINTS: usize = 3;
|
||||
|
||||
#[derive(Clone, Copy, Default, PartialEq)]
|
||||
enum Ask {
|
||||
#[default]
|
||||
Points,
|
||||
Width,
|
||||
FirstLine,
|
||||
NextLine,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct QLeaderM {
|
||||
ask: Ask,
|
||||
pts: Vec<Vec2>,
|
||||
width: f64,
|
||||
lines: Vec<String>,
|
||||
}
|
||||
|
||||
impl Interactive for QLeaderM {
|
||||
fn name(&self) -> &'static str {
|
||||
"QLEADER"
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
let last = self.pts.last().copied();
|
||||
match self.ask {
|
||||
Ask::Points if self.pts.is_empty() => Prompt::new("Specify first leader point,", Accept::POINT).kw(&["Settings"]).default("Settings"),
|
||||
Ask::Points => Prompt::new("Specify next point", Accept::POINT).base_opt(last),
|
||||
// The width isn't remembered: AutoCAD 2024 offers 0 again after a width of 20.
|
||||
Ask::Width => Prompt::new("Specify text width", Accept::POINT_OR_NUMBER).distance().default("0").base_opt(last),
|
||||
Ask::FirstLine => Prompt::new("Enter first line of annotation text", Accept::TEXT).default("Mtext"),
|
||||
Ask::NextLine => Prompt::new("Enter next line of annotation text", Accept::TEXT),
|
||||
}
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
match self.ask {
|
||||
Ask::Points => match i {
|
||||
Input::Point(p) => {
|
||||
self.pts.push(p);
|
||||
if self.pts.len() == MAX_POINTS {
|
||||
self.ask = Ask::Width;
|
||||
}
|
||||
}
|
||||
Input::Enter | Input::Keyword(_) if self.pts.is_empty() => s.echo("The QLEADER Settings dialog is not available yet."),
|
||||
// Enter after one point: no leader.
|
||||
Input::Enter if self.pts.len() < 2 => return Ok(Step::Done),
|
||||
Input::Enter => self.ask = Ask::Width,
|
||||
_ => {}
|
||||
},
|
||||
Ask::Width => {
|
||||
// A point gives the width as its distance from the leader's end; a negative
|
||||
// width is none.
|
||||
let width = match i {
|
||||
Input::Point(p) => self.pts.last().map(|e| e.dist(p)),
|
||||
Input::Text(t) => crate::units::parse_distance(&t),
|
||||
Input::Enter => Some(0.0),
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
let finite = width.filter(|w| w.is_finite());
|
||||
self.width = finite.ok_or_else(|| crate::EngineError::Other("Requires numeric distance or two points.".into()))?.max(0.0);
|
||||
self.ask = Ask::FirstLine;
|
||||
}
|
||||
// Only typed text and Enter: a click in the drawing is no line of text, as at TEXT's.
|
||||
Ask::FirstLine | Ask::NextLine => match i {
|
||||
Input::Text(t) if !t.is_empty() => {
|
||||
self.lines.push(t);
|
||||
self.ask = Ask::NextLine;
|
||||
}
|
||||
Input::Text(_) | Input::Enter => {
|
||||
let lines = std::mem::take(&mut self.lines);
|
||||
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width: self.width } };
|
||||
add_leader(s, &std::mem::take(&mut self.pts), false, true, ann)?;
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
}
|
||||
|
||||
/// QLEADER's JSON form: a leader through 2 or 3 `points`, with `text` (one line per line of it) as wide
|
||||
/// as `width`, placed as the command line places them. The handles of the leader and its text.
|
||||
pub(super) fn run_qleader(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("points").is_none_or(Value::is_null) {
|
||||
return Err(bad("qleader", "`points` is required"));
|
||||
}
|
||||
let pts = points_param(p, "points").ok_or_else(|| bad("qleader", "`points` must be a list of [x, y] points"))?;
|
||||
if !(2..=MAX_POINTS).contains(&pts.len()) {
|
||||
return Err(bad("qleader", "`points` takes 2 or 3 points"));
|
||||
}
|
||||
let width = size_param("qleader", p, "width", true)?.unwrap_or(0.0);
|
||||
if p.get("text").is_some_and(|t| !t.is_null() && !t.is_string()) {
|
||||
return Err(bad("qleader", "`text` must be a string"));
|
||||
}
|
||||
// Empty lines at the end are dropped, as the command line ends at one: a left-running leader
|
||||
// would otherwise sit level with a blank last line. Text with nothing left is no text.
|
||||
let mut lines: Vec<String> = str_param(p, "text").map(|t| t.lines().map(str::to_string).collect()).unwrap_or_default();
|
||||
while lines.last().is_some_and(String::is_empty) {
|
||||
lines.pop();
|
||||
}
|
||||
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width } };
|
||||
let hs = add_leader(s, &pts, false, true, ann)?;
|
||||
Ok(json!({ "handles": hs.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
|
||||
}
|
||||
@@ -386,18 +386,16 @@ fn fmt(v: f64) -> String {
|
||||
format!("{v:.4}")
|
||||
}
|
||||
|
||||
/// A count typed at a prompt (Enter keeps `cur`); `None` for inputs the prompt ignores. A whole
|
||||
/// number as typed: AutoCAD 2024 takes +3 and 03 at its array counts and refuses 5.0, 1e1, 8/2
|
||||
/// and 3' (measured at ARRAYRECT's rows and columns, ARRAYPOLAR's items and rows, and -ARRAY).
|
||||
/// A count typed at a prompt (Enter keeps `cur`); `None` for inputs the prompt ignores.
|
||||
fn count(i: &Input, cur: u64, max: u64) -> Result<Option<u64>> {
|
||||
match i {
|
||||
Input::Enter => Ok(Some(cur)),
|
||||
Input::Text(t) => t
|
||||
.trim()
|
||||
.parse::<u64>()
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|v| (1..=max).contains(v))
|
||||
.map(Some)
|
||||
.filter(|v| v.fract() == 0.0 && *v >= 1.0 && *v <= max as f64)
|
||||
.map(|v| Some(v as u64))
|
||||
.ok_or_else(|| other(format!("Requires an integer between 1 and {max} (MAXARRAY limits the size of the array)."))),
|
||||
_ => Ok(None),
|
||||
}
|
||||
@@ -439,7 +437,7 @@ fn run_array(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// A count parameter (at least 1); a missing key gives the default, an invalid value is refused.
|
||||
pub(crate) fn count_or(cmd: &str, p: &Value, key: &str, default: u64) -> Result<u64> {
|
||||
fn count_or(cmd: &str, p: &Value, key: &str, default: u64) -> Result<u64> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(default),
|
||||
Some(v) => v.as_u64().filter(|n| *n >= 1).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of at least 1"))),
|
||||
|
||||
+59
-182
@@ -403,14 +403,13 @@ fn run_insert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// MINSERT's JSON form: INSERT's parameters and the grid.
|
||||
fn run_minsert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A whole number, as the array commands' JSON counts are: 2.0 and 1e2 are refused too.
|
||||
let count = |key: &str| -> Result<u32> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(1),
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.filter(|n| (1..=Grid::MAX).contains(n))
|
||||
.as_f64()
|
||||
.filter(|n| n.fract() == 0.0 && *n >= 1.0 && *n <= f64::from(Grid::MAX))
|
||||
.map(|n| n as u32)
|
||||
.ok_or_else(|| bad("minsert", format!("`{key}` must be an integer between 1 and {}", Grid::MAX))),
|
||||
}
|
||||
};
|
||||
@@ -834,35 +833,11 @@ enum InsStage {
|
||||
/// rows).
|
||||
Cell(Vec2),
|
||||
ColSpacing,
|
||||
/// The second of two points a preset or the column spacing takes after a point (AutoCAD 2024
|
||||
/// asks "Specify second point:"), from the first.
|
||||
Second(TwoPoints, Vec2),
|
||||
Attribs,
|
||||
/// A Verify attribute asked again.
|
||||
Verify,
|
||||
}
|
||||
|
||||
/// What two points give: a preset scale factor (all axes, or one) or the column spacing by their
|
||||
/// distance, the preset rotation by their direction.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum TwoPoints {
|
||||
Scale,
|
||||
Axis(usize),
|
||||
Rotation,
|
||||
ColSpacing,
|
||||
}
|
||||
|
||||
// AutoCAD 2024's messages at INSERT's and MINSERT's scale, rotation and spacing prompts (measured):
|
||||
// a scale factor of 0; anything else that isn't a number where two points give a distance or an
|
||||
// angle, where a point gives the distance from the insertion point, and where only a number does.
|
||||
const NONZERO: &str = "Value must be nonzero.";
|
||||
/// Exploded INSERT's scale factor, which must be positive.
|
||||
const POSITIVE: &str = "Value must be positive and nonzero.";
|
||||
const TWO_POINTS: &str = "Requires numeric distance or two points.";
|
||||
const ANGLE_TWO_POINTS: &str = "Requires valid numeric angle or two points.";
|
||||
const SECOND_POINT: &str = "Requires numeric distance or second point.";
|
||||
const NUMERIC: &str = "Requires numeric value.";
|
||||
|
||||
#[derive(Default)]
|
||||
struct InsertM {
|
||||
stage: InsStage,
|
||||
@@ -1043,66 +1018,6 @@ impl InsertM {
|
||||
}
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// The Scale preset `f` for every axis.
|
||||
fn preset_scale(&mut self, s: &mut Session, f: f64) -> Result<Step> {
|
||||
self.scale = Some(Vec2::new(f, f));
|
||||
self.z_scale = Some(f.abs());
|
||||
// An axis preset after it changes that axis alone (Scale -3 then X 2: 2/-3/3).
|
||||
self.axes = [Some(f), Some(f), Some(f.abs())];
|
||||
// Exploded insertion asks its one scale factor after the insertion point.
|
||||
if self.at.is_some() {
|
||||
return self.advance(s);
|
||||
}
|
||||
self.stage = InsStage::Point;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
/// One axis preset: the others are 1, and no scale factors are asked after the point.
|
||||
fn preset_axis(&mut self, ax: usize, f: f64) -> Result<Step> {
|
||||
if let Some(a) = self.axes.get_mut(ax) {
|
||||
*a = Some(f);
|
||||
}
|
||||
let [x, y, z] = self.axes.map(|a| a.unwrap_or(1.0));
|
||||
self.scale = Some(Vec2::new(x, y));
|
||||
self.z_scale = Some(z.abs());
|
||||
self.stage = InsStage::Point;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
fn preset_rotation(&mut self, r: f64) -> Result<Step> {
|
||||
self.rotation = Some(r);
|
||||
self.stage = InsStage::Point;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
/// The second of two points (AutoCAD 2024, measured): their distance is a preset scale factor
|
||||
/// (0 refused) or the column spacing (0 taken), their direction the preset rotation. Enter
|
||||
/// keeps a preset's default and is refused for the spacing, as anything else is; a refusal asks
|
||||
/// the first prompt again.
|
||||
fn second_point(&mut self, s: &mut Session, what: TwoPoints, a: Vec2, i: Input) -> Result<Step> {
|
||||
let (first, refused) = match what {
|
||||
TwoPoints::Scale => (InsStage::PresetScale, TWO_POINTS),
|
||||
TwoPoints::Axis(ax) => (InsStage::PresetAxis(ax), TWO_POINTS),
|
||||
TwoPoints::Rotation => (InsStage::PresetRotation, ANGLE_TWO_POINTS),
|
||||
TwoPoints::ColSpacing => (InsStage::ColSpacing, TWO_POINTS),
|
||||
};
|
||||
self.stage = first;
|
||||
match (what, i) {
|
||||
(TwoPoints::ColSpacing, Input::Point(b)) => {
|
||||
self.col_spacing = Some(a.dist(b));
|
||||
self.advance(s)
|
||||
}
|
||||
(TwoPoints::Rotation, Input::Point(b)) => self.preset_rotation(a.angle_to(b)),
|
||||
(TwoPoints::Rotation, Input::Enter) => self.preset_rotation(0.0),
|
||||
(TwoPoints::Scale | TwoPoints::Axis(_), Input::Point(b)) if a.dist(b) == 0.0 => Err(EngineError::Other(NONZERO.into())),
|
||||
(TwoPoints::Scale, Input::Point(b)) => self.preset_scale(s, a.dist(b)),
|
||||
(TwoPoints::Scale, Input::Enter) => self.preset_scale(s, 1.0),
|
||||
(TwoPoints::Axis(ax), Input::Point(b)) => self.preset_axis(ax, a.dist(b)),
|
||||
(TwoPoints::Axis(ax), Input::Enter) => self.preset_axis(ax, 1.0),
|
||||
_ => Err(EngineError::Other(refused.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A distance typed at MINSERT's grid prompts: any finite number, negative or 0 too.
|
||||
@@ -1110,14 +1025,8 @@ fn distance(t: &str) -> Result<f64> {
|
||||
number(t).filter(|v| v.is_finite()).ok_or_else(|| EngineError::Other("Requires a distance.".into()))
|
||||
}
|
||||
|
||||
/// A scale factor typed at `t`: 0 gets AutoCAD 2024's "Value must be nonzero.", anything that
|
||||
/// isn't a number the prompt's own message.
|
||||
fn nonzero(t: &str, not_a_number: &str) -> Result<f64> {
|
||||
let v = number(t).ok_or_else(|| EngineError::Other(not_a_number.into()))?;
|
||||
if v == 0.0 {
|
||||
return Err(EngineError::Other(NONZERO.into()));
|
||||
}
|
||||
Ok(v)
|
||||
fn nonzero(t: &str) -> Result<f64> {
|
||||
number(t).filter(|v| *v != 0.0).ok_or_else(|| EngineError::Other("Requires a non-zero number.".into()))
|
||||
}
|
||||
|
||||
impl Interactive for InsertM {
|
||||
@@ -1138,31 +1047,22 @@ impl Interactive for InsertM {
|
||||
}
|
||||
InsStage::Point => Prompt::new("Specify insertion point", Accept::POINT).kw(&["Basepoint", "Scale", "X", "Y", "Z", "Rotate"]),
|
||||
InsStage::BasePoint => Prompt::new("Specify base point", Accept::POINT),
|
||||
// Exploded, after the insertion point, it takes a number only.
|
||||
InsStage::PresetScale if self.at.is_some() => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).default("1"),
|
||||
InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::POINT_OR_NUMBER).default("1"),
|
||||
InsStage::PresetAxis(i) => {
|
||||
Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::POINT_OR_NUMBER).default("1")
|
||||
}
|
||||
// Typed text is read as before (`<<45` the angle, not an override for a point); a point
|
||||
// still comes from a click or LISP.
|
||||
InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).default("1"),
|
||||
InsStage::PresetAxis(i) => Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::NUMBER).default("1"),
|
||||
InsStage::PresetRotation => Prompt::new("Specify rotation angle", Accept::NUMBER).default("0"),
|
||||
// Text is read here, not taken as a distance along the rubber band: the core console
|
||||
// refuses 5 at this prompt (measured).
|
||||
InsStage::Second(_, a) => Prompt::new("Specify second point", Accept::POINT_OR_NUMBER).base(a),
|
||||
InsStage::XScale if self.xyz => Prompt::new("Specify X scale factor", Accept::POINT_OR_NUMBER).kw(&["Corner"]).default("1").base(at),
|
||||
InsStage::XScale => {
|
||||
Prompt::new("Enter X scale factor, specify opposite corner", Accept::POINT_OR_NUMBER).kw(&["Corner", "XYZ"]).default("1").base(at)
|
||||
}
|
||||
InsStage::Corner => Prompt::new("Specify opposite corner", Accept::POINT).base(at),
|
||||
InsStage::YScale => Prompt::new("Enter Y scale factor", Accept::NUMBER).default("use X scale factor"),
|
||||
InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::POINT_OR_NUMBER).default("use X scale factor").base(at),
|
||||
InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::NUMBER).default("use X scale factor"),
|
||||
InsStage::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER).default("0").base(at),
|
||||
InsStage::Rows => Prompt::new("Enter number of rows (---)", Accept::NUMBER).default("1"),
|
||||
InsStage::Cols => Prompt::new("Enter number of columns (|||)", Accept::NUMBER).default("1"),
|
||||
InsStage::RowSpacing => Prompt::new("Enter distance between rows or specify unit cell (---)", Accept::POINT_OR_NUMBER),
|
||||
InsStage::Cell(a) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a),
|
||||
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::POINT_OR_NUMBER),
|
||||
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::NUMBER),
|
||||
InsStage::Attribs => {
|
||||
let (_, prompt, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
|
||||
let p = Prompt::new(if prompt.is_empty() { "Enter attribute value".into() } else { prompt }, Accept::TEXT);
|
||||
@@ -1238,58 +1138,45 @@ impl Interactive for InsertM {
|
||||
self.stage = InsStage::Point;
|
||||
}
|
||||
}
|
||||
// Exploded, after the insertion point: a positive number only (AutoCAD 2024 refuses a
|
||||
// point and x with "Requires numeric value.", 0 and -2 with "Value must be positive and
|
||||
// nonzero.", measured).
|
||||
InsStage::PresetScale if self.at.is_some() => {
|
||||
return match i {
|
||||
Input::Text(t) => {
|
||||
let f = number(&t).ok_or_else(|| EngineError::Other(NUMERIC.into()))?;
|
||||
let f = Some(f).filter(|f| *f > 0.0).ok_or_else(|| EngineError::Other(POSITIVE.into()))?;
|
||||
self.preset_scale(s, f)
|
||||
}
|
||||
Input::Enter => self.preset_scale(s, 1.0),
|
||||
_ => Err(EngineError::Other(NUMERIC.into())),
|
||||
};
|
||||
}
|
||||
// A point at a preset is the first of two (AutoCAD 2024, measured).
|
||||
InsStage::PresetScale => {
|
||||
return match i {
|
||||
Input::Point(p) => {
|
||||
self.stage = InsStage::Second(TwoPoints::Scale, p);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Input::Text(t) => self.preset_scale(s, nonzero(&t, TWO_POINTS)?),
|
||||
Input::Enter => self.preset_scale(s, 1.0),
|
||||
_ => Err(EngineError::Other(TWO_POINTS.into())),
|
||||
let f = match i {
|
||||
Input::Text(t) => nonzero(&t)?,
|
||||
Input::Enter => 1.0,
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
self.scale = Some(Vec2::new(f, f));
|
||||
self.z_scale = Some(f.abs());
|
||||
// An axis preset after it changes that axis alone (Scale -3 then X 2: 2/-3/3).
|
||||
self.axes = [Some(f), Some(f), Some(f.abs())];
|
||||
// Exploded insertion asks its one scale factor after the insertion point.
|
||||
if self.at.is_some() {
|
||||
return self.advance(s);
|
||||
}
|
||||
self.stage = InsStage::Point;
|
||||
}
|
||||
// One axis preset: the others are 1, and no scale factors are asked after the point.
|
||||
InsStage::PresetAxis(ax) => {
|
||||
return match i {
|
||||
Input::Point(p) => {
|
||||
self.stage = InsStage::Second(TwoPoints::Axis(ax), p);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Input::Text(t) => self.preset_axis(ax, nonzero(&t, TWO_POINTS)?),
|
||||
Input::Enter => self.preset_axis(ax, 1.0),
|
||||
_ => Err(EngineError::Other(TWO_POINTS.into())),
|
||||
let f = match i {
|
||||
Input::Text(t) => nonzero(&t)?,
|
||||
Input::Enter => 1.0,
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
if let Some(a) = self.axes.get_mut(ax) {
|
||||
*a = Some(f);
|
||||
}
|
||||
let [x, y, z] = self.axes.map(|a| a.unwrap_or(1.0));
|
||||
self.scale = Some(Vec2::new(x, y));
|
||||
self.z_scale = Some(z.abs());
|
||||
self.stage = InsStage::Point;
|
||||
}
|
||||
InsStage::PresetRotation => {
|
||||
return match i {
|
||||
Input::Point(p) => {
|
||||
self.stage = InsStage::Second(TwoPoints::Rotation, p);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Input::Text(t) => {
|
||||
let r = s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other(ANGLE_TWO_POINTS.into()))?;
|
||||
self.preset_rotation(r)
|
||||
}
|
||||
Input::Enter => self.preset_rotation(0.0),
|
||||
_ => Err(EngineError::Other(ANGLE_TWO_POINTS.into())),
|
||||
};
|
||||
self.rotation = Some(match i {
|
||||
Input::Text(t) => s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other("Requires an angle.".into()))?,
|
||||
Input::Enter => 0.0,
|
||||
_ => return Ok(Step::Continue),
|
||||
});
|
||||
self.stage = InsStage::Point;
|
||||
}
|
||||
InsStage::Second(what, a) => return self.second_point(s, what, a, i),
|
||||
InsStage::XScale => match i {
|
||||
Input::Keyword(k) if k == "Corner" => self.stage = InsStage::Corner,
|
||||
Input::Keyword(k) if k == "XYZ" => self.xyz = true,
|
||||
@@ -1298,7 +1185,7 @@ impl Interactive for InsertM {
|
||||
return self.corner_scale(s, sc);
|
||||
}
|
||||
Input::Text(t) => {
|
||||
self.x_scale = Some(nonzero(&t, "Requires a non-zero number.")?);
|
||||
self.x_scale = Some(nonzero(&t)?);
|
||||
self.stage = InsStage::YScale;
|
||||
}
|
||||
Input::Enter => {
|
||||
@@ -1315,11 +1202,10 @@ impl Interactive for InsertM {
|
||||
}
|
||||
InsStage::YScale => {
|
||||
let x = self.x_scale.unwrap_or(1.0);
|
||||
// A number only: AutoCAD 2024 refuses a point here (measured).
|
||||
let y = match i {
|
||||
Input::Text(t) => nonzero(&t, NUMERIC)?,
|
||||
Input::Text(t) => nonzero(&t)?,
|
||||
Input::Enter => x,
|
||||
_ => return Err(EngineError::Other(NUMERIC.into())),
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
self.scale = Some(Vec2::new(x, y));
|
||||
if self.xyz {
|
||||
@@ -1328,15 +1214,11 @@ impl Interactive for InsertM {
|
||||
}
|
||||
return self.advance(s);
|
||||
}
|
||||
// A point gives its distance from the insertion point (AutoCAD 2024, measured).
|
||||
InsStage::ZScale => {
|
||||
self.z_scale = Some(match i {
|
||||
Input::Text(t) => nonzero(&t, SECOND_POINT)?,
|
||||
Input::Text(t) => nonzero(&t)?,
|
||||
Input::Enter => self.x_scale.unwrap_or(1.0).abs(),
|
||||
Input::Point(p) => {
|
||||
Some(self.at.unwrap_or_default().dist(p)).filter(|d| *d != 0.0).ok_or_else(|| EngineError::Other(NONZERO.into()))?
|
||||
}
|
||||
_ => return Err(EngineError::Other(SECOND_POINT.into())),
|
||||
_ => return Ok(Step::Continue),
|
||||
});
|
||||
return self.advance(s);
|
||||
}
|
||||
@@ -1350,14 +1232,17 @@ impl Interactive for InsertM {
|
||||
return self.advance(s);
|
||||
}
|
||||
InsStage::Rows | InsStage::Cols => {
|
||||
// A whole number as typed: AutoCAD 2024 takes +3 and 03 here and refuses 5.0, 5.,
|
||||
// 1e1, 8/2, 3', 4.5 and a point (measured at the rows, and 5.0 and +3 at the columns).
|
||||
let n = match i {
|
||||
Input::Text(t) => t.trim().parse::<u32>().ok().filter(|v| (1..=Grid::MAX).contains(v)),
|
||||
Input::Enter => Some(1),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 1 and {}.", Grid::MAX)))?;
|
||||
Input::Text(t) => t
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|v| v.fract() == 0.0 && *v >= 1.0 && *v <= f64::from(Grid::MAX))
|
||||
.map(|v| v as u32)
|
||||
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 1 and {}.", Grid::MAX)))?,
|
||||
Input::Enter => 1,
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
if self.stage == InsStage::Rows {
|
||||
self.rows = Some(n);
|
||||
} else {
|
||||
@@ -1379,19 +1264,11 @@ impl Interactive for InsertM {
|
||||
return self.advance(s);
|
||||
}
|
||||
}
|
||||
// A distance, or two points (AutoCAD 2024, measured): Enter is refused too.
|
||||
InsStage::ColSpacing => {
|
||||
return match i {
|
||||
Input::Text(t) => {
|
||||
self.col_spacing = Some(number(&t).filter(|v| v.is_finite()).ok_or_else(|| EngineError::Other(TWO_POINTS.into()))?);
|
||||
self.advance(s)
|
||||
}
|
||||
Input::Point(p) => {
|
||||
self.stage = InsStage::Second(TwoPoints::ColSpacing, p);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
_ => Err(EngineError::Other(TWO_POINTS.into())),
|
||||
};
|
||||
if let Input::Text(t) = i {
|
||||
self.col_spacing = Some(distance(&t)?);
|
||||
return self.advance(s);
|
||||
}
|
||||
}
|
||||
InsStage::Attribs => {
|
||||
let (tag, _, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert, TagKey};
|
||||
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::cmd::curves::KW;
|
||||
@@ -102,14 +102,17 @@ impl Interactive for AttdispM {
|
||||
/// Properties set on single attributes (layer, colour, …) go back to the definitions', as in AutoCAD.
|
||||
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();
|
||||
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() };
|
||||
t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
|
||||
t.value = ins
|
||||
.attribs
|
||||
.iter()
|
||||
.find(|a| a.tag.eq_ignore_ascii_case(&ad.tag))
|
||||
.map(|a| a.text.value.clone())
|
||||
.unwrap_or_else(|| ad.text.value.clone());
|
||||
Attrib {
|
||||
tag: ad.tag.clone(),
|
||||
text: t,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! become text with the values they show instead of the block's attribute definitions.
|
||||
|
||||
use cadcraft_color::Color;
|
||||
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, TagKey};
|
||||
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Insert};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::cmd::machines::SelectRun;
|
||||
@@ -28,22 +28,22 @@ fn run_burst(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn burst_pieces(d: &Drawing, e: &Entity) -> Option<Vec<Entity>> {
|
||||
let EntityKind::Insert(ins) = &e.kind else { return None };
|
||||
let mut out: Vec<Entity> = explode_kind(d, e)?.into_iter().filter(|p| !matches!(p.kind, EntityKind::AttDef(_))).collect();
|
||||
// The block's definitions by tag, gathered once for all the attributes (#1923).
|
||||
let defs = d.block(&ins.block).map(|b| b.attdefs_by_tag()).unwrap_or_default();
|
||||
for a in ins.attribs.iter().filter(|a| !a.invisible) {
|
||||
let kind = match a.multiline_text() {
|
||||
Some(m) => EntityKind::MText(m),
|
||||
None => EntityKind::Text(a.text.clone()),
|
||||
};
|
||||
out.push(Entity { handle: Handle(0), common: attrib_common(e, defs.get(&TagKey(&a.tag)).copied(), &a.props), kind });
|
||||
out.push(Entity { handle: Handle(0), common: attrib_common(d, e, ins, &a.tag, &a.props), kind });
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The properties an attribute is drawn with: its own, else those of its definition `def`; layer
|
||||
/// 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 {
|
||||
/// The properties an attribute is drawn with: its own, else its definition's; layer 0 is the
|
||||
/// reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the block's
|
||||
/// objects.
|
||||
fn attrib_common(d: &Drawing, e: &Entity, ins: &Insert, tag: &str, props: &cadcraft_doc::AttribProps) -> Common {
|
||||
let def =
|
||||
d.block(&ins.block).and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(tag))));
|
||||
// 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);
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
use cadcraft_doc::color::Color;
|
||||
use cadcraft_doc::dynblock::{self, GripPart, GripShape};
|
||||
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, TagKey, Transparency};
|
||||
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, Transparency};
|
||||
use cadcraft_geom::Vec2;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -111,10 +111,11 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
|
||||
.collect();
|
||||
// An attribute draws with its definition's properties, except those set on it.
|
||||
let by_block = Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..r.clone() };
|
||||
// The block's definitions by tag, gathered once for all the attributes (#1923).
|
||||
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 def = b.entities.iter().find_map(|e| match &e.kind {
|
||||
EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag) => Some(&e.common),
|
||||
_ => None,
|
||||
});
|
||||
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
|
||||
let kind = match a.multiline_text() {
|
||||
Some(m) => EntityKind::MText(m),
|
||||
@@ -247,51 +248,3 @@ impl Session {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn many_attributes_are_previewed_without_comparing_every_pair_with_the_definitions() {
|
||||
// #1923: a reference with N attributes of a block with N definitions, the tags N long ones
|
||||
// alike up to their last characters, no attribute's a definition's. Looking for each
|
||||
// attribute's definition by comparing it with every one cost N x N comparisons of whole
|
||||
// tags for each preview (many seconds here); the definitions gathered by tag once cost
|
||||
// milliseconds.
|
||||
const N: usize = 4000;
|
||||
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
|
||||
let attrib = |tag: String| cadcraft_doc::Attrib {
|
||||
tag,
|
||||
text: cadcraft_doc::Text {
|
||||
insert: cadcraft_geom::Vec3::ZERO,
|
||||
align_pt: None,
|
||||
height: 1.0,
|
||||
value: "v".into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: Default::default(),
|
||||
valign: Default::default(),
|
||||
},
|
||||
invisible: false,
|
||||
constant: false,
|
||||
prompt: String::new(),
|
||||
props: Default::default(),
|
||||
multiline: None,
|
||||
modes: Default::default(),
|
||||
};
|
||||
let mut d = Drawing::new_metric();
|
||||
let mut blk = cadcraft_doc::Block::new("B");
|
||||
for (h, i) in (1..).zip(0..N) {
|
||||
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(attrib(tag('D', i)))));
|
||||
}
|
||||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||||
let ins = cadcraft_doc::Insert { block: "B".into(), attribs: (0..N).map(|i| attrib(tag('A', i))).collect(), ..Default::default() };
|
||||
let h = d.add(&cadcraft_doc::Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
let t = std::time::Instant::now();
|
||||
assert_eq!(drawn(&d, h).len(), N);
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,7 @@ use cadcraft_geom::{Mat3, Vec2, Vec3};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::super::curves::KW;
|
||||
use super::super::file::{
|
||||
Version, drops_unknown, dwg_notes, lost_message, lost_writing, new_folder, own_version, report_dwg_notes, report_lost, report_new_folder,
|
||||
};
|
||||
use super::super::file::{Version, lost_message, lost_writing, new_folder, own_version, report_lost, report_new_folder};
|
||||
use super::super::machines::{SelOutcome, SelectPhase};
|
||||
use super::super::modify::erase_kept;
|
||||
use super::super::{CommandSpec, bad, point_param, str_param, targets};
|
||||
@@ -48,7 +46,7 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string();
|
||||
let base = point_param(p, "base");
|
||||
let folder = new_folder(&path);
|
||||
let (entities, bytes, lost, version, notes) = match str_param(p, "name") {
|
||||
let (entities, bytes, lost, version) = match str_param(p, "name") {
|
||||
Some("*") => write(s, "wblock", &path, Source::Whole)?,
|
||||
Some(name) => write(s, "wblock", &path, Source::Block(name, base))?,
|
||||
None => write(s, "wblock", &path, Source::Objects(&targets(s, p)?, base.unwrap_or(Vec2::ZERO)))?,
|
||||
@@ -56,7 +54,6 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
|
||||
report_new_folder(s, &mut r, folder);
|
||||
report_lost(s, &mut r, &path, version, &lost);
|
||||
report_dwg_notes(s, &mut r, notes);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
@@ -67,7 +64,7 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("-wblock", "`path` is required"))?.to_string();
|
||||
let base = point_param(p, "base");
|
||||
let folder = new_folder(&path);
|
||||
let (entities, bytes, lost, version, notes) = match str_param(p, "name") {
|
||||
let (entities, bytes, lost, version) = match str_param(p, "name") {
|
||||
Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?,
|
||||
None => {
|
||||
let hs = targets(s, p)?;
|
||||
@@ -83,17 +80,16 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
|
||||
report_new_folder(s, &mut r, folder);
|
||||
report_lost(s, &mut r, &path, version, &lost);
|
||||
report_dwg_notes(s, &mut r, notes);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Write `what` to `path` through the io hooks; the objects written, the file's size, what the
|
||||
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams), the
|
||||
/// version it was written at and what a DWG keeps only in part, for the caller to report as a
|
||||
/// save does. The written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK
|
||||
/// does: its units ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in
|
||||
/// inches and scaled on insert, and its defaults (text size, current styles, annotation scales).
|
||||
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version, Vec<String>)> {
|
||||
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams) and
|
||||
/// the version it was written at, for the caller to report as a save does. The
|
||||
/// written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its units
|
||||
/// ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches and
|
||||
/// scaled on insert, and its defaults (text size, current styles, annotation scales).
|
||||
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version)> {
|
||||
let src = s.doc()?;
|
||||
// The base point becomes the written drawing's origin: by default 0,0 for objects and the
|
||||
// block's base point for a block.
|
||||
@@ -119,19 +115,14 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi
|
||||
// The written drawing's own version: the writer is given no other.
|
||||
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() };
|
||||
Ok((d.model.len(), bytes.len(), lost, version, notes))
|
||||
Ok((d.model.len(), bytes.len(), lost, version))
|
||||
}
|
||||
|
||||
/// Say on the command line what the file written at `path` and `version` left out, and what a
|
||||
/// DWG keeps only in part (`notes`).
|
||||
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>, notes: Vec<String>) {
|
||||
/// Say on the command line what the file written at `path` and `version` left out.
|
||||
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>) {
|
||||
if let Some(msg) = lost_message(path, version, lost) {
|
||||
s.echo(msg);
|
||||
}
|
||||
for note in notes {
|
||||
s.echo(note);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new drawing of `ents`, with `src`'s settings and the layers, linetypes, styles and blocks
|
||||
@@ -350,7 +341,7 @@ impl DashWblockM {
|
||||
|
||||
fn write(&self, s: &mut Session, what: Source) -> Result<Step> {
|
||||
match write(s, "-wblock", &self.path, what) {
|
||||
Ok((.., lost, version, notes)) => echo_not_saved(s, &self.path, version, &lost, notes),
|
||||
Ok((.., lost, version)) => echo_not_saved(s, &self.path, version, &lost),
|
||||
Err(e) => s.echo(e.to_string()),
|
||||
}
|
||||
Ok(Step::Done)
|
||||
@@ -361,8 +352,8 @@ impl DashWblockM {
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) {
|
||||
Ok((.., lost, version, notes)) => {
|
||||
echo_not_saved(s, &self.path, version, &lost, notes);
|
||||
Ok((.., lost, version)) => {
|
||||
echo_not_saved(s, &self.path, version, &lost);
|
||||
erase(s, hs)?;
|
||||
}
|
||||
Err(e) => s.echo(e.to_string()),
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -275,15 +265,13 @@ fn defs_for(src: &Drawing, ents: &[Entity]) -> Drawing {
|
||||
}
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header = src.header.clone();
|
||||
d.layers = pick(&src.layers, &used.layers, |l| &l.name).into();
|
||||
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name).into();
|
||||
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.layers = pick(&src.layers, &used.layers, |l| &l.name);
|
||||
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name);
|
||||
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name);
|
||||
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name);
|
||||
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
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ fn save(s: &mut Session, name: &str, annotative: Option<bool>, replace: bool) ->
|
||||
if let Some(a) = annotative {
|
||||
st.annotative = a;
|
||||
}
|
||||
let name = match d.dim_styles.by_name_mut(&name) {
|
||||
let name = match d.dim_styles.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
|
||||
Some(existing) if replace => {
|
||||
let kept = existing.name.clone();
|
||||
*existing = DimStyle { name: kept.clone(), ..st };
|
||||
|
||||
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("pline", "Polyline", run_pline)
|
||||
.menu(&["Draw", "Polyline"])
|
||||
.alias(&["pl"])
|
||||
.params("{vertices: [[x,y] | {p:[x,y], bulge, startWidth, endWidth}], closed?, width? (default PLINEWID unless vertices give widths)}")
|
||||
.params("{vertices: [[x,y] | {p:[x,y], bulge, startWidth, endWidth}], closed?, width?}")
|
||||
.interactive(|_| Ok(Box::new(PlineM::default()))),
|
||||
CommandSpec::new("circle", "Circle", run_circle)
|
||||
.menu(&["Draw", "Circle", "Center, Radius"])
|
||||
@@ -62,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("rectang", "Rectangle", super::draw2::run_rectang2)
|
||||
.menu(&["Draw", "Rectangle"])
|
||||
.alias(&["rec", "rectangle"])
|
||||
.params("{p1, p2 | dimensions: [l, w] (p2 picks the quadrant) | area + length|breadth (the outline encloses it, cut corners included), rotation? (deg), fillet? (wins over a chamfer), chamfer?: [d1, d2], width?, elevation?, thickness?, center?: bool (p1 is the centre, not a corner; the size spans it evenly)}")
|
||||
.params("{p1, p2 | dimensions: [l, w] (p2 picks the quadrant) | area + length|breadth, rotation? (deg), fillet?, chamfer?: [d1, d2], width?, elevation?, thickness?, center?: bool (p1 is the centre, not a corner; the size spans it evenly)}")
|
||||
.interactive(|_| Ok(Box::new(super::draw2::RectM2::default()))),
|
||||
CommandSpec::new("polygon", "Polygon", run_polygon)
|
||||
.menu(&["Draw", "Polygon"])
|
||||
|
||||
@@ -45,21 +45,15 @@ fn current_elevation(s: &Session) -> Result<f64> {
|
||||
|
||||
pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let raw = p.get("vertices").or_else(|| p.get("points")).and_then(Value::as_array);
|
||||
let mut vertex_widths = false;
|
||||
for v in raw.into_iter().flatten() {
|
||||
vertex_widths |= size_param("pline", v, "startWidth", true)?.is_some() | size_param("pline", v, "endWidth", true)?.is_some();
|
||||
size_param("pline", v, "startWidth", true)?;
|
||||
size_param("pline", v, "endWidth", true)?;
|
||||
}
|
||||
let vs: Vec<PolyVertex> = raw.map(|a| a.iter().filter_map(vertex_value).collect()).unwrap_or_default();
|
||||
if vs.len() < 2 {
|
||||
return Err(bad("pline", "`vertices` needs at least 2 points"));
|
||||
}
|
||||
// Without a width, the polyline starts at PLINEWID as the command does (unless its vertices
|
||||
// give their own widths).
|
||||
let width = match size_param("pline", p, "width", true)? {
|
||||
Some(w) => w,
|
||||
None if vertex_widths => 0.0,
|
||||
None => Some(s.doc()?.header.f64("PLINEWID", 0.0)).filter(|w| w.is_finite() && *w > 0.0).unwrap_or(0.0),
|
||||
};
|
||||
let width = size_param("pline", p, "width", true)?.unwrap_or(0.0);
|
||||
let mut k = lwpoly(vs, bool_or(p, "closed", false));
|
||||
if let EntityKind::LwPolyline(pl) = &mut k {
|
||||
pl.const_width = width;
|
||||
@@ -272,11 +266,8 @@ impl Interactive for PlineM {
|
||||
fn name(&self) -> &'static str {
|
||||
"PLINE"
|
||||
}
|
||||
/// Segments start at PLINEWID, the width the last Width or Halfwidth answer left.
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
self.elevation = current_elevation(s)?;
|
||||
let w = s.doc()?.header.f64("PLINEWID", 0.0);
|
||||
(self.start_w, self.end_w) = if w.is_finite() && w > 0.0 { (w, w) } else { (0.0, 0.0) };
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
@@ -325,11 +316,6 @@ impl Interactive for PlineM {
|
||||
self.end_w = self.start_w;
|
||||
}
|
||||
self.asking_width = if self.asking_width == 1 { 2 } else { 0 };
|
||||
if self.asking_width == 0 {
|
||||
// The ending width becomes PLINEWID, the next polyline's width (AutoCAD:
|
||||
// Halfwidth 0.5 0.5 leaves PLINEWID 1).
|
||||
s.doc_mut()?.header.set_f64("PLINEWID", self.end_w);
|
||||
}
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if let (Some(a), Some(st)) = (self.ask, self.verts.last().map(|v| v.p)) {
|
||||
@@ -393,10 +379,6 @@ impl Interactive for PlineM {
|
||||
l.bulge = 0.0;
|
||||
(l.start_width, l.end_width) = (0.0, 0.0);
|
||||
}
|
||||
// Back to the mode of the segment now last (AutoCAD: `_A` point `_U` returns
|
||||
// to "Specify next point", where `_L` is Length, not arc mode's Line).
|
||||
let n = self.verts.len();
|
||||
self.arc_mode = n >= 2 && self.verts.get(n - 2).is_some_and(|v| v.bulge != 0.0);
|
||||
self.sync(s, false)?;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
@@ -125,11 +125,7 @@ impl Interactive for SplineM {
|
||||
}
|
||||
match i {
|
||||
Input::Point(p) => {
|
||||
// The same point again is not a further fit point (AutoCAD 2024 leaves it out),
|
||||
// nor a kink.
|
||||
if self.pts.last() != Some(&p) {
|
||||
self.pts.push(p);
|
||||
}
|
||||
self.pts.push(p);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Input::Keyword(k) if k == "Undo" => {
|
||||
@@ -179,8 +175,6 @@ impl Interactive for SplineM {
|
||||
}
|
||||
Some(crate::cmd::spline_opts::SplineAsk::EndTangent) => opts.end_tangent = self.pts.last().map(|l| c - *l).filter(|d| d.len() > 1e-12),
|
||||
Some(_) => {}
|
||||
// The cursor on the last point adds nothing, as a click there doesn't.
|
||||
None if pts.last() == Some(&c) => {}
|
||||
None => pts.push(c),
|
||||
}
|
||||
if pts.len() < 2 {
|
||||
|
||||
@@ -7,7 +7,7 @@ use cadcraft_geom::{Arc, Circle, Ellipse, Line, PolyVertex, Polyline, Spline, TA
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::curves::{self, Chain, MAX_GEN, TanObj};
|
||||
use super::helpers::{arc, circle, line, lwpoly, rect_corners_fit, rect_vertices, rect_with_corners, v3};
|
||||
use super::helpers::{arc, circle, line, lwpoly, rect_vertices, rect_with_corners, v3};
|
||||
|
||||
use super::machines::number;
|
||||
use super::{CommandSpec, bad, bool_or, f64_or, f64_req, point_param, point_req, point_value, points_param, size_param, str_param, targets};
|
||||
|
||||
@@ -139,15 +139,6 @@ impl DivideM {
|
||||
pub(super) fn new(measure: bool) -> Self {
|
||||
DivideM { measure, obj: None, phase: DivPhase::Object, block: None, align: true }
|
||||
}
|
||||
|
||||
/// The JSON form's parameters for the picked object, before the count or length.
|
||||
fn params(&self, h: Handle, pick: Vec2) -> Value {
|
||||
let mut params = json!({ "handle": h.hex(), "align": self.align, "from": [pick.x, pick.y] });
|
||||
if let Some(b) = &self.block {
|
||||
params["block"] = json!(b);
|
||||
}
|
||||
params
|
||||
}
|
||||
}
|
||||
|
||||
impl Interactive for DivideM {
|
||||
@@ -196,37 +187,27 @@ impl Interactive for DivideM {
|
||||
self.phase = DivPhase::Value;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(DivPhase::Value, inp @ (Input::Text(_) | Input::Point(_))) if self.measure => {
|
||||
(DivPhase::Value, inp @ (Input::Text(_) | Input::Point(_))) => {
|
||||
let Some((h, pick)) = self.obj else { return Ok(Step::Cancel) };
|
||||
let v = match inp {
|
||||
Input::Text(t) => number(&t).ok_or_else(|| other("Requires a number."))?,
|
||||
Input::Point(q) => pick.dist(q),
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
let mut params = self.params(h, pick);
|
||||
params["length"] = json!(v);
|
||||
run_measure(s, ¶ms)?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(DivPhase::Value, inp) if !self.measure => {
|
||||
// A whole number as typed: AutoCAD 2024 takes +5 and 05 here and refuses 5.0, 5.,
|
||||
// 1e1, 4.5, 1, 32768, x, Enter and a point, naming the Block keyword while the
|
||||
// prompt still offers it (measured).
|
||||
let n = match inp {
|
||||
Input::Text(t) => t.trim().parse::<u64>().ok().filter(|n| (2..=32767).contains(n)),
|
||||
_ => None,
|
||||
let mut params = json!({ "handle": h.hex(), "align": self.align, "from": [pick.x, pick.y] });
|
||||
if let Some(b) = &self.block {
|
||||
params["block"] = json!(b);
|
||||
}
|
||||
if self.measure {
|
||||
params["length"] = json!(v);
|
||||
run_measure(s, ¶ms)?;
|
||||
} else {
|
||||
if !(2.0..=32767.0).contains(&v) || v.fract() != 0.0 {
|
||||
return Err(other("Requires an integer between 2 and 32767."));
|
||||
}
|
||||
params["segments"] = json!(v as u64);
|
||||
run_divide(s, ¶ms)?;
|
||||
}
|
||||
.ok_or_else(|| {
|
||||
other(if self.block.is_some() {
|
||||
"Requires an integer between 2 and 32767."
|
||||
} else {
|
||||
"Requires an integer between 2 and 32767, or option keyword."
|
||||
})
|
||||
})?;
|
||||
let Some((h, pick)) = self.obj else { return Ok(Step::Cancel) };
|
||||
let mut params = self.params(h, pick);
|
||||
params["segments"] = json!(n);
|
||||
run_divide(s, ¶ms)?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(_, Input::Enter) => Ok(Step::Cancel),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
Accept, EntityKind, Input, Interactive, PolyVertex, Prompt, Result, Session, Step, Value, Vec2, added, bad, bool_or, curves, f64_or, lwpoly,
|
||||
number, other, point_param, point_req, rect_corners_fit, rect_with_corners, size_param,
|
||||
number, other, point_param, point_req, rect_with_corners, size_param,
|
||||
};
|
||||
use crate::last_used::RectangModes;
|
||||
|
||||
@@ -19,30 +19,9 @@ fn rect_kind(first: Vec2, (w, h): (f64, f64), rot: f64, fillet: f64, chamfer: (f
|
||||
k
|
||||
}
|
||||
|
||||
/// The area a fillet's or chamfer's four corners take off the full rectangle (a fillet wins).
|
||||
fn corner_area(fillet: f64, chamfer: (f64, f64)) -> f64 {
|
||||
if fillet > 0.0 {
|
||||
(4.0 - std::f64::consts::PI) * fillet * fillet
|
||||
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 {
|
||||
2.0 * chamfer.0 * chamfer.1
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// The sides of the rectangle of `area` with one side `side`, its length (or with `breadth`,
|
||||
/// its width). AutoCAD sizes it so that the outline, corners cut, encloses the area: the corners'
|
||||
/// area is added back. When the corners then don't fit they stay square, and the area is the full
|
||||
/// rectangle's.
|
||||
fn area_sides(area: f64, side: f64, breadth: bool, fillet: f64, chamfer: (f64, f64)) -> (f64, f64) {
|
||||
let sides = |a: f64| if breadth { (a / side, side) } else { (side, a / side) };
|
||||
let (w, h) = sides(area + corner_area(fillet, chamfer));
|
||||
if rect_corners_fit(Vec2::new(w, h), fillet, chamfer) { (w, h) } else { sides(area) }
|
||||
}
|
||||
|
||||
/// The width and height of a rectangle from its `dimensions`, its `p2` corner, its `area` with
|
||||
/// `length` or `breadth`, or its second corner `p2`, rotated by `rot` about `a`.
|
||||
fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool, fillet: f64, chamfer: (f64, f64)) -> Result<(f64, f64)> {
|
||||
fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool) -> Result<(f64, f64)> {
|
||||
Ok(if let Some(d) = p.get("dimensions").and_then(Value::as_array) {
|
||||
let l = d.first().and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("rectang", "dimensions: [length, width]"))?;
|
||||
let wd = d.get(1).and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("rectang", "dimensions: [length, width]"))?;
|
||||
@@ -59,8 +38,8 @@ fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool, fillet: f64, chamfer:
|
||||
return Err(bad("rectang", "area must be positive"));
|
||||
}
|
||||
match (p.get("length").and_then(Value::as_f64), p.get("breadth").and_then(Value::as_f64)) {
|
||||
(Some(l), _) if l.is_finite() && l > 0.0 => area_sides(area, l, false, fillet, chamfer),
|
||||
(_, Some(b)) if b.is_finite() && b > 0.0 => area_sides(area, b, true, fillet, chamfer),
|
||||
(Some(l), _) if l.is_finite() && l > 0.0 => (l, area / l),
|
||||
(_, Some(b)) if b.is_finite() && b > 0.0 => (area / b, b),
|
||||
_ => return Err(bad("rectang", "area needs `length` or `breadth`")),
|
||||
}
|
||||
} else {
|
||||
@@ -89,7 +68,7 @@ pub(crate) fn run_rectang2(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let fillet = size_param("rectang", p, "fillet", true)?.unwrap_or(0.0);
|
||||
let width = size_param("rectang", p, "width", true)?.unwrap_or(0.0);
|
||||
let (w, h) = rect_size(p, a, rot, centered, fillet, ch)?;
|
||||
let (w, h) = rect_size(p, a, rot, centered)?;
|
||||
if w.abs() < 1e-12 || h.abs() < 1e-12 || !w.is_finite() || !h.is_finite() {
|
||||
return Err(bad("rectang", "rectangle has no area"));
|
||||
}
|
||||
@@ -137,13 +116,10 @@ pub(crate) struct RectM2 {
|
||||
asking: Option<RAsk>,
|
||||
}
|
||||
|
||||
/// A rectangle's rotation (radians counterclockwise from +X) as AutoCAD 2024 shows it: from
|
||||
/// ANGBASE in the ANGDIR sense, in the drawing's angle units, to two places. Rotation 30 typed
|
||||
/// with ANGBASE 90 and ANGDIR 1 shows as "120.00", and 30.5 in degrees/minutes/seconds as
|
||||
/// "30d30'".
|
||||
fn rotation_text(s: &Session, rotation: f64) -> String {
|
||||
let au = s.angle_settings();
|
||||
crate::units::format_angle(au.shown(rotation), au.aunits, 2)
|
||||
/// A rectangle's rotation as AutoCAD 2024 shows it: degrees from 0 to 360, two decimals.
|
||||
fn rotation_text(rotation: f64) -> String {
|
||||
let t = format!("{:.2}", rotation.to_degrees().rem_euclid(360.0));
|
||||
if t == "360.00" { "0.00".into() } else { t }
|
||||
}
|
||||
|
||||
/// AutoCAD 2024's line listing the RECTANG modes that are set, `None` when none is ("Current
|
||||
@@ -168,10 +144,9 @@ fn modes_line(s: &Session, m: &RectangModes) -> Option<String> {
|
||||
if m.width > 0.0 {
|
||||
parts.push(format!("Width={}", d(m.width)));
|
||||
}
|
||||
// Listed when the rectangle is turned from +X at all, to two places, whatever ANGBASE says.
|
||||
let turned = format!("{:.2}", m.rotation.to_degrees().rem_euclid(360.0));
|
||||
if turned != "0.00" && turned != "360.00" {
|
||||
parts.push(format!("Rotation={}", rotation_text(s, m.rotation)));
|
||||
let rot = rotation_text(m.rotation);
|
||||
if rot != "0.00" {
|
||||
parts.push(format!("Rotation={rot}"));
|
||||
}
|
||||
(!parts.is_empty()).then(|| format!("Current rectangle modes: {}", parts.join(" ")))
|
||||
}
|
||||
@@ -244,7 +219,7 @@ impl Interactive for RectM2 {
|
||||
}
|
||||
/// Asks for the pending option's value, or for the first and second points; in centre mode
|
||||
/// the first prompt asks for the centre instead of a corner.
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
let num = |m: &str, d: f64| Prompt::new(m, Accept::NUMBER).default(format!("{d:.4}"));
|
||||
if let Some(a) = self.asking {
|
||||
return match a {
|
||||
@@ -262,7 +237,7 @@ impl Interactive for RectM2 {
|
||||
RAsk::DimW => num("Specify width for rectangles", self.dims.map(|d| d.1).unwrap_or(10.0)),
|
||||
RAsk::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER)
|
||||
.kw(&["Pick points"])
|
||||
.default(rotation_text(s, self.rotation))
|
||||
.default(rotation_text(self.rotation))
|
||||
.base_opt(self.first),
|
||||
RAsk::RotPick1 => Prompt::new("Specify first point", Accept::POINT),
|
||||
RAsk::RotPick2(b) => Prompt::new("Specify second point", Accept::POINT).base(b),
|
||||
@@ -324,7 +299,7 @@ impl Interactive for RectM2 {
|
||||
self.asking = Some(a);
|
||||
return Err(other("Value must be positive."));
|
||||
}
|
||||
let (w, h) = area_sides(self.area, v, a == RAsk::AreaWidth, self.fillet, self.chamfer);
|
||||
let (w, h) = if a == RAsk::AreaLength { (v, self.area / v) } else { (self.area / v, v) };
|
||||
return self.make(s, w, h);
|
||||
}
|
||||
RAsk::DimL => {
|
||||
@@ -339,8 +314,7 @@ impl Interactive for RectM2 {
|
||||
RAsk::Rotation => match i {
|
||||
Input::Keyword(_) => self.asking = Some(RAsk::RotPick1),
|
||||
Input::Point(p) => self.rotation = self.first.map(|f| f.angle_to(p)).unwrap_or(0.0),
|
||||
// An amount turned in the ANGDIR sense from +X, ANGBASE aside, as AutoCAD takes it.
|
||||
Input::Text(t) => self.rotation = s.angle_settings().rotation(&t).ok_or_else(|| other("Requires a valid angle."))?,
|
||||
Input::Text(t) => self.rotation = s.angle_settings().direction(&t).ok_or_else(|| other("Requires a valid angle."))?,
|
||||
_ => {}
|
||||
},
|
||||
RAsk::RotPick1 => {
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
|
||||
|
||||
@@ -729,57 +729,6 @@ fn divide_and_measure_command_line() {
|
||||
s.cancel();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn divide_takes_a_whole_number_as_typed() {
|
||||
// AutoCAD 2024 at "Enter the number of segments or [Block]:": +5, 05, the LISP real 5.0 and
|
||||
// 32767 are taken; 5.0, 5., 1e1, 4.5, 1, 0, -3, 32768, x, Enter and a point from LISP are
|
||||
// refused and asked again (measured).
|
||||
let points = |s: &Session| kinds(s).iter().filter(|k| **k == "Point").count();
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
s.cmdline("divide 5,0").unwrap();
|
||||
let asked = s.prompt_text();
|
||||
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter the number of segments or [Block]:"));
|
||||
for bad in ["5.0", "5.", "1e1", "4.5", "1", "0", "-3", "32768", "x", "", "(list 1 2)"] {
|
||||
let logged = s.log.len();
|
||||
s.cmdline(bad).unwrap();
|
||||
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
|
||||
assert_eq!(said, ["Requires an integer between 2 and 32767, or option keyword."], "{bad:?}");
|
||||
assert_eq!(s.prompt_text(), asked, "{bad:?}");
|
||||
}
|
||||
assert_eq!(points(&s), 0);
|
||||
s.cmdline("+5").unwrap();
|
||||
assert!(s.running.is_none());
|
||||
assert_eq!(points(&s), 4);
|
||||
for (typed, n) in [("05", 4), ("(+ 2.5 2.5)", 4), ("2", 1), ("32767", 32766)] {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
s.cmdline("divide 5,0").unwrap();
|
||||
s.cmdline(typed).unwrap();
|
||||
assert!(s.running.is_none(), "{typed}: {}", s.prompt_text());
|
||||
assert_eq!(points(&s), n, "{typed}");
|
||||
}
|
||||
// MEASURE shares the prompt machine and is unchanged: Enter at its length still ends it.
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
s.cmdline("measure 5,0").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(points(&s), 0);
|
||||
// After Block the prompt offers no keyword, and the message names none (AutoCAD 2024, measured).
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
let tick = s.execute("circle", &json!({"center": [50, 50], "radius": 0.1})).unwrap();
|
||||
s.execute("block", &json!({"name": "DOT", "base": [50, 50], "handles": [h(&tick)], "keep": "delete"})).unwrap();
|
||||
s.cmdline("divide 5,0 b DOT y").unwrap();
|
||||
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter the number of segments:"));
|
||||
s.cmdline("5.0").unwrap();
|
||||
assert_eq!(s.log.last().map(String::as_str), Some("Requires an integer between 2 and 32767."));
|
||||
s.cmdline("5").unwrap();
|
||||
assert!(s.running.is_none());
|
||||
assert_eq!(kinds(&s).iter().filter(|k| **k == "Block Reference").count(), 4);
|
||||
}
|
||||
|
||||
// ---------------- REVCLOUD ----------------
|
||||
|
||||
#[test]
|
||||
@@ -1152,198 +1101,6 @@ fn rectang_options_command_line() {
|
||||
}
|
||||
}
|
||||
|
||||
/// RECTANG against what AutoCAD 2024 stores for the same typed input (black-box: synthetic
|
||||
/// input in accoreconsole, read back with `entget`): Area with the corners taken off, and
|
||||
/// corners too large for the sides.
|
||||
#[test]
|
||||
fn rectang_area_and_oversized_corners_match_autocad() {
|
||||
type Case = (&'static [&'static str], &'static [[f64; 3]], [f64; 3]);
|
||||
// (typed input, vertices [x, y, bulge], [width, elevation, thickness])
|
||||
let cases: [Case; 4] = [
|
||||
// RECTANG-028: Area counts the chamfered corners off.
|
||||
(
|
||||
&["rectang _C 1.5 2.5 26.36462345136234,-19.7291241693893 _R 0 _A 1442.9297064464572 _W 35.53488991311575"],
|
||||
&[
|
||||
[26.36462345136234, -18.2291241693893, 0.0],
|
||||
[28.86462345136234, -19.7291241693893, 0.0],
|
||||
[65.68168268505678, -19.7291241693893, 0.0],
|
||||
[67.18168268505678, -17.2291241693893, 0.0],
|
||||
[67.18168268505678, 14.30576574372644, 0.0],
|
||||
[64.68168268505678, 15.80576574372644, 0.0],
|
||||
[27.86462345136234, 15.80576574372644, 0.0],
|
||||
[26.36462345136234, 13.30576574372644, 0.0],
|
||||
],
|
||||
[0.0, 0.0, 0.0],
|
||||
),
|
||||
// RECTANG-035-VN: Area counts the fillets off, at survey coordinates.
|
||||
(
|
||||
&["rectang _F 2.0 612322.0691653182,2398792.948957577 _R 0 _A 592.8936847254046 _L 19.287858563349488"],
|
||||
&[
|
||||
[612322.0691653182, 2398794.948957577, 0.414213562373095],
|
||||
[612324.0691653182, 2398792.948957577, 0.0],
|
||||
[612339.3570238815, 2398792.948957577, 0.414213562373095],
|
||||
[612341.3570238815, 2398794.948957577, 0.0],
|
||||
[612341.3570238815, 2398821.866195597, 0.414213562373095],
|
||||
[612339.3570238815, 2398823.866195598, 0.0],
|
||||
[612324.0691653182, 2398823.866195598, 0.414213562373095],
|
||||
[612322.0691653182, 2398821.866195597, 0.0],
|
||||
],
|
||||
[0.0, 0.0, 0.0],
|
||||
),
|
||||
// RECTANG-029: a fillet too large: each corner two coincident vertices.
|
||||
(
|
||||
&["rectang _F 11.37084114989061 -21.46774953784037,-0.023473793210982308 _R 0 -2.5163476213560187,49.88119923361903"],
|
||||
&[
|
||||
[-21.46774953784036, -0.0234737932109823, 0.0],
|
||||
[-21.46774953784036, -0.0234737932109823, 0.0],
|
||||
[-2.516347621356018, -0.0234737932109823, 0.0],
|
||||
[-2.516347621356018, -0.0234737932109823, 0.0],
|
||||
[-2.516347621356018, 49.88119923361903, 0.0],
|
||||
[-2.516347621356018, 49.88119923361903, 0.0],
|
||||
[-21.46774953784036, 49.88119923361903, 0.0],
|
||||
[-21.46774953784036, 49.88119923361903, 0.0],
|
||||
],
|
||||
[0.0, 0.0, 0.0],
|
||||
),
|
||||
// RECTANG-039-VN: a chamfer too large, rotated, with Dimensions.
|
||||
(
|
||||
&[
|
||||
"rectang _C 18.656567079201356 18.656567079201356 612317.9599920243,2398739.0200147885 _R 30 _D 26.652238684573366 32.64533161964191 612344.6122307089,2398771.6653464083",
|
||||
],
|
||||
&[
|
||||
[612317.9599920243, 2398739.020014788, 0.0],
|
||||
[612317.9599920243, 2398739.020014788, 0.0],
|
||||
[612341.041507793, 2398752.34613413, 0.0],
|
||||
[612341.041507793, 2398752.34613413, 0.0],
|
||||
[612324.7188419831, 2398780.617820628, 0.0],
|
||||
[612324.7188419831, 2398780.617820628, 0.0],
|
||||
[612301.6373262145, 2398767.291701286, 0.0],
|
||||
[612301.6373262145, 2398767.291701286, 0.0],
|
||||
],
|
||||
[0.0, 0.0, 0.0],
|
||||
),
|
||||
];
|
||||
let same = |a: f64, b: f64| (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0);
|
||||
for (input, want, [width, elevation, thickness]) in cases {
|
||||
let mut s = Session::new();
|
||||
for line in input {
|
||||
s.cmdline(line).unwrap();
|
||||
assert!(s.running.is_none(), "{line}: {}", s.prompt_text());
|
||||
}
|
||||
let e = s.doc().unwrap().model.last().unwrap().clone();
|
||||
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{input:?}: {:?}", e.kind) };
|
||||
let got: Vec<[f64; 3]> = p.vertices.iter().map(|v| [v.p.x, v.p.y, v.bulge]).collect();
|
||||
let ok = got.len() == want.len() && got.iter().zip(want).all(|(g, w)| g.iter().zip(w).all(|(a, b)| same(*a, *b)));
|
||||
assert!(
|
||||
ok,
|
||||
"{input:?}
|
||||
got {got:?}
|
||||
want {want:?}"
|
||||
);
|
||||
assert!(p.closed && same(p.const_width, width) && same(p.elevation, elevation) && same(e.common.thickness, thickness), "{input:?}");
|
||||
}
|
||||
// Rotation, elevation and thickness are remembered too: AutoCAD opens the next RECTANG with
|
||||
// "Current rectangle modes: Elevation=7.5000 Thickness=2.2500 Rotation=30.96".
|
||||
let mut s = Session::new();
|
||||
s.cmdline("rectang _E 7.5 _T 2.25 0,0 _R _P 0,0 10,6 10,20").unwrap();
|
||||
s.cmdline("rectang 100,100 110,105").unwrap();
|
||||
let e = s.doc().unwrap().model.last().unwrap().clone();
|
||||
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{:?}", e.kind) };
|
||||
let edge = p.vertices[1].p - p.vertices[0].p;
|
||||
assert!(p.vertices[0].p == Vec2::new(100.0, 100.0) && same(edge.angle(), 6f64.atan2(10.0)), "{p:?}");
|
||||
assert!(p.elevation == 7.5 && e.common.thickness == 2.25);
|
||||
}
|
||||
|
||||
/// RECTANG's Rotation follows the drawing's angle settings as AutoCAD 2024's does.
|
||||
#[test]
|
||||
fn rectang_rotation_follows_the_angle_settings() {
|
||||
let modes = |s: &Session| s.log.iter().filter(|l| l.starts_with("Current rectangle modes:")).cloned().collect::<Vec<_>>();
|
||||
// With ANGBASE 90 and ANGDIR 1, AutoCAD 2024 turns a rectangle given Rotation 30 clockwise
|
||||
// by 30° from +X (ANGBASE aside), and shows that rotation from ANGBASE: "Rotation=120.00",
|
||||
// and <120.00> as the next rotation default.
|
||||
let mut s = Session::new();
|
||||
s.cmdline("setvar angbase 90").unwrap();
|
||||
s.cmdline("setvar angdir 1").unwrap();
|
||||
s.cmdline("rectang 50,0 _R 30 60,5").unwrap();
|
||||
let e = s.doc().unwrap().model.last().unwrap().clone();
|
||||
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{:?}", e.kind) };
|
||||
let edge = p.vertices[1].p - p.vertices[0].p;
|
||||
assert!((edge.y.atan2(edge.x) + 30f64.to_radians()).abs() < 1e-9, "{p:?}");
|
||||
s.start("rectang").unwrap();
|
||||
assert_eq!(modes(&s), ["Current rectangle modes: Rotation=120.00"]);
|
||||
s.cmdline("50,0").unwrap();
|
||||
s.cmdline("_R").unwrap();
|
||||
assert!(s.prompt_text().contains("<120.00>"), "{}", s.prompt_text());
|
||||
s.cancel();
|
||||
// In degrees/minutes/seconds: "Rotation=30d30'".
|
||||
let mut s = Session::new();
|
||||
s.cmdline("setvar aunits 1").unwrap();
|
||||
s.cmdline("rectang 50,0 _R 30.5 60,5").unwrap();
|
||||
s.start("rectang").unwrap();
|
||||
assert_eq!(modes(&s), ["Current rectangle modes: Rotation=30d30'"]);
|
||||
s.cancel();
|
||||
}
|
||||
|
||||
/// Area allows for cut corners only while they fit: a fillet too large for the resulting sides
|
||||
/// leaves square corners, so the rectangle is the full area asked for (4 × 1, not 4 × 1.858).
|
||||
/// Corners exactly as long as the shorter side allows still fit; a hair longer and the corners
|
||||
/// stay square, each still written twice (AutoCAD 2024, `entget` of a 4 x 2 rectangle).
|
||||
#[test]
|
||||
fn rectang_corners_at_the_limit_fit_and_just_over_stay_square() {
|
||||
let b = (std::f64::consts::PI / 8.0).tan();
|
||||
let fit: [(&str, &[(f64, f64, f64)]); 4] = [
|
||||
(
|
||||
"_F 0.9999",
|
||||
&[
|
||||
(0.0, 0.9999, b),
|
||||
(0.9999, 0.0, 0.0),
|
||||
(3.0001, 0.0, b),
|
||||
(4.0, 0.9999, 0.0),
|
||||
(4.0, 1.0001, b),
|
||||
(3.0001, 2.0, 0.0),
|
||||
(0.9999, 2.0, b),
|
||||
(0.0, 1.0001, 0.0),
|
||||
],
|
||||
),
|
||||
("_F 1", &[(0.0, 1.0, b), (1.0, 0.0, 0.0), (3.0, 0.0, b), (4.0, 1.0, 0.0), (4.0, 1.0, b), (3.0, 2.0, 0.0), (1.0, 2.0, b), (0.0, 1.0, 0.0)]),
|
||||
(
|
||||
"_C 1 1",
|
||||
&[(0.0, 1.0, 0.0), (1.0, 0.0, 0.0), (3.0, 0.0, 0.0), (4.0, 1.0, 0.0), (4.0, 1.0, 0.0), (3.0, 2.0, 0.0), (1.0, 2.0, 0.0), (0.0, 1.0, 0.0)],
|
||||
),
|
||||
(
|
||||
"_C 1.2 0.8",
|
||||
&[(0.0, 1.2, 0.0), (0.8, 0.0, 0.0), (2.8, 0.0, 0.0), (4.0, 0.8, 0.0), (4.0, 0.8, 0.0), (3.2, 2.0, 0.0), (1.2, 2.0, 0.0), (0.0, 1.2, 0.0)],
|
||||
),
|
||||
];
|
||||
let square =
|
||||
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 2.0, 0.0), (4.0, 2.0, 0.0), (0.0, 2.0, 0.0), (0.0, 2.0, 0.0)];
|
||||
let over: [(&str, &[(f64, f64, f64)]); 2] = [("_F 1.0001", &square), ("_C 1.2 0.81", &square)];
|
||||
for (corners, want) in fit.into_iter().chain(over) {
|
||||
let mut s = Session::new();
|
||||
s.cmdline(&format!("rectang {corners} 0,0 4,2")).unwrap();
|
||||
let EntityKind::LwPolyline(p) = last(&s) else { panic!("no polyline") };
|
||||
let got: Vec<(f64, f64, f64)> = p.vertices.iter().map(|v| (v.p.x, v.p.y, v.bulge)).collect();
|
||||
let ok = got.len() == want.len()
|
||||
&& got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-9 && (g.1 - w.1).abs() < 1e-9 && (g.2 - w.2).abs() < 1e-6);
|
||||
assert!(ok, "{corners}: {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rectang_area_with_corners_too_large_stays_exact() {
|
||||
let check = |s: &Session| {
|
||||
let pts = rect_pts(s);
|
||||
let b = cadcraft_geom::Bounds2::from_points(pts.clone());
|
||||
assert!(near(b.min, 0.0, 0.0) && near(b.max, 4.0, 1.0), "{pts:?}");
|
||||
assert!(pts.len() == 8 && pts.chunks(2).all(|c| c[0] == c[1]), "{pts:?}");
|
||||
};
|
||||
let mut s = Session::new();
|
||||
s.cmdline("rectang _F 2 0,0 _A 4 _L 4").unwrap();
|
||||
check(&s);
|
||||
s.execute("rectang", &json!({"p1": [0, 0], "area": 4, "length": 4, "fillet": 2})).unwrap();
|
||||
check(&s);
|
||||
}
|
||||
|
||||
/// Guards the JSON `center: true` form for every sizing route: a picked corner mirrored about
|
||||
/// the centre, full-size `dimensions`, full `area`, rotation about the centre, that the default
|
||||
/// corner mode is untouched, and that centre mode without a size is rejected.
|
||||
@@ -1379,7 +1136,7 @@ fn rectang_center_mode_json() {
|
||||
}
|
||||
|
||||
/// Guards that fillet, chamfer, width and thickness still apply in centre mode, and that an
|
||||
/// oversized fillet leaves sharp corners without moving the rectangle off centre.
|
||||
/// oversized fillet falls back to sharp corners without moving the rectangle off centre.
|
||||
#[test]
|
||||
fn rectang_center_mode_honours_options() {
|
||||
let mut s = Session::new();
|
||||
@@ -1396,11 +1153,9 @@ fn rectang_center_mode_honours_options() {
|
||||
assert_eq!(rect_pts(&s).len(), 8);
|
||||
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
|
||||
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
|
||||
// A fillet too large for the rectangle leaves sharp corners, each one two coincident vertices
|
||||
// as in AutoCAD, still centred.
|
||||
// A fillet too large for the rectangle falls back to sharp corners, still centred.
|
||||
s.execute("rectang", &json!({"center": true, "p1": [10, 10], "p2": [14, 16], "fillet": 5})).unwrap();
|
||||
let pts = rect_pts(&s);
|
||||
assert!(pts.len() == 8 && pts.chunks(2).all(|c| c[0] == c[1]), "{pts:?}");
|
||||
assert_eq!(rect_pts(&s).len(), 4);
|
||||
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
|
||||
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
|
||||
}
|
||||
@@ -1428,9 +1183,8 @@ fn rectang_center_mode_command_line() {
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
|
||||
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
|
||||
// Area too: the rectangle of that area is centred on the first point (without the fillet
|
||||
// remembered from above, which would take its corners off the area).
|
||||
s.cmdline("rectang f 0 ce 10,10 a 96 l 8").unwrap();
|
||||
// Area too: the rectangle of that area is centred on the first point.
|
||||
s.cmdline("rectang ce 10,10 a 96 l 8").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
|
||||
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
|
||||
|
||||
@@ -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.") }))
|
||||
}
|
||||
|
||||
|
||||
@@ -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)} → {format, bytes, 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"])
|
||||
@@ -123,7 +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}");
|
||||
let (bytes, notes) = 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) => {
|
||||
@@ -134,7 +134,6 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
super::file::report_new_folder(s, &mut r, folder);
|
||||
super::file::report_loss(s, &mut r, &file);
|
||||
super::file::report_notes(s, &mut r, notes);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
|
||||
+16
-126
@@ -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 {
|
||||
@@ -145,46 +104,6 @@ pub fn set_dwg_compat_lost(f: DwgCompatLost) {
|
||||
let _ = DWG_COMPAT_LOST.set(f);
|
||||
}
|
||||
|
||||
/// Notes on what a DWG keeps of a drawing only in part, such as a linetype with more dash
|
||||
/// elements than a DWG can count (installed by the app with the DWG writer, a lower layer; see
|
||||
/// `cadcraft_io::dwg_notes`).
|
||||
pub type DwgNotes = fn(&Drawing) -> Vec<String>;
|
||||
|
||||
static DWG_NOTES: OnceLock<DwgNotes> = OnceLock::new();
|
||||
|
||||
pub fn set_dwg_notes(f: DwgNotes) {
|
||||
let _ = DWG_NOTES.set(f);
|
||||
}
|
||||
|
||||
/// The [`DwgNotes`] of `d`, the drawing a DWG save writes: none without the hook.
|
||||
pub fn dwg_notes(d: &Drawing) -> Vec<String> {
|
||||
DWG_NOTES.get().map(|f| f(d)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 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;
|
||||
}
|
||||
for note in ¬es {
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a DXF of `version` leaves out of `d` for its proxies' string streams (#3229): empty from
|
||||
/// 2007 on. `d` is written as committed (a reference edit's working copies are not in the file).
|
||||
fn proxies_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
@@ -289,10 +208,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"));
|
||||
@@ -301,12 +219,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))
|
||||
}
|
||||
@@ -338,7 +255,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.noundo(),
|
||||
CommandSpec::new("document.switch", "Switch Drawing", run_switch).params("{index}").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..."])
|
||||
@@ -582,19 +499,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."));
|
||||
}
|
||||
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()?;
|
||||
@@ -606,7 +522,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
|
||||
@@ -896,18 +812,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);
|
||||
@@ -956,13 +869,10 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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();
|
||||
report_dwg_notes(s, &mut r, notes);
|
||||
} else if is_dxf_file(format!("drawing.{fmt}")) {
|
||||
let lost = host_dxf_lost(s, version);
|
||||
report_lost(s, &mut r, "drawing.dxf", version, &lost);
|
||||
@@ -1095,9 +1005,7 @@ pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
|
||||
let Ok(d) = s.doc() else { return };
|
||||
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);
|
||||
report_dwg_notes(s, r, notes);
|
||||
}
|
||||
|
||||
/// Say on the command line what the file `path`, written at `version`, couldn't keep (`lost`),
|
||||
@@ -1204,8 +1112,6 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R
|
||||
report_new_folder(s, &mut r, folder);
|
||||
if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) {
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
let notes = s.state().map(|st| dwg_notes(st.drawing())).unwrap_or_default();
|
||||
report_dwg_notes(s, &mut r, notes);
|
||||
} else if r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) {
|
||||
let lost = host_dxf_lost(s, version);
|
||||
report_lost(s, &mut r, "drawing.dxf", version, &lost);
|
||||
@@ -1273,22 +1179,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)]
|
||||
|
||||
@@ -455,9 +455,15 @@ fn tinted_dim_style(d: &mut Drawing, name: &str, color: Color, tinted: &mut Tint
|
||||
if let Some(n) = tinted.names.get(&key) {
|
||||
return Some(n.clone());
|
||||
}
|
||||
let st = d.dim_style(name)?.clone();
|
||||
let st = d.dim_styles.iter().find(|s| s.name.eq_ignore_ascii_case(name))?.clone();
|
||||
let base = format!("COMPARE_{}_{}", tag(color), st.name);
|
||||
let new = tinted.next.find("dimension style", &base, d.dim_styles.len(), |i| suffixed(&base, i), |n| d.dim_style(n).is_some());
|
||||
let new = tinted.next.find(
|
||||
"dimension style",
|
||||
&base,
|
||||
d.dim_styles.len(),
|
||||
|i| suffixed(&base, i),
|
||||
|n| d.dim_styles.iter().any(|s| s.name.eq_ignore_ascii_case(n)),
|
||||
);
|
||||
d.dim_styles.push(DimStyle {
|
||||
name: new.clone(),
|
||||
dim_line_color: Color::ByBlock,
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -17,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;
|
||||
@@ -55,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;
|
||||
@@ -76,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
|
||||
@@ -197,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;
|
||||
}
|
||||
@@ -212,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() {
|
||||
@@ -247,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() {
|
||||
@@ -286,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,
|
||||
@@ -299,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] });
|
||||
}
|
||||
@@ -456,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);
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
@@ -420,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"));
|
||||
|
||||
@@ -68,48 +68,29 @@ pub fn polygon_from_edge(p1: Vec2, p2: Vec2, sides: usize) -> Vec<PolyVertex> {
|
||||
/// chamfer distances at every corner, in AutoCAD 2024's order: from `a` along X to `b`'s X, then
|
||||
/// `b`, then back along Y. A chamfer cuts the edge into each corner by its first distance and the
|
||||
/// edge out of it by its second; each fillet arc starts on the edge into its corner. A fillet or
|
||||
/// chamfer too large for the shorter side leaves the corners square, each as two coincident
|
||||
/// vertices, as AutoCAD stores them.
|
||||
/// chamfer that doesn't fit leaves the corners square.
|
||||
pub fn rect_with_corners(a: Vec2, b: Vec2, fillet: f64, chamfer: (f64, f64)) -> Vec<PolyVertex> {
|
||||
let corners = [a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y)];
|
||||
let Some((d_in, d_out)) = rect_corner_cuts(fillet, chamfer) else { return corners.into_iter().map(PolyVertex::new).collect() };
|
||||
let fits = rect_corners_fit(b - a, fillet, chamfer);
|
||||
// Counter-clockwise round the corners (a positive bulge) when `b` is up and right of `a`, or
|
||||
// down and left.
|
||||
let sign = if (b.x - a.x) * (b.y - a.y) >= 0.0 { 1.0 } else { -1.0 };
|
||||
let bulge = if fillet > 0.0 { sign * cadcraft_geom::arc_to_bulge(std::f64::consts::FRAC_PI_2) } else { 0.0 };
|
||||
let short = (b.x - a.x).abs().min((b.y - a.y).abs());
|
||||
let (d_in, d_out, bulge) = if fillet > 0.0 && fillet * 2.0 <= short + 1e-12 {
|
||||
// Counter-clockwise round the corners (a positive bulge) when `b` is up and right of `a`, or
|
||||
// down and left.
|
||||
let sign = if (b.x - a.x) * (b.y - a.y) >= 0.0 { 1.0 } else { -1.0 };
|
||||
(fillet, fillet, sign * cadcraft_geom::arc_to_bulge(std::f64::consts::FRAC_PI_2))
|
||||
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 && chamfer.0 + chamfer.1 <= short + 1e-12 {
|
||||
(chamfer.0, chamfer.1, 0.0)
|
||||
} else {
|
||||
return corners.into_iter().map(PolyVertex::new).collect();
|
||||
};
|
||||
let mut out = Vec::with_capacity(8);
|
||||
for (i, cur) in corners.iter().enumerate() {
|
||||
let (Some(prev), Some(next)) = (corners.get((i + 3) % 4), corners.get((i + 1) % 4)) else { continue };
|
||||
if fits {
|
||||
out.push(PolyVertex::with_bulge(*cur + (*prev - *cur).normalized() * d_in, bulge));
|
||||
out.push(PolyVertex::new(*cur + (*next - *cur).normalized() * d_out));
|
||||
} else {
|
||||
out.extend([PolyVertex::new(*cur), PolyVertex::new(*cur)]);
|
||||
}
|
||||
out.push(PolyVertex::with_bulge(*cur + (*prev - *cur).normalized() * d_in, bulge));
|
||||
out.push(PolyVertex::new(*cur + (*next - *cur).normalized() * d_out));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How far a rectangle's fillet or chamfer cuts into the edges into and out of each corner, if
|
||||
/// one is set: the fillet radius on both, or the two chamfer distances. A fillet wins over a
|
||||
/// chamfer.
|
||||
fn rect_corner_cuts(fillet: f64, chamfer: (f64, f64)) -> Option<(f64, f64)> {
|
||||
if fillet > 0.0 {
|
||||
Some((fillet, fillet))
|
||||
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 {
|
||||
Some(chamfer)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a fillet or chamfer fits a rectangle of `size` (signed sides): its two cuts together
|
||||
/// no longer than the shorter side. True when neither is set.
|
||||
pub fn rect_corners_fit(size: Vec2, fillet: f64, chamfer: (f64, f64)) -> bool {
|
||||
rect_corner_cuts(fillet, chamfer).is_none_or(|(d_in, d_out)| d_in + d_out <= size.x.abs().min(size.y.abs()) + 1e-12)
|
||||
}
|
||||
|
||||
// ---------- the user's support files ----------
|
||||
|
||||
/// Largest support file (linetype, hatch pattern or alias file) read.
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -62,7 +62,8 @@ impl Scope {
|
||||
Some(_) => {
|
||||
let name = given.unwrap_or_default();
|
||||
let d = s.doc()?;
|
||||
let l = d.layout(&name).ok_or_else(|| bad(cmd, format!("no layout named \"{name}\"")))?;
|
||||
let l =
|
||||
d.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(&name)).ok_or_else(|| bad(cmd, format!("no layout named \"{name}\"")))?;
|
||||
Ok(Scope::Space(Space::Paper(l.name.clone())))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
@@ -298,7 +297,7 @@ fn run_layerp(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let d = s.doc_mut()?;
|
||||
let snap = d.header.str("CADCRAFT_LAYERP", "");
|
||||
let layers: Vec<Layer> = serde_json::from_str(&snap).map_err(|_| bad("layerp", "No previous layer state."))?;
|
||||
d.layers = layers.into();
|
||||
d.layers = layers;
|
||||
Ok(json!({"message": "Restored previous layer states."}))
|
||||
}
|
||||
|
||||
@@ -376,7 +375,7 @@ fn run_layuniso(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let d = s.doc_mut()?;
|
||||
let snap = d.header.str("CADCRAFT_LAYISO", "");
|
||||
let layers: Vec<Layer> = serde_json::from_str(&snap).map_err(|_| bad("layuniso", "No isolated layers."))?;
|
||||
d.layers = layers.into();
|
||||
d.layers = layers;
|
||||
ok()
|
||||
}
|
||||
|
||||
|
||||
@@ -26,18 +26,14 @@ 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?}"),
|
||||
CommandSpec::new("layout.list", "List Layouts", run_list).params("→ [{name, tabOrder, page, viewports}]").noundo(),
|
||||
CommandSpec::new("layout.saveas", "Save Layout as Template", saveas::run_saveas)
|
||||
.params("{name?: layout (default: the current layout, else the first tab), path: .dwt (or .dwg, .dxf; no extension adds .dwt)} → {name, path, bytes, notSaved?, warnings?}")
|
||||
.params("{name?: layout (default: the current layout, else the first tab), path: .dwt (or .dwg, .dxf; no extension adds .dwt)} → {name, path, bytes, notSaved?}")
|
||||
.noundo(),
|
||||
CommandSpec::new("mview", "Viewports", run_mview)
|
||||
.alias(&["mv"])
|
||||
@@ -229,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)?,
|
||||
@@ -366,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)?;
|
||||
@@ -581,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();
|
||||
@@ -832,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(|| {
|
||||
@@ -885,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") {
|
||||
@@ -1049,7 +890,7 @@ 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(),
|
||||
@@ -1068,22 +909,15 @@ 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);
|
||||
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);
|
||||
Ok(r)
|
||||
Ok(json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format }))
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
|
||||
super::file::report_notes(s, &mut r, notes);
|
||||
Ok(r)
|
||||
}
|
||||
None => Ok(json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format })),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ use cadcraft_doc::{Common, Drawing, Entity, EntityKind, EntityStore, Point};
|
||||
use cadcraft_geom::Vec3;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::super::file::{drops_unknown, dwg_notes, io, not_saved, not_saved_message, report_dwg_notes};
|
||||
use super::super::file::{drops_unknown, io, not_saved, not_saved_message};
|
||||
use super::super::{bad, str_param};
|
||||
use super::layout_name;
|
||||
use super::prompts::current_layout;
|
||||
@@ -136,9 +136,6 @@ pub(super) fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
o.insert("notSaved".into(), json!(lost));
|
||||
}
|
||||
}
|
||||
if drops_unknown(&path) {
|
||||
report_dwg_notes(s, &mut r, dwg_notes(&t));
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -129,406 +129,80 @@ pub(crate) fn join(s: &mut Session, hs: &[Handle]) -> Result<Option<Handle>> {
|
||||
if hs.iter().any(|h| crate::cmd::curves::is_locked(s, *h)) {
|
||||
return Err(EngineError::Other("An object is on a locked layer.".into()));
|
||||
}
|
||||
let hs = joinable_picks(s.doc()?, hs);
|
||||
let hs = &hs[..];
|
||||
if let Some(h) = join_on_source(s, hs)? {
|
||||
return Ok(Some(h));
|
||||
}
|
||||
let d = s.doc()?;
|
||||
// Each object JOIN can take, as the pieces it is made of: a line or an arc is one piece, an
|
||||
// open polyline its segments in order, each keeping its vertices, bulge and widths exactly.
|
||||
// Each also with whether it faces down: an arc or a polyline whose normal points down Z
|
||||
// (measured with 0,0,-1; a tilted one is taken the same way). A line faces up whatever its
|
||||
// normal (AutoCAD 2024 joins one with normal 0,0,-1 to a polyline facing up, and no line to a
|
||||
// polyline facing down; measured).
|
||||
let mut units: Vec<(bool, Vec<Piece>)> = Vec::new();
|
||||
let down = |e: &Entity| !matches!(e.kind, EntityKind::Line(_)) && e.common.extrusion.z < 0.0;
|
||||
let mut segs: Vec<Segment> = Vec::new();
|
||||
// Source entity of each segment in `segs`, so only entities that end up in the chain are removed.
|
||||
let mut owners: Vec<Handle> = Vec::new();
|
||||
let mut common = None;
|
||||
for h in hs {
|
||||
let Some(e) = d.entity(*h) else { continue };
|
||||
let piece =
|
||||
|ends: (Vec2, Vec2), heights: (f64, f64), bulge: f64, widths: Option<(f64, f64)>| Piece { owner: *h, ends, heights, bulge, widths };
|
||||
let unit: Vec<Piece> = match &e.kind {
|
||||
// A line of no length joins as AutoCAD 2024 joins it, a repeated vertex.
|
||||
EntityKind::Line(l) => vec![piece((l.a.xy(), l.b.xy()), (l.a.z, l.b.z), 0.0, None)],
|
||||
EntityKind::Arc(a) => {
|
||||
let arc = Arc::new(a.center.xy(), a.radius, a.start, a.end);
|
||||
vec![piece((arc.start_point(), arc.end_point()), (a.center.z, a.center.z), cadcraft_geom::arc_to_bulge(arc.sweep()), None)]
|
||||
}
|
||||
// Repeated vertices included: AutoCAD 2024 keeps them.
|
||||
EntityKind::LwPolyline(p) if !p.closed => {
|
||||
// The elevation is along the polyline's normal: down Z for a mirrored one.
|
||||
let z = if down(e) { -p.elevation } else { p.elevation };
|
||||
p.vertices
|
||||
.windows(2)
|
||||
.map(|w| {
|
||||
let widths = if p.const_width > 0.0 { (p.const_width, p.const_width) } else { (w[0].start_width, w[0].end_width) };
|
||||
piece((w[0].p, w[1].p), (z, z), w[0].bulge, Some(widths))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if !unit.is_empty() {
|
||||
units.push((down(e), unit));
|
||||
common.get_or_insert_with(|| e.common.clone());
|
||||
match &e.kind {
|
||||
EntityKind::Line(l) => segs.push(Segment::Line(Line::new(l.a.xy(), l.b.xy()))),
|
||||
EntityKind::Arc(a) => segs.push(Segment::Arc { arc: Arc::new(a.center.xy(), a.radius, a.start, a.end), ccw: true }),
|
||||
EntityKind::LwPolyline(p) if !p.closed => segs.extend(Polyline { vertices: p.vertices.clone(), closed: false }.segments()),
|
||||
_ => {}
|
||||
}
|
||||
owners.resize(segs.len(), *h);
|
||||
}
|
||||
if units.iter().map(|u| u.1.len()).sum::<usize>() < 2 {
|
||||
if segs.len() < 2 {
|
||||
return Err(EngineError::Other("Select at least two objects to join.".into()));
|
||||
}
|
||||
// An object facing the other way from a polyline source stays out (AutoCAD 2024, measured: one
|
||||
// facing up takes no arc facing down, and one facing down no arc or polyline facing up). Onto a
|
||||
// line or an arc it wasn't measured (the core console's JOIN takes only collinear lines or arcs
|
||||
// on one circle onto those), so objects facing either way still join there.
|
||||
let polyline_source = units.first().filter(|u| u.1.first().is_some_and(|p| p.widths.is_some())).map(|u| u.0);
|
||||
let units: Vec<Vec<Piece>> = units.into_iter().filter(|u| polyline_source.is_none_or(|down| u.0 == down)).map(|u| u.1).collect();
|
||||
// A new polyline takes the source's properties.
|
||||
let first = units.first().and_then(|u| u.first()).map(|p| p.owner);
|
||||
let common = first.and_then(|h| d.entity(h)).map(|e| e.common.clone());
|
||||
// Chain greedily from the first segment.
|
||||
let mut chain = vec![segs.remove(0)];
|
||||
let mut used = vec![owners.remove(0)];
|
||||
let tol = 1e-6;
|
||||
let links = chain_units(units, tol);
|
||||
// One object alone joins nothing, even a polyline whose ends meet: AutoCAD 2024 leaves it open
|
||||
// ("0 segments added to polyline").
|
||||
let closed = links.first().zip(links.last()).is_some_and(|(a, b)| meet(a.start(), b.end(), tol));
|
||||
let one_object = links.first().is_some_and(|f| links.iter().all(|l| l.owner == f.owner));
|
||||
if links.len() < 2 || one_object {
|
||||
loop {
|
||||
let start = chain.first().map(Segment::start).unwrap_or_default();
|
||||
let end = chain.last().map(Segment::end).unwrap_or_default();
|
||||
let Some(i) =
|
||||
segs.iter().position(|s| s.start().near(end, tol) || s.end().near(end, tol) || s.start().near(start, tol) || s.end().near(start, tol))
|
||||
else {
|
||||
break;
|
||||
};
|
||||
let s0 = segs.remove(i);
|
||||
used.push(owners.remove(i));
|
||||
if s0.start().near(end, tol) {
|
||||
chain.push(s0);
|
||||
} else if s0.end().near(end, tol) {
|
||||
chain.push(s0.reversed());
|
||||
} else if s0.end().near(start, tol) {
|
||||
chain.insert(0, s0);
|
||||
} else {
|
||||
chain.insert(0, s0.reversed());
|
||||
}
|
||||
}
|
||||
if chain.len() < 2 {
|
||||
return Err(EngineError::Other("Objects are not connected.".into()));
|
||||
}
|
||||
let used = |h: &Handle| links.iter().any(|l| l.owner == *h);
|
||||
// A polyline's own segments keep their widths.
|
||||
let mut vs: Vec<PolyVertex> = links
|
||||
let closed = chain.first().zip(chain.last()).is_some_and(|(a, b)| a.start().near(b.end(), tol));
|
||||
let mut vs: Vec<PolyVertex> = chain
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let (start_width, end_width) = l.widths.unwrap_or_default();
|
||||
PolyVertex { p: l.ends.0, bulge: l.bulge, start_width, end_width }
|
||||
.map(|s| PolyVertex {
|
||||
p: s.start(),
|
||||
bulge: match s {
|
||||
Segment::Line(_) => 0.0,
|
||||
Segment::Arc { arc, ccw } => cadcraft_geom::arc_to_bulge(if *ccw { arc.sweep() } else { -arc.sweep() }),
|
||||
},
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
if !closed && let Some(l) = links.last() {
|
||||
vs.push(PolyVertex::new(l.ends.1));
|
||||
if !closed && let Some(l) = chain.last() {
|
||||
vs.push(PolyVertex::new(l.end()));
|
||||
}
|
||||
// A new polyline goes in the source's space, whichever space is current.
|
||||
let space = first.and_then(|h| d.space_of(h)).unwrap_or_else(|| s.space());
|
||||
let space = s.space();
|
||||
let doc = s.doc_mut()?;
|
||||
// A polyline source takes the other pieces and keeps its handle (AutoCAD 2024: "1 segments
|
||||
// added to polyline").
|
||||
if let Some(src) = first
|
||||
&& let Some(EntityKind::LwPolyline(sp)) = doc.entity(src).map(|e| &e.kind)
|
||||
&& let Some(onto) = onto_polyline(sp, src, &links, closed)
|
||||
{
|
||||
for h in hs.iter().filter(|h| **h != src && used(h)) {
|
||||
doc.remove_entity(*h);
|
||||
}
|
||||
doc.modify_entity(src, |e| e.kind = EntityKind::LwPolyline(onto))?;
|
||||
s.set_selection(Vec::new());
|
||||
return Ok(Some(src));
|
||||
}
|
||||
for h in hs.iter().filter(|h| used(h)) {
|
||||
for h in hs.iter().filter(|h| used.contains(*h)) {
|
||||
doc.remove_entity(*h);
|
||||
}
|
||||
// A new polyline stays at the source's height, as a polyline source keeps its elevation. The
|
||||
// elevation runs along its normal: negated for one facing down. Not measured: the core
|
||||
// console's JOIN makes no new polyline.
|
||||
let height = links.iter().find(|l| Some(l.owner) == first).map_or(0.0, |l| l.heights.0);
|
||||
let common = common.unwrap_or_default();
|
||||
let elevation = if common.extrusion.z < 0.0 { -height } else { height };
|
||||
let mut kind = lwpoly(vs, closed);
|
||||
if let EntityKind::LwPolyline(p) = &mut kind {
|
||||
p.elevation = elevation;
|
||||
}
|
||||
let nh = doc.new_handle();
|
||||
if let Some(st) = doc.space_mut(&space) {
|
||||
st.push(Entity { handle: nh, common, kind });
|
||||
st.push(Entity { handle: nh, common: common.unwrap_or_default(), kind: lwpoly(vs, closed) });
|
||||
}
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Some(nh))
|
||||
}
|
||||
|
||||
/// The picks JOIN can take, each once, in the order picked: lines, arcs and open polylines. The
|
||||
/// first of them is the source (AutoCAD 2024 passes over a circle picked first and leaves it).
|
||||
fn joinable_picks(d: &cadcraft_doc::Drawing, hs: &[Handle]) -> Vec<Handle> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let joinable = |h: &Handle| {
|
||||
d.entity(*h).is_some_and(|e| match &e.kind {
|
||||
EntityKind::Line(_) => true,
|
||||
EntityKind::Arc(a) => a.radius > cadcraft_geom::EPS,
|
||||
EntityKind::LwPolyline(p) => !p.closed,
|
||||
_ => false,
|
||||
})
|
||||
};
|
||||
hs.iter().copied().filter(|h| joinable(h) && seen.insert(*h)).collect()
|
||||
}
|
||||
|
||||
/// Whether JOIN would make the picked arcs a circle. AutoCAD 2024 asks first ("Combined arc
|
||||
/// segments form a circle. Convert to circle? [Yes/No] <Yes>:"), and No leaves every arc as it
|
||||
/// is (measured).
|
||||
pub(crate) fn join_makes_circle(s: &Session, hs: &[Handle]) -> bool {
|
||||
let Ok(d) = s.doc() else { return false };
|
||||
// Elliptical arcs and splines join another way, and a locked object stops the join.
|
||||
let other_way = |h: &Handle| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Ellipse(_) | EntityKind::Spline(_)));
|
||||
if hs.iter().any(|h| other_way(h) || crate::cmd::curves::is_locked(s, *h)) {
|
||||
return false;
|
||||
}
|
||||
let picks = joinable_picks(d, hs);
|
||||
let arcs: Vec<&cadcraft_doc::Arc> = picks
|
||||
.iter()
|
||||
.filter_map(|h| match d.entity(*h).map(|e| &e.kind) {
|
||||
Some(EntityKind::Arc(a)) => Some(a),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let tol = 1e-6;
|
||||
match &arcs[..] {
|
||||
[g, rest @ ..] if !rest.is_empty() && arcs.len() == picks.len() => arc_reach(g, rest, tol).is_some_and(|far| far > cadcraft_geom::TAU - tol),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// How far round the source arc `g`'s circle, counterclockwise from its start, it and the
|
||||
/// `others` reach; `None` when one of them isn't on that circle (less than `tol` off its centre
|
||||
/// and radius). An arc that starts even a hair before the source's start reaches on round past
|
||||
/// it: AutoCAD 2024 makes a circle of 7°-100° and an arc stored from 7° less 5e-16 rad, and
|
||||
/// leaves 7°-100° with one from exactly 7° or 5e-7 rad after it.
|
||||
fn arc_reach(g: &cadcraft_doc::Arc, others: &[&cadcraft_doc::Arc], tol: f64) -> Option<f64> {
|
||||
let same_circle =
|
||||
|o: &cadcraft_doc::Arc| o.center.xy().dist(g.center.xy()) < tol && (o.radius - g.radius).abs() < tol && (o.center.z - g.center.z).abs() < tol;
|
||||
let reach = |o: &cadcraft_doc::Arc| norm_angle(o.start - g.start) + cadcraft_geom::ccw_sweep(o.start, o.end);
|
||||
others.iter().all(|o| same_circle(o)).then(|| others.iter().map(|o| reach(o)).fold(reach(g), f64::max))
|
||||
}
|
||||
|
||||
/// The chain JOIN builds from the first object: each next object with an end on one of the
|
||||
/// chain's ends joins whole, turned round where needed, as AutoCAD 2024 joins them, until a join
|
||||
/// closes the chain; one that the chain meets only at an inner vertex of a polyline stays out.
|
||||
/// Ends are compared at the objects' own end points, not ones worked out again from arcs, and at
|
||||
/// their heights.
|
||||
fn chain_units(mut units: Vec<Vec<Piece>>, tol: f64) -> Vec<Piece> {
|
||||
let ends = |u: &[Piece]| u.first().zip(u.last()).map(|(a, b)| (a.start(), b.end()));
|
||||
let near = |p, q| meet(p, q, tol);
|
||||
if units.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
// A source that already ends where it starts still takes more, unless it has no length at all
|
||||
// (AutoCAD 2024, measured with a polyline that ends where it starts and with a line of no
|
||||
// length).
|
||||
let mut chain: std::collections::VecDeque<Piece> = units.remove(0).into();
|
||||
if chain.iter().all(|p| p.ends.0.near(p.ends.1, tol)) {
|
||||
return chain.into();
|
||||
}
|
||||
while let (Some(start), Some(end)) = (chain.front().map(Piece::start), chain.back().map(Piece::end)) {
|
||||
let meets = |u: &Vec<Piece>| ends(u).is_some_and(|(a, b)| near(a, end) || near(b, end) || near(a, start) || near(b, start));
|
||||
let Some(i) = units.iter().position(meets) else { break };
|
||||
let unit = units.remove(i);
|
||||
let Some((a, b)) = ends(&unit) else { break };
|
||||
// Where an object that meets the chain at more than one place goes, as AutoCAD 2024 puts
|
||||
// it (measured): a polyline by its first vertex if it can, and before the chain rather
|
||||
// than after it; a line or an arc turned round if it can, its end on the chain's end
|
||||
// before its start on the chain's start.
|
||||
let polyline = unit.first().is_some_and(|p| p.widths.is_some());
|
||||
let (before, turned) = if polyline {
|
||||
if near(a, start) {
|
||||
(true, true)
|
||||
} else if near(a, end) {
|
||||
(false, false)
|
||||
} else {
|
||||
(near(b, start), !near(b, start))
|
||||
}
|
||||
} else if near(b, end) {
|
||||
(false, true)
|
||||
} else if near(a, start) {
|
||||
(true, true)
|
||||
} else {
|
||||
(!near(a, end), false)
|
||||
};
|
||||
match (before, turned) {
|
||||
(false, false) => chain.extend(unit),
|
||||
(false, true) => chain.extend(unit.into_iter().rev().map(Piece::flipped)),
|
||||
(true, false) => unit.into_iter().rev().for_each(|p| chain.push_front(p)),
|
||||
(true, true) => unit.into_iter().for_each(|p| chain.push_front(p.flipped())),
|
||||
}
|
||||
// A chain that a join closes takes nothing more.
|
||||
if chain.front().zip(chain.back()).is_some_and(|(f, l)| near(f.start(), l.end())) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
chain.into()
|
||||
}
|
||||
|
||||
/// A segment in the chain JOIN builds: the object it came from, its end points as the object has
|
||||
/// them (turned round when it runs backwards in the chain) and their world heights (a line's own
|
||||
/// Z, an arc's centre Z, a polyline's elevation, negated for one facing down), its bulge and, for a
|
||||
/// polyline's own segment, its widths.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Piece {
|
||||
owner: Handle,
|
||||
ends: (Vec2, Vec2),
|
||||
heights: (f64, f64),
|
||||
bulge: f64,
|
||||
widths: Option<(f64, f64)>,
|
||||
}
|
||||
|
||||
impl Piece {
|
||||
fn flipped(self) -> Self {
|
||||
Piece {
|
||||
ends: (self.ends.1, self.ends.0),
|
||||
heights: (self.heights.1, self.heights.0),
|
||||
bulge: -self.bulge,
|
||||
widths: self.widths.map(|(a, b)| (b, a)),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
fn start(&self) -> (Vec2, f64) {
|
||||
(self.ends.0, self.heights.0)
|
||||
}
|
||||
|
||||
fn end(&self) -> (Vec2, f64) {
|
||||
(self.ends.1, self.heights.1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two ends meet: in plan and at the same height. AutoCAD 2024 leaves an end that meets
|
||||
/// another only in plan apart (measured: a line or a polyline at 0 and a line at 5, or a polyline
|
||||
/// at 5 and a line at 0, end to end in plan, stay as they are).
|
||||
fn meet(p: (Vec2, f64), q: (Vec2, f64), tol: f64) -> bool {
|
||||
p.0.near(q.0, tol) && (p.1 - q.1).abs() < tol
|
||||
}
|
||||
|
||||
/// The open polyline `sp` (handle `src`) with the chain's other pieces added before and after
|
||||
/// it, as AutoCAD 2024 JOIN makes it (measured with `entget`): its own vertices stay exactly as
|
||||
/// they are, and so do its elevation, linetype generation and, when only lines and arcs join,
|
||||
/// its constant width; another polyline's segments keep their bulges and widths; a line or arc
|
||||
/// takes the widths of the source's vertex at the end it joins (first or last); and when another
|
||||
/// polyline joins, the end vertex's widths are cleared.
|
||||
///
|
||||
/// `None` when the source's segments aren't one run of the chain (they always are: the chain
|
||||
/// starts from the source and takes its segments in order).
|
||||
fn onto_polyline(sp: &cadcraft_doc::LwPolyline, src: Handle, links: &[Piece], closed: bool) -> Option<cadcraft_doc::LwPolyline> {
|
||||
let run: Vec<usize> = (0..links.len()).filter(|i| links[*i].owner == src).collect();
|
||||
let (&first, &last) = (run.first()?, run.last()?);
|
||||
if sp.closed || run.len() != last - first + 1 {
|
||||
return None;
|
||||
}
|
||||
let other_polyline = links.iter().any(|l| l.owner != src && l.widths.is_some());
|
||||
let mut own = sp.vertices.clone();
|
||||
if other_polyline && sp.const_width > 0.0 {
|
||||
// The constant width goes, so spell it out on the source's own segments.
|
||||
for v in &mut own {
|
||||
(v.start_width, v.end_width) = (sp.const_width, sp.const_width);
|
||||
}
|
||||
}
|
||||
let widths = |v: &PolyVertex| (v.start_width, v.end_width);
|
||||
let (head, tail) = (widths(own.first()?), widths(own.last()?));
|
||||
let vertex = |i: usize, fill: (f64, f64)| {
|
||||
let (start_width, end_width) = links[i].widths.unwrap_or(fill);
|
||||
PolyVertex { p: links[i].ends.0, bulge: links[i].bulge, start_width, end_width }
|
||||
};
|
||||
let mut vs: Vec<PolyVertex> = (0..first).map(|i| vertex(i, head)).collect();
|
||||
vs.extend(own);
|
||||
if last + 1 < links.len() {
|
||||
// The source's end vertex starts the first piece after it.
|
||||
let v = vertex(last + 1, tail);
|
||||
if let Some(end) = vs.last_mut() {
|
||||
(end.bulge, end.start_width, end.end_width) = (v.bulge, v.start_width, v.end_width);
|
||||
}
|
||||
vs.extend((last + 2..links.len()).map(|i| vertex(i, tail)));
|
||||
vs.push(PolyVertex { p: links.last()?.ends.1, start_width: tail.0, end_width: tail.1, ..Default::default() });
|
||||
}
|
||||
if other_polyline && let Some(end) = vs.last_mut() {
|
||||
(end.start_width, end.end_width) = (0.0, 0.0);
|
||||
}
|
||||
if closed {
|
||||
// The last vertex is the first one again.
|
||||
vs.pop();
|
||||
}
|
||||
Some(cadcraft_doc::LwPolyline { vertices: vs, closed, const_width: if other_polyline { 0.0 } else { sp.const_width }, ..sp.clone() })
|
||||
}
|
||||
|
||||
/// JOIN onto the first object (the source) as AutoCAD 2024 does when the others all lie on its
|
||||
/// line or its circle: gaps and overlaps are bridged and the source keeps its handle.
|
||||
///
|
||||
/// - Lines on the source's line make one line, from the source's start end to the farthest
|
||||
/// point the way it runs (and back past its start if one reaches behind it).
|
||||
/// - Arcs on the source's circle join counterclockwise from the source's start to the farthest
|
||||
/// end; arcs that reach all the way round make a circle, a new object in their place.
|
||||
///
|
||||
/// `None` when the objects aren't all of one of those kinds.
|
||||
fn join_on_source(s: &mut Session, hs: &[Handle]) -> Result<Option<Handle>> {
|
||||
let d = s.doc()?;
|
||||
let ents: Vec<std::sync::Arc<Entity>> = hs.iter().filter_map(|h| d.entity(*h).cloned()).collect();
|
||||
let [src, rest @ ..] = &ents[..] else { return Ok(None) };
|
||||
if rest.is_empty() || ents.len() != hs.len() {
|
||||
return Ok(None);
|
||||
}
|
||||
// AutoCAD 2024 takes lines less than 1e-6 off the source's line, and arcs less than 1e-6
|
||||
// off its centre and radius, at any size of coordinates (measured at 0, 1000 and 2.4e6), and
|
||||
// makes a circle of arcs that come round to less than 1e-6 radians from the source's start.
|
||||
let tol = 1e-6;
|
||||
let kind = match &src.kind {
|
||||
EntityKind::Line(l) => {
|
||||
let (a, b) = (l.a.xy(), l.b.xy());
|
||||
let len = a.dist(b);
|
||||
let lines: Vec<&cadcraft_doc::Line> = rest
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
EntityKind::Line(o) => Some(o),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let level = |z: f64| (z - l.a.z).abs() < tol;
|
||||
if lines.len() != rest.len() || len <= 0.0 || !level(l.b.z) || !lines.iter().all(|o| level(o.a.z) && level(o.b.z)) {
|
||||
return Ok(None);
|
||||
}
|
||||
let u = (b - a) * (1.0 / len);
|
||||
let on_line = |p: Vec2| (p - a).cross(u).abs() < tol;
|
||||
if !lines.iter().all(|o| on_line(o.a.xy()) && on_line(o.b.xy())) {
|
||||
return Ok(None);
|
||||
}
|
||||
let ts = lines.iter().flat_map(|o| [o.a.xy(), o.b.xy()]).map(|p| (p - a).dot(u)).chain([0.0, len]);
|
||||
let (t0, t1) = ts.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), t| (lo.min(t), hi.max(t)));
|
||||
let at = |t: f64| (a + u * t).to3(l.a.z);
|
||||
EntityKind::Line(cadcraft_doc::Line { a: at(t0), b: if t1 == len { l.b } else { at(t1) } })
|
||||
}
|
||||
EntityKind::Arc(g) => {
|
||||
let arcs: Vec<&cadcraft_doc::Arc> = rest
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
EntityKind::Arc(o) => Some(o),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let Some(far) = arc_reach(g, &arcs, tol).filter(|_| arcs.len() == rest.len()) else { return Ok(None) };
|
||||
if far > cadcraft_geom::TAU - tol {
|
||||
let circle = Entity {
|
||||
handle: Handle(0),
|
||||
common: src.common.clone(),
|
||||
kind: EntityKind::Circle(cadcraft_doc::Circle { center: g.center, radius: g.radius }),
|
||||
};
|
||||
// In the source's space, whichever space is current.
|
||||
let space = d.space_of(src.handle).unwrap_or_else(|| s.space());
|
||||
let doc = s.doc_mut()?;
|
||||
for h in hs {
|
||||
doc.remove_entity(*h);
|
||||
}
|
||||
let nh = doc.new_handle();
|
||||
if let Some(st) = doc.space_mut(&space) {
|
||||
st.push(Entity { handle: nh, ..circle });
|
||||
}
|
||||
s.set_selection(Vec::new());
|
||||
return Ok(Some(nh));
|
||||
}
|
||||
let end = if far > cadcraft_geom::ccw_sweep(g.start, g.end) { norm_angle(g.start + far) } else { g.end };
|
||||
EntityKind::Arc(cadcraft_doc::Arc { end, ..g.clone() })
|
||||
}
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let src_h = src.handle;
|
||||
let doc = s.doc_mut()?;
|
||||
for h in hs.iter().filter(|h| **h != src_h) {
|
||||
doc.remove_entity(*h);
|
||||
}
|
||||
doc.modify_entity(src_h, |e| e.kind = kind)?;
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Some(src_h))
|
||||
}
|
||||
|
||||
pub(super) fn run_join(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let hs = targets(s, p)?;
|
||||
if p.get("close").and_then(Value::as_bool) == Some(true) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::break_join::{join, join_makes_circle};
|
||||
use super::break_join::join;
|
||||
use super::explode::explode;
|
||||
use super::transform::{at_elevation, erase, scale_entities, transform_entities};
|
||||
use super::{
|
||||
@@ -20,18 +20,6 @@ pub(super) enum Op {
|
||||
Join,
|
||||
}
|
||||
|
||||
/// COPY's Array option: asking how many items, then where the second one goes (or, with Fit, the
|
||||
/// last one).
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum CopyArray {
|
||||
Off,
|
||||
Count,
|
||||
Items { n: u16, fit: bool },
|
||||
}
|
||||
|
||||
/// The most items COPY's Array option makes, the original included, as in AutoCAD.
|
||||
const MAX_COPY_ITEMS: u16 = 32767;
|
||||
|
||||
/// Select objects, then collect the points/values the operation needs.
|
||||
pub(super) struct SelectThen {
|
||||
op: Op,
|
||||
@@ -49,16 +37,9 @@ pub(super) struct SelectThen {
|
||||
/// SCALE Reference: the reference length, once known.
|
||||
ref_len: Option<f64>,
|
||||
copy_mode: bool,
|
||||
/// COPY: one copy and done (COPYMODE 1, until the Multiple option), else copies until Exit.
|
||||
copy_single: bool,
|
||||
/// COPY: the objects each placement made, so Undo takes back the last one.
|
||||
copies: Vec<Vec<Handle>>,
|
||||
copy_array: CopyArray,
|
||||
ask_erase: bool,
|
||||
/// JOIN of a single arc or elliptical arc: the prompt asks for arcs to join to it, or cLose.
|
||||
join_source: Option<Handle>,
|
||||
/// JOIN of arcs that make a circle: asking whether to.
|
||||
ask_circle: bool,
|
||||
}
|
||||
|
||||
impl SelectThen {
|
||||
@@ -74,12 +55,8 @@ impl SelectThen {
|
||||
ref_from: None,
|
||||
ref_len: None,
|
||||
copy_mode: false,
|
||||
copy_single: false,
|
||||
copies: Vec::new(),
|
||||
copy_array: CopyArray::Off,
|
||||
ask_erase: false,
|
||||
join_source: None,
|
||||
ask_circle: false,
|
||||
}
|
||||
}
|
||||
fn apply(&mut self, s: &mut Session) -> Result<Step> {
|
||||
@@ -107,120 +84,8 @@ impl SelectThen {
|
||||
}
|
||||
}
|
||||
|
||||
/// COPY's prompt once the base point is known, as AutoCAD 2024 asks it.
|
||||
fn copy_prompt(&self, base: Option<Vec2>) -> Prompt {
|
||||
match self.copy_array {
|
||||
CopyArray::Count => Prompt::new("Enter number of items to array", Accept::NUMBER),
|
||||
CopyArray::Items { fit: false, .. } => Prompt::new("Specify second point", Accept::POINT).kw(&["Fit"]).base_opt(base),
|
||||
CopyArray::Items { fit: true, .. } => Prompt::new("Specify second point", Accept::POINT).kw(&["Array"]).base_opt(base),
|
||||
CopyArray::Off if self.copies.is_empty() => {
|
||||
Prompt::new("Specify second point", Accept::POINT).kw(&["Array"]).default("use first point as displacement").base_opt(base)
|
||||
}
|
||||
CopyArray::Off => Prompt::new("Specify second point", Accept::POINT).kw(&["Array", "Exit", "Undo"]).default("Exit").base_opt(base),
|
||||
}
|
||||
}
|
||||
|
||||
/// COPY once the base point is known (AutoCAD 2024, measured): a point places a copy; Enter
|
||||
/// at the first prompt copies by the base point taken as a displacement, and after a copy
|
||||
/// ends the command; Array asks for a number of items, the original included, then puts
|
||||
/// them a second point apart (or, with Fit, spread up to it, Enter keeping them at the
|
||||
/// base); Undo takes back the last placement. One placement ends a single-copy COPY.
|
||||
fn copy_input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
let Some(base) = self.pts.first().copied() else { return Ok(Step::Continue) };
|
||||
let placed = match (self.copy_array, i) {
|
||||
(CopyArray::Count, Input::Enter) => return self.copy_done(s),
|
||||
(CopyArray::Count, i) => {
|
||||
// A whole number as typed, from 2 to 32767 whatever the selection: AutoCAD 2024 takes
|
||||
// +3 and 03 here, refuses 4.0, 1e1, 8/2, 1', 3", 50002 and a point, and doesn't
|
||||
// apply MAXARRAY (with MAXARRAY 100000, four lines and 26000 items made 104000
|
||||
// lines; measured).
|
||||
let n = match i {
|
||||
Input::Text(t) => t.trim().parse::<u16>().ok().filter(|v| (2..=MAX_COPY_ITEMS).contains(v)),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 2 and {MAX_COPY_ITEMS}.")))?;
|
||||
// Not AutoCAD's: the copies (items after the first, times the objects) stay within
|
||||
// ARRAY's own limit, whatever MAXARRAY says, so a large selection can't run out of
|
||||
// memory.
|
||||
let copies = u64::from(n - 1).saturating_mul(u64::try_from(self.objs.len()).unwrap_or(u64::MAX));
|
||||
if copies > cadcraft_doc::MAX_ARRAY_ITEMS {
|
||||
return Err(EngineError::Other(format!(
|
||||
"The array would create {copies} objects; the limit is {}. Use fewer items or select fewer objects.",
|
||||
cadcraft_doc::MAX_ARRAY_ITEMS
|
||||
)));
|
||||
}
|
||||
self.copy_array = CopyArray::Items { n, fit: false };
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
(CopyArray::Items { n, fit }, Input::Keyword(kw)) if kw == if fit { "Array" } else { "Fit" } => {
|
||||
self.copy_array = CopyArray::Items { n, fit: !fit };
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
(CopyArray::Items { n, fit }, i @ (Input::Point(_) | Input::Enter)) => {
|
||||
let p = if let Input::Point(p) = i { p } else { base };
|
||||
let step = if fit { (p - base) * (1.0 / f64::from(n - 1)) } else { p - base };
|
||||
self.copy_array = CopyArray::Off;
|
||||
let mut made = Vec::new();
|
||||
for k in 1..n {
|
||||
match transform_entities(s, &self.objs, &Mat3::translate(step * f64::from(k)), true) {
|
||||
Ok(hs) => made.extend(hs),
|
||||
Err(e) => {
|
||||
// The items made so far are a placement Undo takes back.
|
||||
self.copies.push(made);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
made
|
||||
}
|
||||
(CopyArray::Off, Input::Keyword(kw)) if kw == "Array" => {
|
||||
self.copy_array = CopyArray::Count;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
(CopyArray::Off, Input::Keyword(kw)) if kw == "Undo" => {
|
||||
if let Some(last) = self.copies.pop() {
|
||||
let d = s.doc_mut()?;
|
||||
for h in last {
|
||||
d.remove_entity(h);
|
||||
}
|
||||
if self.copies.is_empty() {
|
||||
s.echo("Command has been completely undone.");
|
||||
}
|
||||
}
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
(CopyArray::Off, Input::Keyword(kw)) if kw == "Exit" => return self.copy_done(s),
|
||||
(CopyArray::Off, Input::Enter) if !self.copies.is_empty() => return self.copy_done(s),
|
||||
(CopyArray::Off, Input::Enter) => {
|
||||
transform_entities(s, &self.objs, &Mat3::translate(base), true)?;
|
||||
return self.copy_done(s);
|
||||
}
|
||||
(CopyArray::Off, Input::Point(p)) => transform_entities(s, &self.objs, &Mat3::translate(p - base), true)?,
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
self.copies.push(placed);
|
||||
if self.copy_single {
|
||||
return self.copy_done(s);
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
fn copy_done(&mut self, s: &mut Session) -> Result<Step> {
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Step::Done)
|
||||
}
|
||||
|
||||
/// JOIN the selected objects and report what they became. Arcs that make a circle ask first,
|
||||
/// as AutoCAD 2024 does.
|
||||
/// JOIN the selected objects and report what they became.
|
||||
fn join_now(&mut self, s: &mut Session) -> Result<Step> {
|
||||
if join_makes_circle(s, &self.objs) {
|
||||
self.ask_circle = true;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
self.join_apply(s)
|
||||
}
|
||||
|
||||
fn join_apply(&mut self, s: &mut Session) -> Result<Step> {
|
||||
match join(s, &self.objs) {
|
||||
Ok(h) => {
|
||||
// Objects outside the joined chain are kept, so count only the ones JOIN consumed
|
||||
@@ -230,9 +95,6 @@ impl SelectThen {
|
||||
let what = match h.and_then(|h| d.entity(h)).map(|e| &e.kind) {
|
||||
Some(EntityKind::Spline(_)) => "spline",
|
||||
Some(EntityKind::Ellipse(_)) => "ellipse",
|
||||
Some(EntityKind::Line(_)) => "line",
|
||||
Some(EntityKind::Arc(_)) => "arc",
|
||||
Some(EntityKind::Circle(_)) => "circle",
|
||||
_ => "polyline",
|
||||
};
|
||||
s.echo(format!("{n} objects joined into 1 {what}"))
|
||||
@@ -446,9 +308,6 @@ impl Interactive for SelectThen {
|
||||
if self.ask_erase {
|
||||
return Prompt::new("Erase source objects?", Accept::TEXT).kw(&["Yes", "No"]).default("No");
|
||||
}
|
||||
if self.ask_circle {
|
||||
return Prompt::new("Combined arc segments form a circle. Convert to circle?", crate::cmd::curves::KW).kw(&["Yes", "No"]).default("Yes");
|
||||
}
|
||||
if let Some(src) = self.join_source {
|
||||
let ellipse = s.doc().is_ok_and(|d| matches!(d.entity(src).map(|e| &e.kind), Some(EntityKind::Ellipse(_))));
|
||||
let msg = if ellipse { "Select elliptical arcs to join to source" } else { "Select arcs to join to source" };
|
||||
@@ -469,7 +328,7 @@ impl Interactive for SelectThen {
|
||||
match (self.op, k) {
|
||||
(Op::Move | Op::Copy, 0) => Prompt::new("Specify base point", Accept::POINT).kw(&["Displacement"]),
|
||||
(Op::Move, _) => Prompt::new("Specify second point or <use first point as displacement>", Accept::POINT).base_opt(base),
|
||||
(Op::Copy, _) => self.copy_prompt(base),
|
||||
(Op::Copy, _) => Prompt::new("Specify second point", Accept::POINT).kw(&["Array", "Exit", "Undo"]).base_opt(base),
|
||||
(Op::Rotate | Op::Scale, 0) => Prompt::new("Specify base point", Accept::POINT),
|
||||
// ROTATE and SCALE offer the angle/factor used last time.
|
||||
(Op::Rotate, _) => {
|
||||
@@ -502,14 +361,6 @@ impl Interactive for SelectThen {
|
||||
}
|
||||
}
|
||||
}
|
||||
// No leaves every arc as it is (AutoCAD 2024, measured).
|
||||
if self.ask_circle {
|
||||
return match &i {
|
||||
Input::Keyword(k) if k == "No" => Ok(Step::Done),
|
||||
Input::Keyword(_) | Input::Enter => self.join_apply(s),
|
||||
_ => Err(EngineError::Other("Invalid option keyword.".into())),
|
||||
};
|
||||
}
|
||||
if let Some(src) = self.join_source {
|
||||
return self.join_source_input(s, src, i);
|
||||
}
|
||||
@@ -537,6 +388,10 @@ impl Interactive for SelectThen {
|
||||
self.reference = true;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(Op::Copy, _, Input::Keyword(kw)) if kw == "Exit" => {
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(_, 0, Input::Point(p)) => {
|
||||
self.pts.push(p);
|
||||
Ok(Step::Continue)
|
||||
@@ -553,7 +408,15 @@ impl Interactive for SelectThen {
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Op::Copy, _, i) => self.copy_input(s, i),
|
||||
(Op::Copy, _, Input::Point(p)) => {
|
||||
let d = p - self.pts[0];
|
||||
transform_entities(s, &self.objs, &Mat3::translate(d), true)?;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(Op::Copy, _, Input::Enter) => {
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Op::Rotate, 1, inp @ (Input::Point(_) | Input::Text(_) | Input::Enter)) => {
|
||||
let a = match inp {
|
||||
Input::Point(p) => self.pts[0].angle_to(p),
|
||||
@@ -679,13 +542,11 @@ impl Interactive for SelectThen {
|
||||
pub(super) struct DisplaceM {
|
||||
inner: SelectThen,
|
||||
displacement: bool,
|
||||
/// COPY's mOde option: asking Single or Multiple.
|
||||
ask_mode: bool,
|
||||
}
|
||||
|
||||
impl DisplaceM {
|
||||
pub(super) fn new(op: Op) -> Self {
|
||||
DisplaceM { inner: SelectThen::new(op), displacement: false, ask_mode: false }
|
||||
DisplaceM { inner: SelectThen::new(op), displacement: false }
|
||||
}
|
||||
/// At "Specify base point": objects selected, no point yet.
|
||||
fn at_base(&self) -> bool {
|
||||
@@ -698,26 +559,14 @@ impl Interactive for DisplaceM {
|
||||
self.inner.name()
|
||||
}
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
self.inner.copy_single = self.inner.op == Op::Copy && s.settings.copymode;
|
||||
self.inner.begin(s)
|
||||
}
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
if self.displacement {
|
||||
return Prompt::new("Specify displacement", Accept::POINT).default("0,0");
|
||||
}
|
||||
if self.ask_mode {
|
||||
let current = if s.settings.copymode { "Single" } else { "Multiple" };
|
||||
return Prompt::new("Enter a copy mode option", crate::cmd::curves::KW).kw(&["Single", "Multiple"]).default(current);
|
||||
}
|
||||
if self.at_base() {
|
||||
// COPY: mOde sets COPYMODE; Multiple, offered while it is single, copies until Exit
|
||||
// this once.
|
||||
let kw: &[&str] = match self.inner.op {
|
||||
Op::Copy if self.inner.copy_single => &["Displacement", "mOde", "Multiple"],
|
||||
Op::Copy => &["Displacement", "mOde"],
|
||||
_ => &["Displacement"],
|
||||
};
|
||||
return Prompt::new("Specify base point", Accept::POINT).kw(kw).default("Displacement");
|
||||
return Prompt::new("Specify base point", Accept::POINT).kw(&["Displacement"]).default("Displacement");
|
||||
}
|
||||
self.inner.prompt(s)
|
||||
}
|
||||
@@ -734,34 +583,10 @@ impl Interactive for DisplaceM {
|
||||
s.set_selection(Vec::new());
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
if self.ask_mode {
|
||||
match &i {
|
||||
Input::Keyword(k) if k == "Single" || k == "Multiple" => s.settings.copymode = k == "Single",
|
||||
Input::Enter => {}
|
||||
_ => return Ok(Step::Continue),
|
||||
}
|
||||
// The mode shown is the mode this COPY runs in, Enter keeping it.
|
||||
self.inner.copy_single = s.settings.copymode;
|
||||
self.ask_mode = false;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if self.at_base() && (matches!(&i, Input::Enter) || matches!(&i, Input::Keyword(k) if k == "Displacement")) {
|
||||
self.displacement = true;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if self.at_base() && self.inner.op == Op::Copy {
|
||||
match &i {
|
||||
Input::Keyword(k) if k == "mOde" => {
|
||||
self.ask_mode = true;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
Input::Keyword(k) if k == "Multiple" => {
|
||||
self.inner.copy_single = false;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.inner.input(s, i)
|
||||
}
|
||||
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
|
||||
|
||||
@@ -3,7 +3,6 @@ use super::{
|
||||
Accept, Entity, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelectKind, SelectMode, Session, Step, Value, Vec2, bad, json,
|
||||
line, points_param,
|
||||
};
|
||||
use cadcraft_geom::Arc;
|
||||
|
||||
/// An area whose vertices STRETCH moves: a window's box, or a polygon closed back to its first
|
||||
/// point.
|
||||
@@ -41,18 +40,6 @@ fn add_mline_vertex_hits(s: &Session, area: &StretchArea, hs: &mut Vec<Handle>)
|
||||
}
|
||||
}
|
||||
|
||||
/// The bulge that keeps an arc's height (bulge × chord / 2) when its chord changes length; none
|
||||
/// once the chord collapses to a point, which has no arc left to keep.
|
||||
fn keep_height(bulge: f64, old_chord: f64, new_chord: f64) -> f64 {
|
||||
if new_chord.is_nan() || new_chord <= 1e-12 {
|
||||
0.0
|
||||
} else if old_chord.is_finite() {
|
||||
bulge * old_chord / new_chord
|
||||
} else {
|
||||
bulge
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the vertices of `e` that lie inside any of the areas `wins` by `d` (STRETCH).
|
||||
fn stretch_entity(e: &mut Entity, wins: &[StretchArea], d: Vec2) {
|
||||
let inside = |p: Vec2| wins.iter().any(|a| a.contains(p));
|
||||
@@ -68,56 +55,18 @@ fn stretch_entity(e: &mut Entity, wins: &[StretchArea], d: Vec2) {
|
||||
mv(&mut l.b);
|
||||
}
|
||||
EntityKind::LwPolyline(pl) => {
|
||||
let old: Vec<Vec2> = pl.vertices.iter().map(|v| v.p).collect();
|
||||
for v in &mut pl.vertices {
|
||||
if inside(v.p) {
|
||||
v.p += d;
|
||||
}
|
||||
}
|
||||
// An arc segment keeps its height (bulge × chord / 2) as its ends move, as in AutoCAD.
|
||||
let n = pl.vertices.len();
|
||||
let segs = if pl.closed { n } else { n.saturating_sub(1) };
|
||||
for i in 0..segs {
|
||||
let j = (i + 1) % n;
|
||||
let (Some(a0), Some(b0), Some(b1)) = (old.get(i), old.get(j), pl.vertices.get(j).map(|v| v.p)) else { continue };
|
||||
if let Some(v) = pl.vertices.get_mut(i)
|
||||
&& v.bulge != 0.0
|
||||
{
|
||||
v.bulge = keep_height(v.bulge, a0.dist(*b0), v.p.dist(b1));
|
||||
}
|
||||
}
|
||||
}
|
||||
EntityKind::MLine(m) => m.vertices.iter_mut().for_each(|v| mv(&mut v.p)),
|
||||
EntityKind::Arc(a) => {
|
||||
// AutoCAD moves the ends inside the area and keeps the arc's height (bulge × chord / 2);
|
||||
// the centre alone moves nothing. An end stretched onto the other leaves the arc as it
|
||||
// was: AutoCAD collapses it into a zero-radius arc at that point (radius 6e-16, start
|
||||
// 180°, end 0°), an object nothing can draw or pick, which CADCraft does not make.
|
||||
let g = Arc::new(a.center.xy(), a.radius, a.start, a.end);
|
||||
let (s0, e0) = (g.start_point(), g.end_point());
|
||||
let (s_in, e_in) = (inside(s0), inside(e0));
|
||||
let (s1, e1) = (if s_in { s0 + d } else { s0 }, if e_in { e0 + d } else { e0 });
|
||||
if s_in && e_in {
|
||||
// Both ends move: the arc moves whole (a full sweep has no chord to rebuild from).
|
||||
(a.center.x, a.center.y) = (a.center.x + d.x, a.center.y + d.y);
|
||||
} else if (s_in || e_in)
|
||||
&& let Some((r, _)) =
|
||||
cadcraft_geom::bulge_to_arc(s1, e1, keep_height(cadcraft_geom::arc_to_bulge(g.sweep()), s0.dist(e0), s1.dist(e1)))
|
||||
{
|
||||
(a.center.x, a.center.y) = (r.center.x, r.center.y);
|
||||
(a.radius, a.start, a.end) = (r.radius, r.start, r.end);
|
||||
}
|
||||
}
|
||||
// Control points inside the area move (AutoCAD).
|
||||
EntityKind::Spline(sp) if sp.fit.is_empty() => sp.control.iter_mut().filter(|p| inside(**p)).for_each(|p| *p += d),
|
||||
// A spline built from fit points: the fit points inside the area move and it is fitted
|
||||
// through them again, its fit data kept (AutoCAD 2024). All of them inside, it moves.
|
||||
EntityKind::Spline(sp) => {
|
||||
if sp.fit.iter().all(|p| inside(*p)) {
|
||||
sp.transform(&Mat3::translate(d));
|
||||
} else if sp.fit.iter().any(|p| inside(*p)) {
|
||||
let fit: Vec<Vec2> = sp.fit.iter().map(|p| if inside(*p) { *p + d } else { *p }).collect();
|
||||
*sp = sp.refit(&fit, sp.closed);
|
||||
// Arcs keep their shape: move when the centre is inside.
|
||||
if inside(a.center.xy()) {
|
||||
a.center.x += d.x;
|
||||
a.center.y += d.y;
|
||||
}
|
||||
}
|
||||
EntityKind::Solid(so) | EntityKind::Trace(so) => so.corners.iter_mut().for_each(mv),
|
||||
|
||||
@@ -84,7 +84,6 @@ pub(crate) fn at_elevation(s: &Session, p: Vec2) -> Vec3 {
|
||||
fn edit_entities(s: &mut Session, hs: &[Handle], copy: bool, edit: impl Fn(&mut Entity)) -> Result<Vec<Handle>> {
|
||||
let d = s.doc_mut()?;
|
||||
let mut out = Vec::new();
|
||||
let mut copies = Vec::new();
|
||||
for h in hs {
|
||||
let Some(sp) = d.space_of(*h) else { continue };
|
||||
if copy {
|
||||
@@ -95,7 +94,6 @@ fn edit_entities(s: &mut Session, hs: &[Handle], copy: bool, edit: impl Fn(&mut
|
||||
if let Some(st) = d.space_mut(&sp) {
|
||||
st.push(ne);
|
||||
out.push(nh);
|
||||
copies.push((*h, nh));
|
||||
}
|
||||
} else {
|
||||
let locked = d.entity(*h).and_then(|e| d.layer(&e.common.layer)).is_some_and(|l| l.locked);
|
||||
@@ -106,9 +104,6 @@ fn edit_entities(s: &mut Session, hs: &[Handle], copy: bool, edit: impl Fn(&mut
|
||||
out.push(*h);
|
||||
}
|
||||
}
|
||||
if copy && !copies.is_empty() {
|
||||
crate::cmd::groups::replicate_groups_for_copies(d, &copies);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
|
||||
use cadcraft_doc::{Common, Entity, EntityKind, Handle, LwPolyline, MAX_BLOCK_DEPTH, Space};
|
||||
use cadcraft_geom::{
|
||||
Arc, Ellipse, Line, Mat3, PolyVertex, Polyline, Segment, Spline, TAU, Vec2, Vec3, ccw_sweep, intersect_ext, line_circle, line_line_infinite,
|
||||
norm_angle,
|
||||
Arc, Ellipse, Line, Mat3, PolyVertex, Polyline, Segment, Spline, TAU, Vec2, ccw_sweep, intersect_ext, line_circle, line_line_infinite, norm_angle,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -40,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(
|
||||
"{handle, option: close|open|join|reverse|refit|purge|polyline|move|fitmove|fitadd|fitdelete|kink|tangents|tolerance|vertexadd|vertexmove|vertexdelete|weight|elevate, \
|
||||
handles2? (join), fit?, index?, to?, before?: bool (fitadd), at? (kink, vertexadd), start?, end? (tangent directions; null = default), tolerance?, weight?, \
|
||||
order? (elevate), precision?: 0..99 (polyline, default 10)}",
|
||||
order? (elevate), precision?}",
|
||||
)
|
||||
.interactive(|_| Ok(Box::new(SplineditM::default()))),
|
||||
CommandSpec::new("lengthen", "Lengthen", run_lengthen)
|
||||
@@ -123,47 +122,6 @@ pub(crate) fn as_lwpoly(k: &EntityKind) -> Option<LwPolyline> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The polyline PEDIT turns a line or an arc into, and the normal it faces, as AutoCAD 2024 makes
|
||||
/// them (measured): facing the way the arc faces, and up for a line whatever its normal; at the
|
||||
/// line's height, or at the arc's centre height measured along its normal (a mirrored arc whose
|
||||
/// centre is at world Z -5 gives elevation 5, one at Z 5 elevation -5); the thickness stays the
|
||||
/// object's. A sloped line still comes out at elevation 0: AutoCAD makes a polyline in the line's
|
||||
/// vertical plane, which a CADCraft polyline can't be. An arc in a tilted plane (normal neither up
|
||||
/// nor down Z), which CADCraft keeps only approximately, keeps its normal and goes by the sign of
|
||||
/// its Z as above; AutoCAD's result for one isn't measured. A polyline is returned as it is.
|
||||
pub(crate) fn polyline_of(e: &Entity) -> Option<(LwPolyline, Vec3)> {
|
||||
let mut pl = as_lwpoly(&e.kind)?;
|
||||
let normal = e.common.extrusion;
|
||||
match &e.kind {
|
||||
EntityKind::Line(l) => {
|
||||
if (l.a.z - l.b.z).abs() < 1e-9 {
|
||||
pl.elevation = l.a.z;
|
||||
}
|
||||
Some((pl, Vec3::Z))
|
||||
}
|
||||
// The arc's centre is in world coordinates; a polyline's elevation runs along its normal.
|
||||
// A mirrored arc runs clockwise in plan, and so does its polyline (AutoCAD 2024 starts it
|
||||
// at the arc's start in the arc's own coordinates).
|
||||
EntityKind::Arc(a) => {
|
||||
pl.elevation = if normal.z < 0.0 { -a.center.z } else { a.center.z };
|
||||
if normal.z < 0.0 {
|
||||
pl.vertices = curves::reverse_vertices(&pl.vertices, false);
|
||||
}
|
||||
Some((pl, normal))
|
||||
}
|
||||
_ => Some((pl, normal)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts the polyline `pl`, facing `normal`, in place of the object `h`.
|
||||
fn set_polyline(s: &mut Session, h: Handle, pl: LwPolyline, normal: Vec3) -> Result<()> {
|
||||
s.doc_mut()?.modify_entity(h, |e| {
|
||||
e.kind = EntityKind::LwPolyline(pl);
|
||||
e.common.extrusion = normal;
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
mod pedit_multi;
|
||||
mod pedit_vertex;
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
Accept, Chain, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Value, bad, bool_or, curves, json,
|
||||
other, targets,
|
||||
number, other, targets,
|
||||
};
|
||||
|
||||
// =====================================================================================
|
||||
@@ -26,13 +26,7 @@ pub(crate) fn arraypath(
|
||||
return Err(other("Select objects to array."));
|
||||
}
|
||||
let (n, step) = match (count, spacing) {
|
||||
// As AutoCAD 2024 fills a path by distance: floor(length / spacing) items on a closed path,
|
||||
// so none lands on or near the first where the path closes, and one more, at the end, on
|
||||
// an open one (measured). The 1e-9 lets a length that comes out a hair short still fit.
|
||||
(_, Some(sp)) if sp.is_finite() && sp > 0.0 => {
|
||||
let fit = (l / sp + 1e-9).floor() as usize;
|
||||
(if c.closed { fit.max(1) } else { fit.saturating_add(1) }, sp)
|
||||
}
|
||||
(_, Some(sp)) if sp.is_finite() && sp > 0.0 => (((l / sp).floor() as usize).saturating_add(1), sp),
|
||||
(Some(n), _) => {
|
||||
let n = n.max(1);
|
||||
(n, if c.closed { l / n as f64 } else { l / (n.max(2) - 1) as f64 })
|
||||
@@ -67,25 +61,12 @@ pub(crate) fn arraypath(
|
||||
pub(super) fn run_arraypath(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let hs = targets(s, p)?;
|
||||
let path = curves::handle_param(p, "path").ok_or_else(|| bad("arraypath", "`path` (handle) is required"))?;
|
||||
// As in the other arrays' JSON forms, a value that isn't a whole number of at least 1 (or a
|
||||
// positive spacing) is refused, not ignored; missing or null is the default.
|
||||
let count = crate::cmd::array::count_or("arraypath", p, "count", 6)?;
|
||||
let spacing = crate::cmd::size_param("arraypath", p, "spacing", false)?;
|
||||
let r = arraypath(s, &hs, path, Some(usize::try_from(count).unwrap_or(usize::MAX)), spacing, bool_or(p, "align", true))?;
|
||||
let count = p.get("count").and_then(Value::as_u64).map(|n| usize::try_from(n).unwrap_or(usize::MAX));
|
||||
let spacing = p.get("spacing").and_then(Value::as_f64);
|
||||
let r = arraypath(s, &hs, path, count, spacing, bool_or(p, "align", true))?;
|
||||
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// The number of items typed at ARRAYPATH's prompt: a whole number from 1 to 32767, written in
|
||||
/// plain decimals. AutoCAD 2024 takes 5, +5, 05, 5., 5.0, 5.00 and +5.0 there, and refuses 4.5,
|
||||
/// 1e1, 8/2, 3', 0 and 32768 (measured).
|
||||
pub(super) fn item_count(t: &str) -> Option<usize> {
|
||||
let t = t.trim();
|
||||
let digits = t.strip_prefix('+').unwrap_or(t);
|
||||
let (whole, fraction) = digits.split_once('.').unwrap_or((digits, ""));
|
||||
let plain = !whole.is_empty() && whole.bytes().all(|b| b.is_ascii_digit()) && fraction.bytes().all(|b| b == b'0');
|
||||
whole.parse::<usize>().ok().filter(|n| plain && (1..=32_767).contains(n))
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(in crate::cmd) struct PathArrayM {
|
||||
sel: SelectPhase,
|
||||
@@ -140,7 +121,7 @@ impl Interactive for PathArrayM {
|
||||
}
|
||||
(Some(path), inp @ (Input::Text(_) | Input::Enter)) => {
|
||||
let n = match &inp {
|
||||
Input::Text(t) => item_count(t).ok_or_else(|| other("Requires an integer between 1 and 32767."))?,
|
||||
Input::Text(t) => number(t).filter(|n| *n >= 1.0).ok_or_else(|| other("Requires a count of 1 or more."))? as usize,
|
||||
_ => 6,
|
||||
};
|
||||
arraypath(s, &self.objs, path, Some(n), None, true)?;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{
|
||||
Accept, Chain, Entity, EntityKind, Handle, Input, Interactive, LwPolyline, MAX_GEN, PolyVertex, Prompt, Result, SelOutcome, SelectPhase, Session,
|
||||
Spline, Step, Value, Vec2, Vec3, as_lwpoly, bad, bool_or, curves, f64_or, f64_req, json, line, number, other, pedit_vertex, point_req,
|
||||
polyline_of, set_kind, set_polyline, str_param, targets,
|
||||
Accept, Chain, EntityKind, Handle, Input, Interactive, LwPolyline, MAX_GEN, PolyVertex, Prompt, Result, SelOutcome, SelectPhase, Session, Spline,
|
||||
Step, Value, Vec2, as_lwpoly, bad, bool_or, curves, f64_or, f64_req, json, line, number, other, pedit_vertex, point_req, set_kind, str_param,
|
||||
targets,
|
||||
};
|
||||
|
||||
/// Fit curve: a tangent-continuous pair of arcs (biarc) per segment through every vertex,
|
||||
@@ -106,21 +106,7 @@ pub(crate) fn spline_vertices(vs: &[PolyVertex], closed: bool, segs: usize) -> V
|
||||
}
|
||||
|
||||
/// Join connected lines/arcs/open polylines onto the ends of polyline `h` (kept in place).
|
||||
///
|
||||
/// As AutoCAD 2024 joins (measured), none facing the other way: an arc or a polyline whose normal
|
||||
/// points down Z where the polyline's points up, or the other way round; a line counts as facing
|
||||
/// up. Multiple's Join (`same_height` false) takes them at any height (lines at Z 5 and Z 0 join).
|
||||
///
|
||||
/// PEDIT's own Join takes only objects in one plane with the polyline: the plane the polyline and
|
||||
/// every line picked share, when they share one, else the polyline's own. So a sloped line joins
|
||||
/// only when the polyline and all the lines picked lie in one plane (a vertical one for a sloped
|
||||
/// line continuing a straight polyline in plan), and then no arc or polyline joins, as those lie
|
||||
/// flat; otherwise only objects at the polyline's height join (a line, arc or polyline at Z 0
|
||||
/// stays off one at Z 5). Ends meet within `fuzz` in plan and within 1e-6 in height, which `fuzz`
|
||||
/// doesn't widen. After a sloped line the chain's end is at the line's far end, so the next object
|
||||
/// meets it there; AutoCAD's polyline then lies in the lines' plane, CADCraft's keeps the source's
|
||||
/// elevation and runs through the objects' points seen from above.
|
||||
pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f64, same_height: bool) -> Result<usize> {
|
||||
pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f64) -> Result<usize> {
|
||||
let e = curves::entity(s, h)?;
|
||||
let mut base = as_lwpoly(&e.kind).ok_or_else(|| other("Select a polyline."))?;
|
||||
if base.closed {
|
||||
@@ -128,88 +114,46 @@ pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f6
|
||||
}
|
||||
let mut chain = Chain::of(&EntityKind::LwPolyline(base.clone())).unwrap_or_default();
|
||||
let tol = fuzz.max(1e-6);
|
||||
// Which way an object faces, and its two ends' world heights.
|
||||
let down = |e: &Entity| !matches!(e.kind, EntityKind::Line(_)) && e.common.extrusion.z < 0.0;
|
||||
let heights = |e: &Entity| match &e.kind {
|
||||
EntityKind::Line(l) => (l.a.z, l.b.z),
|
||||
// An arc's centre is in world coordinates.
|
||||
EntityKind::Arc(a) => (a.center.z, a.center.z),
|
||||
// A polyline's elevation runs along its normal.
|
||||
EntityKind::LwPolyline(p) => {
|
||||
let z = if down(e) { -p.elevation } else { p.elevation };
|
||||
(z, z)
|
||||
}
|
||||
_ => (0.0, 0.0),
|
||||
};
|
||||
// Two ends meet: in plan within the fuzz distance, and for PEDIT's own Join at the same height.
|
||||
let at = |p: Vec2, ph: f64, q: Vec2, qh: f64| p.near(q, tol) && (!same_height || (ph - qh).abs() < 1e-6);
|
||||
let picked: Vec<(Handle, Entity)> = others.iter().filter(|o| **o != h).filter_map(|o| Some((*o, curves::entity(s, *o).ok()?))).collect();
|
||||
// The plane PEDIT's own Join works in (AutoCAD 2024, measured): the polyline's points, with a
|
||||
// point off the chord of an arc segment, which lies flat, and the ends of every line picked.
|
||||
let z0 = heights(&e).0;
|
||||
let mut pts: Vec<Vec3> = base.vertices.iter().map(|v| Vec3::new(v.p.x, v.p.y, z0)).collect();
|
||||
if let Some(w) = base.vertices.windows(2).find(|w| w[0].bulge.abs() > 1e-12) {
|
||||
let (a, b) = (w[0].p, w[1].p);
|
||||
let off = (a + b) * 0.5 + Vec2::new(a.y - b.y, b.x - a.x);
|
||||
pts.push(Vec3::new(off.x, off.y, z0));
|
||||
}
|
||||
let lines: Vec<(Vec3, Vec3)> =
|
||||
picked.iter().filter_map(|(_, oe)| if let EntityKind::Line(l) = &oe.kind { Some((l.a, l.b)) } else { None }).collect();
|
||||
pts.extend(lines.iter().flat_map(|(a, b)| [*a, *b]));
|
||||
let shared = coplanar(&pts);
|
||||
// That plane is the polyline's own, flat, when every line is at its height.
|
||||
let level = lines.iter().all(|(a, b)| (a.z - z0).abs() < 1e-6 && (b.z - z0).abs() < 1e-6);
|
||||
let mut pool: Vec<(Handle, Chain, (f64, f64))> = Vec::new();
|
||||
for (o, oe) in &picked {
|
||||
if down(oe) != down(&e) {
|
||||
let mut pool: Vec<(Handle, Chain)> = Vec::new();
|
||||
for o in others {
|
||||
if *o == h {
|
||||
continue;
|
||||
}
|
||||
let line = matches!(oe.kind, EntityKind::Line(_));
|
||||
let (ah, bh) = heights(oe);
|
||||
// A sloped line lies in no flat plane, and an arc or a polyline in no other.
|
||||
let off_plane = if shared && !level { !line } else { (ah - bh).abs() >= 1e-6 };
|
||||
if same_height && off_plane {
|
||||
continue;
|
||||
}
|
||||
let ok = line || matches!(&oe.kind, EntityKind::Arc(_)) || matches!(&oe.kind, EntityKind::LwPolyline(p) if !p.closed);
|
||||
let Ok(oe) = curves::entity(s, *o) else { continue };
|
||||
let ok = matches!(&oe.kind, EntityKind::Line(_) | EntityKind::Arc(_)) || matches!(&oe.kind, EntityKind::LwPolyline(p) if !p.closed);
|
||||
if ok && let Some(c) = Chain::of(&oe.kind) {
|
||||
pool.push((*o, c, (ah, bh)));
|
||||
pool.push((*o, c));
|
||||
}
|
||||
}
|
||||
let (mut st_h, mut en_h) = heights(&e);
|
||||
let mut joined = Vec::new();
|
||||
while let (Some(st), Some(en)) = (chain.start(), chain.end()) {
|
||||
let meets = |c: &Chain, (ah, bh): (f64, f64)| {
|
||||
c.start().zip(c.end()).is_some_and(|(a, b)| at(a, ah, en, en_h) || at(b, bh, en, en_h) || at(a, ah, st, st_h) || at(b, bh, st, st_h))
|
||||
};
|
||||
let Some(i) = pool.iter().position(|(_, c, z)| meets(c, *z)) else {
|
||||
let Some(i) = pool
|
||||
.iter()
|
||||
.position(|(_, c)| c.start().zip(c.end()).is_some_and(|(a, b)| a.near(en, tol) || b.near(en, tol) || a.near(st, tol) || b.near(st, tol)))
|
||||
else {
|
||||
break;
|
||||
};
|
||||
let (oh, c, (ah, bh)) = pool.remove(i);
|
||||
let (oh, c) = pool.remove(i);
|
||||
let (Some(a), Some(b)) = (c.start(), c.end()) else { continue };
|
||||
if at(a, ah, en, en_h) {
|
||||
if a.near(en, tol) {
|
||||
chain.segs.extend(c.segs);
|
||||
en_h = bh;
|
||||
} else if at(b, bh, en, en_h) {
|
||||
} else if b.near(en, tol) {
|
||||
chain.segs.extend(c.reversed().segs);
|
||||
en_h = ah;
|
||||
} else if at(b, bh, st, st_h) {
|
||||
} else if b.near(st, tol) {
|
||||
let mut v = c.segs;
|
||||
v.extend(chain.segs);
|
||||
chain.segs = v;
|
||||
st_h = ah;
|
||||
} else {
|
||||
let mut v = c.reversed().segs;
|
||||
v.extend(chain.segs);
|
||||
chain.segs = v;
|
||||
st_h = bh;
|
||||
}
|
||||
joined.push(oh);
|
||||
}
|
||||
if joined.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
chain.closed = chain.start().zip(chain.end()).is_some_and(|(a, b)| at(a, st_h, b, en_h)) && chain.segs.len() > 1;
|
||||
chain.closed = chain.start().zip(chain.end()).is_some_and(|(a, b)| a.near(b, tol)) && chain.segs.len() > 1;
|
||||
base.vertices = chain.vertices();
|
||||
base.closed = chain.closed;
|
||||
let d = s.doc_mut()?;
|
||||
@@ -220,29 +164,14 @@ pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f6
|
||||
Ok(joined.len())
|
||||
}
|
||||
|
||||
/// Whether the points `pts` lie in one plane, to within 1e-6 (points in a line always do).
|
||||
fn coplanar(pts: &[Vec3]) -> bool {
|
||||
let Some(&p0) = pts.first() else { return true };
|
||||
let far = |a: &&Vec3, b: &&Vec3| (**a - p0).len().total_cmp(&(**b - p0).len());
|
||||
let Some(&p1) = pts.iter().max_by(far) else { return true };
|
||||
let d = p1 - p0;
|
||||
// The normal from the point farthest off the line p0 p1, for the least rounding.
|
||||
let Some(n) = pts.iter().map(|p| d.cross(*p - p0)).max_by(|a, b| a.len().total_cmp(&b.len())) else { return true };
|
||||
if n.len() <= 1e-6 * d.len() {
|
||||
return true;
|
||||
}
|
||||
let n = n.normalized();
|
||||
pts.iter().all(|p| n.dot(*p - p0).abs() < 1e-6)
|
||||
}
|
||||
|
||||
pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> Result<Value> {
|
||||
let e = curves::entity(s, h)?;
|
||||
if curves::is_locked(s, h) {
|
||||
return Err(other("The object is on a locked layer."));
|
||||
}
|
||||
let (mut pl, normal) = match &e.kind {
|
||||
EntityKind::LwPolyline(pl) => (pl.clone(), e.common.extrusion),
|
||||
EntityKind::Line(_) | EntityKind::Arc(_) if bool_or(p, "convert", true) => polyline_of(&e).ok_or_else(|| other("Cannot convert."))?,
|
||||
let mut pl = match &e.kind {
|
||||
EntityKind::LwPolyline(pl) => pl.clone(),
|
||||
EntityKind::Line(_) | EntityKind::Arc(_) if bool_or(p, "convert", true) => as_lwpoly(&e.kind).ok_or_else(|| other("Cannot convert."))?,
|
||||
_ => return Err(other("Object selected is not a polyline.")),
|
||||
};
|
||||
match opt {
|
||||
@@ -268,14 +197,14 @@ pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> R
|
||||
"reverse" | "r" => pl.vertices = curves::reverse_vertices(&pl.vertices, pl.closed),
|
||||
"ltypegen" | "l" => pl.plinegen = bool_or(p, "on", !pl.plinegen),
|
||||
"join" | "j" => {
|
||||
set_polyline(s, h, pl, normal)?;
|
||||
set_kind(s, h, EntityKind::LwPolyline(pl))?;
|
||||
let others: Vec<Handle> = p
|
||||
.get("handles2")
|
||||
.or_else(|| p.get("join"))
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(curves::handle_value).collect())
|
||||
.unwrap_or_default();
|
||||
let n = pedit_join(s, h, &others, f64_or(p, "fuzz", 0.0), true)?;
|
||||
let n = pedit_join(s, h, &others, f64_or(p, "fuzz", 0.0))?;
|
||||
return Ok(json!({ "handle": h.hex(), "joined": n }));
|
||||
}
|
||||
"vertex" | "e" => {
|
||||
@@ -325,7 +254,7 @@ pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> R
|
||||
}
|
||||
_ => return Err(bad("pedit", "unknown option")),
|
||||
}
|
||||
set_polyline(s, h, pl, normal)?;
|
||||
set_kind(s, h, EntityKind::LwPolyline(pl))?;
|
||||
Ok(json!({ "handle": h.hex() }))
|
||||
}
|
||||
|
||||
@@ -539,9 +468,10 @@ impl Interactive for PeditM {
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
let h = self.h.ok_or_else(|| other("No object."))?;
|
||||
let (pl, normal) = polyline_of(&curves::entity(s, h)?).ok_or_else(|| other("Cannot convert."))?;
|
||||
let k = curves::entity(s, h)?.kind;
|
||||
let pl = as_lwpoly(&k).ok_or_else(|| other("Cannot convert."))?;
|
||||
self.original = Some(pl.vertices.clone());
|
||||
set_polyline(s, h, pl, normal)?;
|
||||
set_kind(s, h, EntityKind::LwPolyline(pl))?;
|
||||
self.phase = PPhase::Main;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
@@ -614,7 +544,7 @@ impl Interactive for PeditM {
|
||||
SelOutcome::Done(hs) => {
|
||||
let h = self.h.ok_or_else(|| other("No polyline."))?;
|
||||
self.snapshot(s);
|
||||
let n = pedit_join(s, h, &hs, 0.0, true)?;
|
||||
let n = pedit_join(s, h, &hs, 0.0)?;
|
||||
s.echo(format!("{n} segments added to polyline"));
|
||||
s.set_selection(vec![h]);
|
||||
self.phase = PPhase::Main;
|
||||
|
||||
@@ -8,7 +8,7 @@ use serde_json::json;
|
||||
use super::super::curves;
|
||||
use super::super::machines::{SelOutcome, SelectPhase, number};
|
||||
use super::pedit::{PPhase, PeditM, clear_widths, pedit_apply, pedit_join, yes_no};
|
||||
use super::{other, polyline_of, set_kind, set_polyline};
|
||||
use super::{as_lwpoly, other, set_kind};
|
||||
use crate::{Accept, Input, Prompt, Result, Session, Step};
|
||||
|
||||
/// Most option steps Undo can take back.
|
||||
@@ -78,13 +78,13 @@ impl PeditM {
|
||||
let no = !yes_no(&i)?;
|
||||
let mut kept = Vec::new();
|
||||
for h in std::mem::take(&mut self.multi) {
|
||||
let e = curves::entity(s, h)?;
|
||||
match e.kind {
|
||||
let kind = curves::entity(s, h)?.kind;
|
||||
match kind {
|
||||
EntityKind::LwPolyline(_) => kept.push(h),
|
||||
_ if no => {}
|
||||
_ => {
|
||||
if let Some((pl, normal)) = polyline_of(&e) {
|
||||
set_polyline(s, h, pl, normal)?;
|
||||
k => {
|
||||
if let Some(pl) = as_lwpoly(&k) {
|
||||
set_kind(s, h, EntityKind::LwPolyline(pl))?;
|
||||
kept.push(h);
|
||||
}
|
||||
}
|
||||
@@ -219,7 +219,7 @@ impl PeditM {
|
||||
let open = matches!(curves::entity(s, h)?.kind, EntityKind::LwPolyline(p) if !p.closed);
|
||||
if open {
|
||||
// A polyline that took on segments no longer goes back past the Join on Decurve.
|
||||
if pedit_join(s, h, &rest, fuzz, false)? > 0 {
|
||||
if pedit_join(s, h, &rest, fuzz)? > 0 {
|
||||
self.morig.remove(&h);
|
||||
}
|
||||
rest.retain(|o| s.doc().is_ok_and(|d| d.entity(*o).is_some()));
|
||||
|
||||
@@ -61,11 +61,8 @@ fn edit(sp: &Spline, opt: &str, p: &Value) -> Result<EntityKind> {
|
||||
spline(sp.refit(&fit, sp.closed))
|
||||
}
|
||||
"polyline" => {
|
||||
let precision = match p.get("precision") {
|
||||
None | Some(Value::Null) => 10,
|
||||
Some(v) => v.as_u64().filter(|n| *n <= 99).ok_or_else(|| bad("splinedit", "`precision` must be a whole number from 0 to 99"))?,
|
||||
};
|
||||
Ok(EntityKind::LwPolyline(spline_to_poly(sp, precision as usize)))
|
||||
let precision = p.get("precision").and_then(Value::as_u64).unwrap_or(10).min(99) as usize;
|
||||
Ok(EntityKind::LwPolyline(spline_to_poly(sp, precision)))
|
||||
}
|
||||
"move" => {
|
||||
let (i, to) = (index(p)?, point_req("splinedit", p, "to")?);
|
||||
@@ -99,9 +96,7 @@ fn spline_close(sp: &Spline) -> Spline {
|
||||
return sp.clone();
|
||||
}
|
||||
let mut out = if sp.fit.len() >= 2 {
|
||||
// The open ends' tangents don't carry over: the closed curve takes its own where it closes.
|
||||
let opts = cadcraft_geom::FitOptions { start_tangent: None, end_tangent: None, ..sp.fit_opts };
|
||||
Spline::fit_with_end_derivatives(&sp.fit, true, opts)
|
||||
sp.refit(&sp.fit, true)
|
||||
} else {
|
||||
let mut c = sp.control.clone();
|
||||
c.extend(sp.control.first().copied());
|
||||
@@ -240,11 +235,11 @@ fn tolerance(sp: &Spline, tol: f64) -> Result<Spline> {
|
||||
|
||||
// ---------------- control points ----------------
|
||||
|
||||
/// The number of distinct control points: control points that wrap round repeat their first
|
||||
/// `degree` at the end, and a clamped closed spline repeats its first at the end.
|
||||
/// The number of distinct control points: a periodic spline repeats its first `degree` at the
|
||||
/// end, and a clamped closed one repeats its first at the end.
|
||||
fn distinct(sp: &Spline) -> usize {
|
||||
let n = sp.control.len();
|
||||
if sp.wraps() {
|
||||
if sp.is_periodic() {
|
||||
n.saturating_sub(sp.degree)
|
||||
} else if sp.closed && n > 2 && sp.control.first().zip(sp.control.last()).is_some_and(|(a, b)| a.near(*b, 1e-12)) {
|
||||
n - 1
|
||||
@@ -316,7 +311,7 @@ fn delete_control(sp: &Spline, j: usize) -> Result<Spline> {
|
||||
}
|
||||
let mut s = without_fit(sp.clone());
|
||||
let w = |s: &Spline, i: usize| s.weights.get(i).copied().unwrap_or(1.0);
|
||||
if sp.wraps() {
|
||||
if sp.is_periodic() {
|
||||
if u <= p + 1 {
|
||||
return Err(other(format!("A closed spline of degree {p} needs more than {} control points.", p + 1)));
|
||||
}
|
||||
@@ -384,30 +379,22 @@ fn join(s: &mut Session, h: Handle, sp: &Spline, others: &[Handle]) -> Result<Ve
|
||||
}
|
||||
|
||||
/// A control point added by inserting a knot where the curve passes nearest `at`; the curve
|
||||
/// keeps its shape. Control points that wrap round are clamped at the seam first.
|
||||
/// keeps its shape. A periodic spline is clamped at its seam first.
|
||||
fn add_control(sp: &Spline, at: Vec2) -> Result<Spline> {
|
||||
let base = if sp.wraps() { sp.clamped().ok_or_else(|| other("Cannot add a control point to this spline."))? } else { sp.clone() };
|
||||
let base = if sp.is_periodic() { sp.clamped().ok_or_else(|| other("Cannot add a control point to this spline."))? } else { sp.clone() };
|
||||
let t = curves::spline_param_of(&base, at);
|
||||
let mut out = base.insert_knot(t).ok_or_else(|| other("Cannot add a control point to this spline."))?;
|
||||
out.closed = sp.closed;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The highest order Elevate order takes: degree 25 is the most `Spline::elevated` builds, and
|
||||
/// AutoCAD 2024's limit too.
|
||||
const MAX_ORDER: u64 = 26;
|
||||
|
||||
/// AutoCAD 2024's message for an order it refuses: from the spline's own order to 26 (measured at
|
||||
/// orders 4 and 5).
|
||||
fn order_range(sp: &Spline) -> crate::EngineError {
|
||||
other(format!("Requires an integer between {} and {MAX_ORDER}.", sp.degree as u64 + 1))
|
||||
}
|
||||
|
||||
/// The same curve at a higher order (degree + 1), with more control points.
|
||||
fn elevate(sp: &Spline, order: u64) -> Result<Spline> {
|
||||
// Degree 25 is the most `Spline::elevated` builds.
|
||||
let max = 26;
|
||||
let current = sp.degree as u64 + 1;
|
||||
if order < current || order > MAX_ORDER {
|
||||
return Err(order_range(sp));
|
||||
if order < current || order > max {
|
||||
return Err(other(format!("Requires an order between {current} and {max}.")));
|
||||
}
|
||||
if order == current {
|
||||
return Ok(sp.clone());
|
||||
@@ -598,22 +585,6 @@ impl SplineditM {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Elevate order's "Enter new order": a whole number as typed. AutoCAD 2024 takes +5 and 05
|
||||
/// and refuses 5.0, 5., 1e1, 4.5, 3, 27 and a point, all with the order range; Enter keeps
|
||||
/// the order (measured).
|
||||
fn input_order(&mut self, s: &mut Session, sp: &Spline, input: &Input) -> Result<()> {
|
||||
if *input != Input::Enter {
|
||||
let order = match input {
|
||||
Input::Text(t) => t.trim().parse::<u64>().ok(),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| order_range(sp))?;
|
||||
self.apply(s, json!({ "option": "elevate", "order": order }))?;
|
||||
}
|
||||
self.sub = Sub::Vertex;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Interactive for SplineditM {
|
||||
@@ -702,15 +673,11 @@ impl Interactive for SplineditM {
|
||||
}
|
||||
Sub::Join => self.input_join(s, h, &sp, &i)?,
|
||||
Sub::Precision => {
|
||||
// A whole number as typed: AutoCAD 2024 takes +5 and 05 and refuses 5.0, 5., 4.5,
|
||||
// 1e1, 8/2, 100, -1 and a point (measured).
|
||||
let precision = match &i {
|
||||
Input::Text(t) => t.trim().parse::<u64>().ok().filter(|n| *n <= 99),
|
||||
Input::Enter => Some(10),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| other("Requires an integer between 0 and 99."))?;
|
||||
self.apply(s, json!({ "option": "polyline", "precision": precision }))?;
|
||||
Input::Text(t) => number(t).filter(|n| (0.0..=99.0).contains(n)).ok_or_else(|| other("Requires an integer between 0 and 99."))?,
|
||||
_ => 10.0,
|
||||
};
|
||||
self.apply(s, json!({ "option": "polyline", "precision": precision.round() as u64 }))?;
|
||||
s.set_selection(Vec::new());
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
@@ -817,7 +784,14 @@ impl Interactive for SplineditM {
|
||||
None if enter => self.sub = Sub::Vertex,
|
||||
None => {}
|
||||
},
|
||||
Sub::VertexOrder => self.input_order(s, &sp, &i)?,
|
||||
Sub::VertexOrder => {
|
||||
if let Input::Text(t) = &i {
|
||||
let order =
|
||||
number(t).filter(|o| o.fract() == 0.0 && *o >= 1.0 && *o <= 1000.0).ok_or_else(|| other("Requires a whole number."))?;
|
||||
self.apply(s, json!({ "option": "elevate", "order": order as u64 }))?;
|
||||
}
|
||||
self.sub = Sub::Vertex;
|
||||
}
|
||||
Sub::VertexDelete => match point {
|
||||
Some(p) => {
|
||||
let u = distinct(&sp);
|
||||
|
||||
@@ -639,32 +639,6 @@ fn arraypath_json_and_command_line() {
|
||||
assert!(matches!(last(&s), EntityKind::Line(l) if near(l.a.xy(), -5.0, 20.0) && near(l.b.xy(), -6.0, 20.0)));
|
||||
assert!(s.execute("arraypath", &json!({"handles": [dot], "path": dot})).is_err());
|
||||
|
||||
// By spacing, AutoCAD 2024 fills a closed path with floor(length / spacing) items and an open
|
||||
// one with one more, at the end (measured on a 100 square and on the same square open).
|
||||
let square = [[0, 0], [100, 0], [100, 100], [0, 100]];
|
||||
let r400 = 400.0 / std::f64::consts::TAU;
|
||||
for (closed, spacing, items) in
|
||||
[(true, 100, 4), (true, 30, 13), (true, 200, 2), (true, 400, 1), (true, 399, 1), (false, 100, 4), (false, 30, 11), (false, 300, 2)]
|
||||
{
|
||||
let mut s = Session::new();
|
||||
let dot = h(&s.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap());
|
||||
let path = h(&s.execute("pline", &json!({"points": square, "closed": closed})).unwrap());
|
||||
let r = s.execute("arraypath", &json!({"handles": [dot], "path": path, "spacing": spacing})).unwrap();
|
||||
assert_eq!(r["handles"].as_array().map(Vec::len), Some(items - 1), "closed {closed}, spacing {spacing}");
|
||||
}
|
||||
// A circle 400 round: 4 items at 100, none on the first (AutoCAD 2024, measured).
|
||||
let mut s = Session::new();
|
||||
let dot = h(&s.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap());
|
||||
let path = h(&s.execute("circle", &json!({"center": [0, r400], "radius": r400})).unwrap());
|
||||
let r = s.execute("arraypath", &json!({"handles": [dot], "path": path, "spacing": 100})).unwrap();
|
||||
assert_eq!(r["handles"].as_array().map(Vec::len), Some(3));
|
||||
// Three sides of 0.35 add up to a hair under 3 × 0.35; the item at the end still fits.
|
||||
let mut s = Session::new();
|
||||
let dot = h(&s.execute("circle", &json!({"center": [0, 0], "radius": 0.01})).unwrap());
|
||||
let path = h(&s.execute("pline", &json!({"points": [[0, 0], [0.35, 0], [0.35, 0.35], [0, 0.35]]})).unwrap());
|
||||
let r = s.execute("arraypath", &json!({"handles": [dot], "path": path, "spacing": 0.35})).unwrap();
|
||||
assert_eq!(r["handles"].as_array().map(Vec::len), Some(3));
|
||||
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({"center": [0, 1], "radius": 0.25})).unwrap();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
@@ -675,40 +649,6 @@ fn arraypath_json_and_command_line() {
|
||||
assert_eq!(s.doc().unwrap().model.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arraypath_item_count_as_autocad_takes_it() {
|
||||
// AutoCAD 2024 at "Enter number of items along path": a whole number from 1 to 32767 in plain
|
||||
// decimals, 5. and 5.0 included; 4.5, 1e1, 8/2, 3', 0 and 32768 are refused.
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({"center": [0, 1], "radius": 0.25})).unwrap();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
s.cmdline("arraypath 0.25,1").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
s.cmdline("5,0").unwrap();
|
||||
let asked = s.prompt_text();
|
||||
// Measured, then texts that aren't plain whole numbers (not measured).
|
||||
for t in ["4.5", "1e1", "8/2", "3'", "0", "32768", "+", ".5", "5.0.0", "5.1"] {
|
||||
s.cmdline(t).unwrap();
|
||||
assert_eq!(s.log.last().map(String::as_str), Some("Requires an integer between 1 and 32767."), "{t}");
|
||||
assert_eq!(s.prompt_text(), asked, "{t}");
|
||||
}
|
||||
s.cmdline("3").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
// The ends of the range, without drawing 32,767 copies.
|
||||
assert_eq!((super::patharray::item_count("1"), super::patharray::item_count("32767")), (Some(1), Some(32_767)));
|
||||
for (typed, items) in [("5", 5), ("5.", 5), ("5.0", 5), ("5.00", 5), ("05.0", 5), ("+5.0", 5), ("05", 5), ("+4", 4), ("1", 1)] {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({"center": [0, 1], "radius": 0.25})).unwrap();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
for t in ["arraypath 0.25,1", "", "5,0", typed] {
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
assert!(s.running.is_none(), "{typed}: {}", s.prompt_text());
|
||||
// The path and the items (the original is the first).
|
||||
assert_eq!(s.doc().unwrap().model.len(), 1 + items, "{typed}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn textedit_json_and_command_line() {
|
||||
let mut s = Session::new();
|
||||
@@ -837,155 +777,3 @@ fn offset_elliptical_arc_follows_picked_side() {
|
||||
let outer = max_x(json!([20, 20]));
|
||||
assert!((outer - 11.0).abs() < 0.05, "outer side went inward: max x = {outer}");
|
||||
}
|
||||
|
||||
/// STRETCH against what AutoCAD 2024 stores for the same crossing window and displacement (5, 3)
|
||||
/// (black-box: synthetic objects in accoreconsole, read back with `entget`): the ends of an arc
|
||||
/// that are inside move and the arc keeps its height (bulge × chord / 2), as does a polyline arc
|
||||
/// segment; the centre alone moves nothing; a spline's control points inside move.
|
||||
#[test]
|
||||
fn stretch_arcs_bulges_and_splines_match_autocad() {
|
||||
enum Want {
|
||||
Arc([f64; 2], f64, f64, f64),
|
||||
Bulges(&'static [f64]),
|
||||
Control(&'static [[f64; 2]]),
|
||||
}
|
||||
// ((seed command, params), crossing window, what AutoCAD stores)
|
||||
let cases: Vec<((&str, Value), [[f64; 2]; 2], Want)> = vec![
|
||||
// SX-ARC-1END: one end of the arc inside.
|
||||
(
|
||||
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 0.0, "end": 90.0})),
|
||||
[[15.0, -5.0], [30.0, 5.0]],
|
||||
Want::Arc([3.17984478246544, -2.20611061402141], 22.43262716319083, 0.2342130724507349, 1.713026264953702),
|
||||
),
|
||||
// SX2-ARC-ENDPT: the other end inside.
|
||||
(
|
||||
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 0.0, "end": 90.0})),
|
||||
[[-5.0, 15.0], [5.0, 25.0]],
|
||||
Want::Arc([1.476584509301813, 4.310815984327269], 19.01841360081773, 6.054532724492258, 1.384456456611818),
|
||||
),
|
||||
// SX2-ARC-BIG-END: an arc over 180 degrees, its end inside.
|
||||
(
|
||||
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 30.0, "end": 300.0})),
|
||||
[[5.0, -25.0], [15.0, -12.0]],
|
||||
Want::Arc([1.341732093243006, -0.7463649967436295], 19.25631435504786, 0.5920576993601167, 5.500876277544912),
|
||||
),
|
||||
// SX2-ARC-CEN: only the centre inside: unchanged.
|
||||
(
|
||||
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 0.0, "end": 90.0})),
|
||||
[[-3.0, -3.0], [16.0, 16.0]],
|
||||
Want::Arc([0.0, 0.0], 20.0, 0.0, std::f64::consts::FRAC_PI_2),
|
||||
),
|
||||
// SX-ARC-ALL: the whole arc inside: moved.
|
||||
(
|
||||
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 0.0, "end": 90.0})),
|
||||
[[-5.0, -5.0], [30.0, 30.0]],
|
||||
Want::Arc([5.0, 3.0], 20.0, 0.0, std::f64::consts::FRAC_PI_2),
|
||||
),
|
||||
// A full-sweep arc (start = end) inside the window: moved whole, though its chord is zero.
|
||||
(
|
||||
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 45.0, "end": 45.0})),
|
||||
[[-25.0, -25.0], [25.0, 25.0]],
|
||||
Want::Arc([5.0, 3.0], 20.0, std::f64::consts::FRAC_PI_4, std::f64::consts::FRAC_PI_4),
|
||||
),
|
||||
// SX-PLA-V1: the vertex starting an arc segment.
|
||||
(
|
||||
(
|
||||
"pline",
|
||||
json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [30.0, 0.0], "bulge": 0.5}, {"p": [45.0, 20.0], "bulge": 0.0}, {"p": [60.0, 20.0], "bulge": 0.0}], "closed": false}),
|
||||
),
|
||||
[[25.0, -5.0], [35.0, 5.0]],
|
||||
Want::Bulges(&[0.0, 0.6337751582042422, 0.0, 0.0]),
|
||||
),
|
||||
// SX-PLA-V2: the vertex ending an arc segment.
|
||||
(
|
||||
(
|
||||
"pline",
|
||||
json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [30.0, 0.0], "bulge": 0.5}, {"p": [45.0, 20.0], "bulge": 0.0}, {"p": [60.0, 20.0], "bulge": 0.0}], "closed": false}),
|
||||
),
|
||||
[[40.0, 15.0], [50.0, 25.0]],
|
||||
Want::Bulges(&[0.0, 0.4101116968279916, 0.0, 0.0]),
|
||||
),
|
||||
// SX2-PLA-NEG: a negative bulge over 180 degrees.
|
||||
(
|
||||
(
|
||||
"pline",
|
||||
json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [30.0, 0.0], "bulge": -1.5}, {"p": [45.0, 20.0], "bulge": 0.0}, {"p": [60.0, 20.0], "bulge": 0.0}], "closed": false}),
|
||||
),
|
||||
[[40.0, 15.0], [50.0, 25.0]],
|
||||
Want::Bulges(&[0.0, -1.230335090483974, 0.0, 0.0]),
|
||||
),
|
||||
// SX3-SPL-CV-ONLY: a window holding a control point but missing the drawn curve selects
|
||||
// nothing in AutoCAD ("0 found"), so the spline stays as it was.
|
||||
(
|
||||
("spline", json!({"control": [[0.0, 0.0], [10.0, 100.0], [20.0, 100.0], [30.0, 0.0]], "degree": 3})),
|
||||
[[5.0, 95.0], [15.0, 105.0]],
|
||||
Want::Control(&[[0.0, 0.0], [10.0, 100.0], [20.0, 100.0], [30.0, 0.0]]),
|
||||
),
|
||||
// SX3-SPL-CV-CROSS: the same control point in a window that also crosses the curve moves.
|
||||
(
|
||||
("spline", json!({"control": [[0.0, 0.0], [10.0, 100.0], [20.0, 100.0], [30.0, 0.0]], "degree": 3})),
|
||||
[[5.0, 40.0], [15.0, 105.0]],
|
||||
Want::Control(&[[0.0, 0.0], [15.0, 103.0], [20.0, 100.0], [30.0, 0.0]]),
|
||||
),
|
||||
// SX-SPL: two control points inside.
|
||||
(
|
||||
("spline", json!({"control": [[0.0, 0.0], [10.0, 10.0], [20.0, 0.0], [30.0, 10.0]], "degree": 3})),
|
||||
[[15.0, -5.0], [35.0, 15.0]],
|
||||
Want::Control(&[[0.0, 0.0], [10.0, 10.0], [25.0, 3.0], [35.0, 13.0]]),
|
||||
),
|
||||
];
|
||||
let same = |a: f64, b: f64| (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0);
|
||||
let same_angle = |a: f64, b: f64| {
|
||||
let d = (a - b).rem_euclid(std::f64::consts::TAU);
|
||||
d < 1e-9 || std::f64::consts::TAU - d < 1e-9
|
||||
};
|
||||
for ((seed, params), window, want) in cases {
|
||||
let mut s = Session::new();
|
||||
let hd = h(&s.execute(seed, ¶ms).unwrap());
|
||||
s.execute("stretch", &json!({"window": window, "delta": [5.0, 3.0]})).unwrap();
|
||||
match (kind(&s, &hd), want) {
|
||||
(EntityKind::Arc(a), Want::Arc(c, r, start, end)) => assert!(
|
||||
same(a.center.x, c[0]) && same(a.center.y, c[1]) && same(a.radius, r) && same_angle(a.start, start) && same_angle(a.end, end),
|
||||
"{window:?}: {a:?}"
|
||||
),
|
||||
(EntityKind::LwPolyline(p), Want::Bulges(want)) => {
|
||||
let got: Vec<f64> = p.vertices.iter().map(|v| v.bulge).collect();
|
||||
assert!(got.len() == want.len() && got.iter().zip(want).all(|(a, b)| same(*a, *b)), "{window:?}: {got:?} / {want:?}");
|
||||
}
|
||||
(EntityKind::Spline(sp), Want::Control(want)) => {
|
||||
let ok = sp.control.len() == want.len() && sp.control.iter().zip(want).all(|(p, w)| same(p.x, w[0]) && same(p.y, w[1]));
|
||||
assert!(ok, "{window:?}: {:?} / {want:?}", sp.control);
|
||||
}
|
||||
(k, _) => panic!("{window:?}: {k:?}"),
|
||||
}
|
||||
}
|
||||
// A spline built from fit points: the fit points inside move and it is fitted through them
|
||||
// again, keeping its fit data; all of them inside, it moves whole (AutoCAD 2024, `entget`
|
||||
// after STRETCH of a spline stored with these fit points only).
|
||||
let fit = [[200.0, 0.0], [210.0, 10.0], [220.0, 0.0], [230.0, 10.0]];
|
||||
let fit_cases: [([[f64; 2]; 2], [f64; 2], [[f64; 2]; 4]); 3] = [
|
||||
([[225.0, 5.0], [235.0, 15.0]], [5.0, 0.0], [[200.0, 0.0], [210.0, 10.0], [220.0, 0.0], [235.0, 10.0]]),
|
||||
([[205.0, 5.0], [215.0, 15.0]], [0.0, 5.0], [[200.0, 0.0], [210.0, 15.0], [220.0, 0.0], [230.0, 10.0]]),
|
||||
([[195.0, -5.0], [235.0, 15.0]], [5.0, 5.0], [[205.0, 5.0], [215.0, 15.0], [225.0, 5.0], [235.0, 15.0]]),
|
||||
];
|
||||
for (window, delta, want) in fit_cases {
|
||||
let mut s = Session::new();
|
||||
let hd = h(&s.execute("spline", &json!({ "fit": fit })).unwrap());
|
||||
s.execute("stretch", &json!({ "window": window, "delta": delta })).unwrap();
|
||||
let EntityKind::Spline(sp) = kind(&s, &hd) else { panic!("not a spline") };
|
||||
let got: Vec<[f64; 2]> = sp.fit.iter().map(|p| [p.x, p.y]).collect();
|
||||
assert!(got.len() == 4 && got.iter().zip(want).all(|(g, w)| same(g[0], w[0]) && same(g[1], w[1])), "{window:?}: {got:?}");
|
||||
// The curve still runs through them.
|
||||
let (lo, hi) = sp.domain();
|
||||
for w in want {
|
||||
let q = cadcraft_geom::Vec2::new(w[0], w[1]);
|
||||
let near = (0..=4000).map(|i| sp.eval(lo + (hi - lo) * f64::from(i) / 4000.0).dist(q)).fold(f64::INFINITY, f64::min);
|
||||
assert!(near < 1e-2, "{window:?}: {w:?} is {near} off the curve");
|
||||
}
|
||||
}
|
||||
// A stretch that brings an arc segment's ends together leaves no arc to keep: the bulge goes.
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([{"p": [0, 0], "bulge": 0.5}, [10, 0], [20, 0]]), false);
|
||||
s.execute("stretch", &json!({"window": [[9, -1], [11, 1]], "delta": [-10, 0]})).unwrap();
|
||||
assert_eq!(poly(&kind(&s, &p)).vertices.iter().map(|v| v.bulge).collect::<Vec<_>>(), [0.0, 0.0, 0.0]);
|
||||
}
|
||||
|
||||
@@ -50,7 +50,6 @@ pub const PROFILE_VARS: &[&str] = &[
|
||||
"CURSORSIZE",
|
||||
"PICKFIRST",
|
||||
"PICKADD",
|
||||
"COPYMODE",
|
||||
"PICKDRAG",
|
||||
"MAXARRAY",
|
||||
"MEASUREINIT",
|
||||
@@ -86,31 +85,18 @@ pub fn profile(s: &Session) -> Value {
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
/// The profile variables the drawing keeps in its header rather than in the session's settings.
|
||||
const DRAWING_VARS: &[&str] = &["SNAPUNIT", "GRIDUNIT"];
|
||||
|
||||
/// Set the profile variables named in `values` (an object; other keys are refused). All or
|
||||
/// nothing: one bad name or value leaves every setting, and the drawing, as they were.
|
||||
/// nothing: one bad name or value leaves every setting as it was.
|
||||
pub fn apply(s: &mut Session, values: &Value) -> Result<()> {
|
||||
let Some(obj) = values.as_object() else { return Err(bad("options", "expected an object of profile variables")) };
|
||||
let before = s.settings.clone();
|
||||
// When one of the values is a drawing variable, the drawing as it is: put back whole on a
|
||||
// refusal, it is the same drawing again, so not marked as changed either.
|
||||
let touches_drawing = obj.keys().any(|k| DRAWING_VARS.iter().any(|v| v.eq_ignore_ascii_case(k.trim())));
|
||||
let drawing = if touches_drawing { s.state().ok().map(|st| st.doc.clone()) } else { None };
|
||||
let put_back = |s: &mut Session| {
|
||||
s.settings = before.clone();
|
||||
if let (Some(doc), Ok(st)) = (&drawing, s.state_mut()) {
|
||||
st.doc = doc.clone();
|
||||
}
|
||||
};
|
||||
for (name, v) in obj {
|
||||
if !is_profile_var(name) {
|
||||
put_back(s);
|
||||
s.settings = before;
|
||||
return Err(bad("options", format!("{name} is not a profile setting")));
|
||||
}
|
||||
if let Err(e) = crate::sysvars::set(s, name, v) {
|
||||
put_back(s);
|
||||
s.settings = before;
|
||||
return Err(bad("options", format!("invalid value for {}: {e}", name.to_ascii_uppercase())));
|
||||
}
|
||||
}
|
||||
@@ -131,8 +117,7 @@ pub fn restore(s: &mut Session, saved: &Value) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Put every profile variable back to its default, except [`DRAWING_VARS`]: a reset doesn't change
|
||||
/// the drawing.
|
||||
/// Put every profile variable back to its default.
|
||||
pub fn reset(s: &mut Session) {
|
||||
let d = Settings::default();
|
||||
let st = &mut s.settings;
|
||||
@@ -158,24 +143,8 @@ pub fn reset(s: &mut Session) {
|
||||
st.cursorsize = d.cursorsize;
|
||||
st.pickfirst = d.pickfirst;
|
||||
st.pickadd = d.pickadd;
|
||||
st.copymode = d.copymode;
|
||||
st.pickdrag = d.pickdrag;
|
||||
st.maxarray = d.maxarray;
|
||||
st.dynprompt = d.dynprompt;
|
||||
st.dyndigrip = d.dyndigrip;
|
||||
st.dyndivis = d.dyndivis;
|
||||
st.selectioneffect = d.selectioneffect;
|
||||
st.selectionpreview = d.selectionpreview;
|
||||
st.previeweffect = d.previeweffect;
|
||||
st.previewfilter = d.previewfilter;
|
||||
st.grips = d.grips;
|
||||
st.gripobjlimit = d.gripobjlimit;
|
||||
st.selectionarea = d.selectionarea;
|
||||
st.windowareacolor = d.windowareacolor;
|
||||
st.crossingareacolor = d.crossingareacolor;
|
||||
st.selectionareaopacity = d.selectionareaopacity;
|
||||
st.pickstyle = d.pickstyle;
|
||||
st.measureinit = d.measureinit;
|
||||
}
|
||||
|
||||
fn run_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -222,56 +191,4 @@ mod tests {
|
||||
restore(&mut b, &saved);
|
||||
assert_eq!(profile(&b), saved);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_change_leaves_the_drawings_snap_and_grid_too() {
|
||||
let mut s = Session::new();
|
||||
let before = profile(&s);
|
||||
let refused = [
|
||||
json!({ "SNAPUNIT": [2, 3], "GRIDUNIT": [4, 5], "WINDOWAREACOLOR": 0 }),
|
||||
json!({ "GRIDUNIT": [4, 5], "LUNITS": 2 }),
|
||||
json!({ "WINDOWAREACOLOR": 0 }),
|
||||
];
|
||||
for bad_one in refused {
|
||||
assert!(apply(&mut s, &bad_one).is_err(), "{bad_one}");
|
||||
assert_eq!(profile(&s), before, "{bad_one}");
|
||||
// The same drawing, so there is nothing new to save.
|
||||
assert!(!s.state().unwrap().is_dirty(), "{bad_one}");
|
||||
}
|
||||
assert!(s.execute("options", &json!({ "reset": true, "SNAPUNIT": [2, 3], "WINDOWAREACOLOR": 0 })).is_err());
|
||||
assert_eq!(profile(&s), before);
|
||||
// The header entries come back exactly: a zero grid spacing (which reads as the snap
|
||||
// spacing), and a snap spacing the drawing doesn't have. The refused value comes last, so
|
||||
// both are written first (the keys are taken in name order).
|
||||
let header = |s: &Session, n: &str| s.doc().unwrap().header.get(n).cloned();
|
||||
s.doc_mut().unwrap().header.set("GRIDUNIT", cadcraft_doc::HVal::Point(cadcraft_geom::Vec3::new(0.0, 0.0, 0.0)));
|
||||
s.doc_mut().unwrap().header.vars.remove("SNAPUNIT");
|
||||
let (grid, snap) = (header(&s, "GRIDUNIT"), header(&s, "SNAPUNIT"));
|
||||
assert!(apply(&mut s, &json!({ "GRIDUNIT": [4, 5], "SNAPUNIT": [2, 3], "WINDOWAREACOLOR": 0 })).is_err());
|
||||
assert_eq!((header(&s, "GRIDUNIT"), header(&s, "SNAPUNIT")), (grid, snap));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_puts_every_profile_var_back_except_the_drawings() {
|
||||
let defaults = profile(&Session::new());
|
||||
let mut s = Session::new();
|
||||
for name in PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)) {
|
||||
// A value the variable takes that isn't its default: 0 and 1 swapped, or a number one
|
||||
// more or less, or an angle.
|
||||
let was = &defaults[*name];
|
||||
let n = was.as_f64().unwrap_or(0.0);
|
||||
let tries = [json!(if n == 0.0 { 1 } else { 0 }), json!(n + 1.0), json!(n - 1.0), json!("15")];
|
||||
let changed = tries.iter().any(|v| apply(&mut s, &json!({ *name: v })).is_ok() && profile(&s)[*name] != *was);
|
||||
assert!(changed, "no other value found for {name} (default {was})");
|
||||
}
|
||||
assert!(PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)).all(|n| profile(&s)[*n] != defaults[*n]));
|
||||
apply(&mut s, &json!({ "SNAPUNIT": [2, 3], "GRIDUNIT": [4, 5] })).unwrap();
|
||||
reset(&mut s);
|
||||
let after = profile(&s);
|
||||
for name in PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)) {
|
||||
assert_eq!(after[*name], defaults[*name], "{name}");
|
||||
}
|
||||
// The snap and grid spacing are the drawing's, and stay.
|
||||
assert_eq!((after["SNAPUNIT"].clone(), after["GRIDUNIT"].clone()), (json!([2.0, 3.0]), json!([4.0, 5.0])));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,25 +215,11 @@ fn device_paper<'a>(dev: &'a PlotterConfig, name: &str) -> Option<&'a DevicePape
|
||||
dev.paper(name).or_else(|| dev.paper(cadcraft_render::paper_size(name)?.name))
|
||||
}
|
||||
|
||||
/// A paper's stored portrait margins on the landscape sheet: the sheet's axes swap, so left and
|
||||
/// right become bottom and top (#1266).
|
||||
pub(crate) fn landscape_margins([l, b, r, t]: [f64; 4]) -> [f64; 4] {
|
||||
[t, l, b, r]
|
||||
}
|
||||
|
||||
/// The inverse: a landscape page's margins on the stored portrait sheet, for a page that keeps
|
||||
/// its paper when its orientation turns (#1266).
|
||||
pub(crate) fn portrait_margins([l, b, r, t]: [f64; 4]) -> [f64; 4] {
|
||||
[b, r, t, l]
|
||||
}
|
||||
|
||||
fn set_paper(page: &mut PageSetup, p: &DevicePaper) {
|
||||
page.paper = p.name.clone();
|
||||
page.width_mm = p.width;
|
||||
page.height_mm = p.height;
|
||||
// The paper keeps its margins for its stored portrait sheet; the page measures them against
|
||||
// the sheet in the orientation it names, so they turn with it (#1266).
|
||||
page.margins_mm = if page.landscape { landscape_margins(p.margins) } else { p.margins };
|
||||
page.margins_mm = p.margins;
|
||||
}
|
||||
|
||||
fn unknown_device(cmd: &str, name: &str) -> EngineError {
|
||||
@@ -368,16 +354,9 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
o.remove("paper");
|
||||
o.insert("width".into(), json!(pp.width));
|
||||
o.insert("height".into(), json!(pp.height));
|
||||
// The paper's margins belong to its stored portrait sheet; the plot draws on the sheet in
|
||||
// the orientation it names, so they turn to it (#1266).
|
||||
let landscape = p.get("landscape").and_then(Value::as_bool).unwrap_or_else(|| match &layout {
|
||||
Some(pg) => pg.landscape,
|
||||
None => dev.orientation == Orientation::Landscape,
|
||||
});
|
||||
let [l, b, r, t] = pp.margins;
|
||||
o.insert("margins".into(), json!(if landscape { [t, l, b, r] } else { [l, b, r, t] }));
|
||||
o.insert("margins".into(), json!(pp.margins));
|
||||
if p.get("landscape").is_none() && layout.is_none() {
|
||||
o.insert("landscape".into(), json!(landscape));
|
||||
o.insert("landscape".into(), json!(dev.orientation == Orientation::Landscape));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
@@ -548,22 +527,13 @@ fn edit_device(cmd: &str, c: &mut PlotterConfig, p: &Value) -> Result<()> {
|
||||
_ => return Err(bad(cmd, "`paper.width` and `paper.height` (mm) are both required")),
|
||||
};
|
||||
let margins = match pv.get("margins") {
|
||||
None => match existing.as_ref() {
|
||||
// Stored margins belong to the stored portrait sheet; naming the same sheet
|
||||
// landscape turns them back, so re-saving a paper does not refuse its own
|
||||
// margins.
|
||||
// Naming the sheet landscape turns the stored portrait margins to it, whatever
|
||||
// its new sides: sanitization turns them back for the stored (portrait) sheet.
|
||||
Some(e) if w > h => {
|
||||
let [l, b, r, t] = e.margins;
|
||||
[t, l, b, r]
|
||||
}
|
||||
_ => existing.as_ref().map(|e| e.margins).unwrap_or([0.0; 4]),
|
||||
},
|
||||
None => existing.as_ref().map(|e| e.margins).unwrap_or([0.0; 4]),
|
||||
Some(m) => {
|
||||
let a: Vec<f64> = m.as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
|
||||
match a[..] {
|
||||
[l, b, r, t] if a.iter().all(|v| v.is_finite() && (0.0..=1000.0).contains(v)) && l + r < w && b + t < h => [l, b, r, t],
|
||||
[l, b, r, t] if a.iter().all(|v| v.is_finite() && (0.0..=1000.0).contains(v)) && l + r < w.min(h) && b + t < w.max(h) => {
|
||||
[l, b, r, t]
|
||||
}
|
||||
_ => return Err(bad(cmd, "`paper.margins` must be [left, bottom, right, top] in mm, leaving a printable area")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -449,7 +449,7 @@ fn run_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = s.doc_mut()?;
|
||||
// As it was (none for a new style), so dimensions are redrawn only when it changes.
|
||||
let before = d.text_style(&name).cloned();
|
||||
let idx = match d.text_styles.position_by_name(&name) {
|
||||
let idx = match d.text_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&name)) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
d.text_styles.push(cadcraft_doc::TextStyle { name: name.clone(), ..Default::default() });
|
||||
@@ -554,9 +554,8 @@ fn run_style_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if d.text_style(&to).is_some() && !to.eq_ignore_ascii_case(&from) {
|
||||
return Err(bad("style.rename", format!("a text style `{to}` already exists")));
|
||||
}
|
||||
let st = d.text_styles.by_name_mut(&from).ok_or_else(|| bad("style.rename", "no such style"))?;
|
||||
let st = d.text_styles.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("style.rename", "no such style"))?;
|
||||
st.name = to.clone();
|
||||
cadcraft_doc::foreign::Foreign::rename_shared(&mut d.foreign, &["STYLE"], &from, &to);
|
||||
// References follow the new name.
|
||||
let fix = |n: &mut String| {
|
||||
if n.eq_ignore_ascii_case(&from) {
|
||||
@@ -643,7 +642,7 @@ fn run_dimstyle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// As it was (none for a new style), so dimensions are redrawn only when it changes.
|
||||
let before = d.dim_style(&name).cloned();
|
||||
let base = d.dim_style(&d.header.str("DIMSTYLE", "Standard")).cloned().unwrap_or_default();
|
||||
let idx = match d.dim_styles.position_by_name(&name) {
|
||||
let idx = match d.dim_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&name)) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
d.dim_styles.push(cadcraft_doc::DimStyle { name: name.clone(), ..base });
|
||||
@@ -793,9 +792,8 @@ fn run_dimstyle_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if d.dim_style(&to).is_some() && !to.eq_ignore_ascii_case(&from) {
|
||||
return Err(bad("dimstyle.rename", format!("a dimension style `{to}` already exists")));
|
||||
}
|
||||
let st = d.dim_styles.by_name_mut(&from).ok_or_else(|| bad("dimstyle.rename", "no such dimension style"))?;
|
||||
let st = d.dim_styles.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("dimstyle.rename", "no such dimension style"))?;
|
||||
st.name = to.clone();
|
||||
cadcraft_doc::foreign::Foreign::rename_shared(&mut d.foreign, &["DIMSTYLE"], &from, &to);
|
||||
if d.header.str("DIMSTYLE", "Standard").eq_ignore_ascii_case(&from) {
|
||||
d.header.set_str("DIMSTYLE", &to);
|
||||
}
|
||||
@@ -1017,9 +1015,8 @@ fn run_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if d.linetype(&to).is_some() && !to.eq_ignore_ascii_case(&from) {
|
||||
return Err(bad("rename", format!("a linetype `{to}` already exists")));
|
||||
}
|
||||
let st = d.linetypes.by_name_mut(&from).ok_or_else(|| bad("rename", "no such linetype"))?;
|
||||
let st = d.linetypes.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("rename", "no such linetype"))?;
|
||||
st.name = to.clone();
|
||||
cadcraft_doc::foreign::Foreign::rename_shared(&mut d.foreign, &["LTYPE"], &from, &to);
|
||||
// References follow the new name.
|
||||
let fix = |n: &mut String| {
|
||||
if n.eq_ignore_ascii_case(&from) {
|
||||
|
||||
@@ -59,7 +59,7 @@ fn put(d: &mut Drawing, lt: Linetype, reload: bool, out: &mut Loaded) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
match d.linetypes.by_name_mut(<.name) {
|
||||
match d.linetypes.iter_mut().find(|l| l.name.eq_ignore_ascii_case(<.name)) {
|
||||
Some(old) if reload => {
|
||||
out.reloaded.push(old.name.clone());
|
||||
// The drawing keeps the name as it had it (objects refer to it).
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::foreign::Foreign;
|
||||
use cadcraft_doc::{Drawing, EntityKind, EntityStore, Handle};
|
||||
use serde_json::json;
|
||||
|
||||
@@ -55,7 +54,6 @@ pub(super) fn block(s: &mut Session, from: &str, to: &str) -> Result<()> {
|
||||
let mut b = d.blocks.remove(&key).ok_or_else(|| bad("rename", "no such block"))?;
|
||||
Arc::make_mut(&mut b).name = to.clone();
|
||||
d.blocks.insert(to.clone(), b);
|
||||
Foreign::rename_shared(&mut d.foreign, &["BLOCK_RECORD", "BLOCK", "ENDBLK"], &key, &to);
|
||||
let uses = |k: &EntityKind| match k {
|
||||
EntityKind::Insert(i) => i.block.eq_ignore_ascii_case(&key),
|
||||
EntityKind::MLeader(m) => m.block.as_ref().is_some_and(|b| b.block.eq_ignore_ascii_case(&key)),
|
||||
@@ -104,13 +102,6 @@ pub(super) fn simple(s: &mut Session, table: &str, from: &str, to: &str) -> Resu
|
||||
}
|
||||
let n = names.iter_mut().find(|n| n.eq_ignore_ascii_case(from)).ok_or_else(|| bad("rename", format!("no {table} `{from}`")))?;
|
||||
let old = std::mem::replace(&mut **n, to.clone());
|
||||
let kind = match table {
|
||||
"mleaderstyle" => "NOD/ACAD_MLEADERSTYLE",
|
||||
"tablestyle" => "NOD/ACAD_TABLESTYLE",
|
||||
"view" => "VIEW",
|
||||
_ => "UCS",
|
||||
};
|
||||
Foreign::rename_shared(&mut d.foreign, &[kind], &old, &to);
|
||||
let current = match table {
|
||||
"mleaderstyle" => "CMLEADERSTYLE",
|
||||
"tablestyle" => "CTABLESTYLE",
|
||||
|
||||
@@ -8,13 +8,11 @@ use super::cells::cell_of;
|
||||
use super::{MAX_COLS, MAX_ROWS, anchors, edit, set_anchors, usize_param};
|
||||
use crate::cmd::machines::SelectRun;
|
||||
use crate::cmd::{CommandSpec, bad, bool_or, str_param};
|
||||
use crate::{Accept, DocState, Input, Interactive, Prompt, Result, Session, Step};
|
||||
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
|
||||
|
||||
/// Largest linked file read (bytes).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_LINK_BYTES: usize = 8 << 20;
|
||||
/// Most files remembered per drawing as linked by the user ([`DocState::chosen_links`]).
|
||||
const MAX_CHOSEN_LINKS: usize = 1000;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -28,10 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.menu(&["Insert", "Data Link..."])
|
||||
.params("{handle, path (.csv, .txt/.tsv tab-separated), startRow? (default: below the title), remove?: bool} → {rows, cols}"),
|
||||
CommandSpec::new("datalinkupdate", "Update Data Links", run_update)
|
||||
.params(
|
||||
"{handles?} (default: every linked table) → {updated, errors}; a link saved in the drawing is read only from the drawing's \
|
||||
folder or below it, unless DATALINK linked that file since the drawing was opened",
|
||||
)
|
||||
.params("{handles?} (default: every linked table) → {updated}")
|
||||
.interactive(|_| Ok(Box::new(SelectRun::new("datalinkupdate", "DATALINKUPDATE")))),
|
||||
]
|
||||
}
|
||||
@@ -229,45 +224,13 @@ fn separator(path: &str, text: &str) -> char {
|
||||
if first.contains(';') && !first.contains(',') { ';' } else { ',' }
|
||||
}
|
||||
|
||||
/// The file to read for a data link of the drawing `st`: a path the user just `chosen` as given;
|
||||
/// a path stored in the drawing through [`crate::doc_path::resolve`], and then only as the file
|
||||
/// system finds it (`..` and links followed) in the drawing's `folder`
|
||||
/// ([`crate::doc_path::drawing_folder`]) or below it, or when the user linked that same file since
|
||||
/// the drawing was opened ([`DocState::chosen_links`]).
|
||||
fn link_file(id: &str, path: &str, st: &DocState, folder: Option<&std::path::Path>, chosen: bool) -> Result<std::path::PathBuf> {
|
||||
/// The file to read for a data link: a path the user just `chosen` as given, a path stored in the
|
||||
/// drawing at `host` only through [`crate::doc_path::resolve`].
|
||||
fn link_file(id: &str, path: &str, host: Option<&str>, chosen: bool) -> Result<std::path::PathBuf> {
|
||||
if chosen {
|
||||
return Ok(std::path::PathBuf::from(path));
|
||||
}
|
||||
let host = st.path.as_deref().map(std::path::Path::new);
|
||||
let file = crate::doc_path::resolve(path, host).map_err(|r| bad(id, format!("{path}: not opened, {r}")))?;
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
// Nothing is read there; [`read_link`] says so.
|
||||
return Ok(file);
|
||||
}
|
||||
// The automation roots first: outside them nothing about the file is asked.
|
||||
crate::file_access::check_read(&file).map_err(|e| bad(id, e))?;
|
||||
let real = std::fs::canonicalize(&file).map_err(|e| bad(id, format!("{path}: {e}")))?;
|
||||
// Whole components: `plans-old` is not in `plans`.
|
||||
if folder.is_some_and(|f| real.starts_with(f)) || st.chosen_links.contains_key(&real) {
|
||||
// Read where it was checked, not through the links again.
|
||||
return Ok(real);
|
||||
}
|
||||
Err(bad(id, format!("{path}: not read, the file is outside the drawing's folder; link it with DATALINK to read it")))
|
||||
}
|
||||
|
||||
/// Remember `real` (resolved), the file of a link the user just gave, as theirs to read for the
|
||||
/// drawing `st`, as its latest choice. At [`MAX_CHOSEN_LINKS`] files a new one makes room by
|
||||
/// dropping the file chosen longest ago.
|
||||
fn remember_link(st: &mut DocState, real: std::path::PathBuf) {
|
||||
let links = &mut st.chosen_links;
|
||||
let latest = links.values().max().map_or(0, |n| n.saturating_add(1));
|
||||
if links.len() >= MAX_CHOSEN_LINKS
|
||||
&& !links.contains_key(&real)
|
||||
&& let Some(oldest) = links.iter().min_by_key(|(_, n)| **n).map(|(p, _)| p.clone())
|
||||
{
|
||||
links.remove(&oldest);
|
||||
}
|
||||
links.insert(real, latest);
|
||||
crate::doc_path::resolve(path, host.map(std::path::Path::new)).map_err(|r| bad(id, format!("{path}: not opened, {r}")))
|
||||
}
|
||||
|
||||
/// Read a linked file through the host (natively the file system; not on the web).
|
||||
@@ -325,20 +288,16 @@ fn fill(t: &mut Table, start: usize, data: &[Vec<String>]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-read the linked file of table `h`; `chosen` says its path was just given by the user, else
|
||||
/// it is read from the drawing's `folder` ([`crate::doc_path::drawing_folder`]) or a file the user
|
||||
/// linked.
|
||||
fn update(s: &mut Session, h: Handle, folder: Option<&std::path::Path>, chosen: bool) -> Result<(usize, usize)> {
|
||||
/// Re-read the linked file of table `h`; `chosen` says its path was just given by the user.
|
||||
fn update(s: &mut Session, h: Handle, chosen: bool) -> Result<(usize, usize)> {
|
||||
let id = "datalinkupdate";
|
||||
let link = match s.doc()?.entity(h).map(|e| &e.kind) {
|
||||
Some(EntityKind::Table(t)) => t.data_link.clone().ok_or_else(|| bad(id, "the table has no data link"))?,
|
||||
_ => return Err(bad(id, "object is not a table")),
|
||||
};
|
||||
let file = link_file(id, &link.path, s.state()?, folder, chosen)?;
|
||||
let host = s.state()?.path.clone();
|
||||
let file = link_file(id, &link.path, host.as_deref(), chosen)?;
|
||||
let text = read_link(id, &file)?;
|
||||
if chosen && let Ok(real) = std::fs::canonicalize(&file) {
|
||||
remember_link(s.state_mut()?, real);
|
||||
}
|
||||
let data = parse_csv(&text, separator(&link.path, &text));
|
||||
let mut size = (0, 0);
|
||||
edit(s, &json!({ "handle": h.hex() }), id, |t| {
|
||||
@@ -366,7 +325,7 @@ fn run_datalink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(())
|
||||
})?;
|
||||
let h = r.get("handle").and_then(Value::as_str).and_then(Handle::parse_hex).ok_or_else(|| bad(id, "no table"))?;
|
||||
let (rows, cols) = update(s, h, None, true)?;
|
||||
let (rows, cols) = update(s, h, true)?;
|
||||
Ok(json!({ "handle": h.hex(), "rows": rows, "cols": cols }))
|
||||
}
|
||||
|
||||
@@ -392,10 +351,8 @@ fn run_update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let mut updated = 0;
|
||||
let mut errors = Vec::new();
|
||||
// Resolved once for every table, and only when there is one.
|
||||
let folder = if hs.is_empty() { None } else { crate::doc_path::drawing_folder(s.state()?.path.as_deref().map(std::path::Path::new)) };
|
||||
for h in hs {
|
||||
match update(s, h, folder.as_deref(), false) {
|
||||
match update(s, h, false) {
|
||||
Ok(_) => updated += 1,
|
||||
Err(e) => errors.push(e.to_string()),
|
||||
}
|
||||
@@ -422,38 +379,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the drawing `st` remembers `file` as linked by the user.
|
||||
fn remembered(st: &DocState, file: &std::path::Path) -> bool {
|
||||
st.chosen_links.contains_key(file)
|
||||
}
|
||||
|
||||
/// However many files the user links, the drawing remembers at most [`MAX_CHOSEN_LINKS`] of
|
||||
/// them: the ones linked last, a file linked again counting as just linked.
|
||||
#[test]
|
||||
fn remembered_links_are_the_most_recent_ones() {
|
||||
let mut st = DocState::new(cadcraft_doc::Drawing::new_metric(), "t", None);
|
||||
let file = |i: usize| std::path::PathBuf::from(format!("/data/{i}.csv"));
|
||||
for i in 0..MAX_CHOSEN_LINKS {
|
||||
remember_link(&mut st, file(i));
|
||||
}
|
||||
// Linked again at the bound, the second file drops nothing and becomes the newest, so two
|
||||
// new files make room by dropping the first and the third.
|
||||
remember_link(&mut st, file(1));
|
||||
assert_eq!(st.chosen_links.len(), MAX_CHOSEN_LINKS);
|
||||
assert!(remembered(&st, &file(0)));
|
||||
remember_link(&mut st, file(MAX_CHOSEN_LINKS));
|
||||
remember_link(&mut st, file(MAX_CHOSEN_LINKS + 1));
|
||||
assert!([1, MAX_CHOSEN_LINKS, MAX_CHOSEN_LINKS + 1].iter().all(|&i| remembered(&st, &file(i))));
|
||||
assert!(!remembered(&st, &file(0)) && !remembered(&st, &file(2)));
|
||||
// After many more, the ones linked last are the ones remembered.
|
||||
let end = 2 * MAX_CHOSEN_LINKS + 10;
|
||||
for i in MAX_CHOSEN_LINKS + 2..end {
|
||||
remember_link(&mut st, file(i));
|
||||
}
|
||||
assert_eq!(st.chosen_links.len(), MAX_CHOSEN_LINKS, "the bound is reached, not a smaller one");
|
||||
assert!((end - MAX_CHOSEN_LINKS..end).all(|i| remembered(&st, &file(i))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_parsing() {
|
||||
assert_eq!(parse_csv("a,b\r\n\"c,d\",\"e\"\"f\"\n", ','), vec![vec!["a", "b"], vec!["c,d", "e\"f"]]);
|
||||
|
||||
@@ -258,7 +258,7 @@ fn run_cellstyle_use(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(v) => v.as_str().map(|x| x.trim().to_string()).ok_or_else(|| bad(id, "`style` must be a cell style name"))?,
|
||||
None => return Err(bad(id, "`style` (cell style name) is required")),
|
||||
};
|
||||
let styles: Vec<TableStyle> = s.doc()?.table_styles.to_vec();
|
||||
let styles: Vec<TableStyle> = s.doc()?.table_styles.clone();
|
||||
edit(s, p, id, |t| {
|
||||
let st = styles.iter().find(|x| x.name.eq_ignore_ascii_case(&t.style)).cloned().unwrap_or_default();
|
||||
if !name.is_empty() && !st.has_cell_style(&name) {
|
||||
|
||||
@@ -5,12 +5,6 @@
|
||||
//! itself is on, are opened (see `craft_docpath`). A refused path is handled like a missing file,
|
||||
//! with the reason in its status. Paths the user gives a command (XATTACH, -XREF Path, DATALINK)
|
||||
//! are their own choice and are used as given.
|
||||
//!
|
||||
//! A data link copies its file's text into the drawing, where the next save keeps it. So a data
|
||||
//! link the drawing itself names is read only from the drawing's folder or a folder below it, once
|
||||
//! `..` and links are followed ([`drawing_folder`]), unless the user linked that file with
|
||||
//! DATALINK since the drawing was opened. Otherwise a drawing could copy any file it names into
|
||||
//! itself for whoever made it.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -27,15 +21,6 @@ pub fn resolve(stored: &str, document: Option<&Path>) -> Result<PathBuf, Refused
|
||||
craft_docpath::resolve_absolute(stored.trim(), document.as_deref())
|
||||
}
|
||||
|
||||
/// The folder of the drawing saved at `document` as the file system resolves it
|
||||
/// ([`std::fs::canonicalize`]: absolute, with `..` and links followed), to compare files resolved
|
||||
/// the same way with. `None` for a drawing without a file, and when its folder can't be resolved.
|
||||
pub fn drawing_folder(document: Option<&Path>) -> Option<PathBuf> {
|
||||
let document = document.filter(|d| !d.as_os_str().is_empty())?;
|
||||
let folder = std::path::absolute(document).ok()?.parent()?.to_path_buf();
|
||||
std::fs::canonicalize(folder).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -48,11 +48,6 @@ pub struct DocState {
|
||||
/// The fonts missing on Windows that a save last named: the next save names them again only
|
||||
/// when they change.
|
||||
pub(crate) fonts_noted: String,
|
||||
/// The files the user linked with DATALINK since the drawing was opened, as the file system
|
||||
/// resolves them, each with when it was last chosen (a larger number is later):
|
||||
/// DATALINKUPDATE reads these also outside the drawing's folder ([`crate::doc_path`]). Kept
|
||||
/// with the open drawing only, never saved.
|
||||
pub(crate) chosen_links: std::collections::HashMap<std::path::PathBuf, u64>,
|
||||
}
|
||||
|
||||
static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
@@ -82,7 +77,6 @@ impl DocState {
|
||||
ucs_tilted_noted: false,
|
||||
erased: Default::default(),
|
||||
fonts_noted: String::new(),
|
||||
chosen_links: Default::default(),
|
||||
}
|
||||
}
|
||||
/// The drawing has changes not saved to its file, or the Block Editor has changes not yet
|
||||
|
||||
@@ -202,7 +202,6 @@ pub const NO_FILES: &[&str] = &[
|
||||
"dim",
|
||||
"mleader",
|
||||
"leader",
|
||||
"qleader",
|
||||
"dimstyle.update",
|
||||
"dimoverride",
|
||||
"dimreassociate",
|
||||
@@ -359,7 +358,6 @@ pub const NO_FILES: &[&str] = &[
|
||||
"laymrg",
|
||||
"laydel",
|
||||
"layout.new",
|
||||
"layout.newarea",
|
||||
"layout.delete",
|
||||
"layout.rename",
|
||||
"layout.copy",
|
||||
|
||||
@@ -379,11 +379,6 @@ impl Session {
|
||||
v.height / self.viewport_px.1.max(1.0)
|
||||
}
|
||||
|
||||
/// The running interactive command id, or `None` if the command line is idle.
|
||||
pub fn active_command_id(&self) -> Option<&str> {
|
||||
self.running.as_ref().map(|r| r.id.as_str())
|
||||
}
|
||||
|
||||
/// Serializable summary for inspect/automation.
|
||||
pub fn summary(&self) -> Value {
|
||||
let docs: Vec<Value> = self
|
||||
|
||||
@@ -143,8 +143,7 @@ pub struct LispState {
|
||||
/// the step is charged it without charging the enclosing callback a second time.
|
||||
pub(crate) callback_work: u64,
|
||||
/// The `callback_used` value the callback running now (and so every one it calls) must not
|
||||
/// pass: the lowest of its own and its callers' allowances, and of what is left to an
|
||||
/// expression typed at a prompt.
|
||||
/// pass: the lowest of its own and its callers' allowances.
|
||||
pub(crate) callback_ceiling: Option<u64>,
|
||||
}
|
||||
|
||||
@@ -201,9 +200,6 @@ struct Run {
|
||||
inputs: std::collections::VecDeque<Value>,
|
||||
/// Run to the end without waiting (programmatic calls): `get…` without an input gets nil.
|
||||
blocking: bool,
|
||||
/// An expression typed at a command's prompt ([`Session::lisp_eval_answer`]): blocking, with
|
||||
/// [`ANSWER_CAP`] steps instead of [`BLOCKING_CAP`].
|
||||
answer: bool,
|
||||
/// Steps taken, for the cap on blocking runs.
|
||||
steps: u64,
|
||||
/// The `*error*` handler is the one running.
|
||||
@@ -219,10 +215,6 @@ struct Run {
|
||||
const SLICE: u64 = 400_000;
|
||||
/// Steps a blocking run (a programmatic call) may take before it is stopped.
|
||||
const BLOCKING_CAP: u64 = 500_000_000;
|
||||
/// Steps an expression typed at a command's prompt may take, the callbacks it runs included. It
|
||||
/// runs blocking, since its value is the prompt's answer, so the interface draws no frame and
|
||||
/// Esc doesn't reach it until it ends; a routine at `Command:` runs a slice per frame instead.
|
||||
const ANSWER_CAP: u64 = 20_000_000;
|
||||
|
||||
impl Session {
|
||||
/// The LISP environment of the active drawing.
|
||||
@@ -280,19 +272,12 @@ impl Session {
|
||||
inputs: Vec<Value>,
|
||||
) -> crate::Result<Option<std::result::Result<Value, String>>> {
|
||||
let forms = read::read_all(src).map_err(|e| crate::EngineError::Other(format!("; error: {}", e.msg)))?;
|
||||
self.lisp_start(Machine::forms(forms), print, blocking, inputs, "LISP".into(), false)
|
||||
}
|
||||
|
||||
/// Evaluate an expression typed at a command's prompt, whose value is the answer: it runs to
|
||||
/// the end as a programmatic call does, within [`ANSWER_CAP`] steps.
|
||||
pub(crate) fn lisp_eval_answer(&mut self, src: &str) -> crate::Result<Option<std::result::Result<Value, String>>> {
|
||||
let forms = read::read_all(src).map_err(|e| crate::EngineError::Other(format!("; error: {}", e.msg)))?;
|
||||
self.lisp_start(Machine::forms(forms), false, true, Vec::new(), "LISP".into(), true)
|
||||
self.lisp_start(Machine::forms(forms), print, blocking, inputs, "LISP".into())
|
||||
}
|
||||
|
||||
/// Call a LISP function (`c:` commands typed at the command line).
|
||||
fn lisp_call(&mut self, f: Value, label: String) -> crate::Result<Option<std::result::Result<Value, String>>> {
|
||||
self.lisp_start(Machine::calling(f, Vec::new()), false, false, Vec::new(), label, false)
|
||||
self.lisp_start(Machine::calling(f, Vec::new()), false, false, Vec::new(), label)
|
||||
}
|
||||
|
||||
fn lisp_start(
|
||||
@@ -302,7 +287,6 @@ impl Session {
|
||||
blocking: bool,
|
||||
inputs: Vec<Value>,
|
||||
label: String,
|
||||
answer: bool,
|
||||
) -> crate::Result<Option<std::result::Result<Value, String>>> {
|
||||
if self.lisp.active {
|
||||
return Err(crate::EngineError::Other("a LISP routine is already running".into()));
|
||||
@@ -321,7 +305,6 @@ impl Session {
|
||||
before,
|
||||
inputs: inputs.into(),
|
||||
blocking,
|
||||
answer,
|
||||
steps: 0,
|
||||
handler: false,
|
||||
string_bytes: 0,
|
||||
@@ -385,10 +368,6 @@ impl Session {
|
||||
// [`Session::typed`] first, never opens a dialog. Restored after the slice, a panic
|
||||
// in it included, so a person's later command keeps its own origin.
|
||||
let program_input = std::mem::replace(&mut self.program_input, true);
|
||||
// Set for every slice (callbacks run only inside one). An answer's callbacks
|
||||
// (`vl-sort`'s comparator…) run inside one of its steps: they share what is left of
|
||||
// its allowance instead of each taking a callback's own.
|
||||
self.lisp.callback_ceiling = run.answer.then(|| self.lisp.callback_used.saturating_add(ANSWER_CAP.saturating_sub(run.steps)));
|
||||
let outcome = {
|
||||
let machine = &mut run.machine;
|
||||
let mut ctx = Ctx { s: self, env: &mut env, depth: 0 };
|
||||
@@ -416,21 +395,9 @@ impl Session {
|
||||
// The work the slice did, which one step can take far past the slice. After a panic
|
||||
// `used` is still the previous slice's; the run ends with the error anyway.
|
||||
run.steps = run.steps.saturating_add(run.machine.used);
|
||||
// An answer that failed past its cap was stopped by the cap too: a callback that ran
|
||||
// out of what was left ends here past the cap, since the step that called it counts.
|
||||
let past_cap = if run.answer {
|
||||
run.steps > ANSWER_CAP && matches!(outcome, Outcome::Wait(_) | Outcome::Error(_))
|
||||
} else {
|
||||
run.steps > BLOCKING_CAP && matches!(outcome, Outcome::Wait(_))
|
||||
};
|
||||
if run.blocking && past_cap {
|
||||
let msg = if run.answer {
|
||||
format!("expression at a prompt stopped after {ANSWER_CAP} steps; run long routines at Command:, where Esc stops them")
|
||||
} else {
|
||||
format!("routine stopped after {BLOCKING_CAP} steps")
|
||||
};
|
||||
if run.blocking && run.steps > BLOCKING_CAP && matches!(outcome, Outcome::Wait(_)) {
|
||||
self.lisp.run = Some(run);
|
||||
self.lisp_error(LispError::quit(msg));
|
||||
self.lisp_error(LispError::quit(format!("routine stopped after {BLOCKING_CAP} steps")));
|
||||
return;
|
||||
}
|
||||
match outcome {
|
||||
|
||||
@@ -205,8 +205,6 @@ pub(super) fn float(a: &[Value]) -> R {
|
||||
Ok(Value::Real(num(&a[0])?))
|
||||
}
|
||||
|
||||
/// The greatest common divisor. The one past 32 bits, 2147483648 (of -2147483648 and 0 or
|
||||
/// itself), is a real, as the reader and `fix` give such a number, not the largest integer.
|
||||
pub(super) fn gcd(a: &[Value]) -> R {
|
||||
arity(a, 2, 2)?;
|
||||
let (mut x, mut y) = (i64::from(int(&a[0])?).abs(), i64::from(int(&a[1])?).abs());
|
||||
@@ -218,7 +216,7 @@ pub(super) fn gcd(a: &[Value]) -> R {
|
||||
x = y;
|
||||
y = t;
|
||||
}
|
||||
Ok(i32::try_from(x).map_or(Value::Real(x as f64), Value::Int))
|
||||
Ok(Value::Int(i32::try_from(x).unwrap_or(i32::MAX)))
|
||||
}
|
||||
|
||||
pub(super) fn logand(a: &[Value]) -> R {
|
||||
|
||||
@@ -51,20 +51,13 @@ pub(super) fn itoa(a: &[Value]) -> R {
|
||||
Ok(Value::str(&int(&a[0])?.to_string()))
|
||||
}
|
||||
|
||||
/// C's `atoi`: leading blanks, a sign, digits; 0 when there are none. Digits past the 32-bit
|
||||
/// range give a real, the number `atof` reads from them, as the reader gives one for such a
|
||||
/// literal: neither wrapped nor clamped to an integer.
|
||||
/// C's `atoi`: leading blanks, a sign, digits; 0 when there are none.
|
||||
pub(super) fn atoi(a: &[Value]) -> R {
|
||||
arity(a, 1, 1)?;
|
||||
let s = string(&a[0])?;
|
||||
let t = s.trim_start();
|
||||
let end = t.char_indices().take_while(|(i, c)| c.is_ascii_digit() || (*i == 0 && (*c == '-' || *c == '+'))).count();
|
||||
let digits = t.get(..end).unwrap_or_default();
|
||||
match digits.parse::<i32>() {
|
||||
Ok(n) => Ok(Value::Int(n)),
|
||||
Err(_) if digits.bytes().any(|b| b.is_ascii_digit()) => atof(&[Value::str(digits)]),
|
||||
Err(_) => Ok(Value::Int(0)),
|
||||
}
|
||||
Ok(Value::Int(t.get(..end).and_then(|n| n.parse::<i64>().ok()).map(|n| n as i32).unwrap_or(0)))
|
||||
}
|
||||
|
||||
/// C's `atof`: the number token at the start; 0.0 when there is none.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user